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) patterns.append(p) vecs = [] if args.char_weights is not None: weightmodel = word_vector.WeightModel(char_weights=args.char_weights) vecklas = {'counts': word_vector.CountsWeight, 'freqs': word_vector.FreqsWeight}[args.vector] kwargs = {'seq_lengths': seq_records.length_list, 'weightmodel': weightmodel} else: vecklas = {'counts': word_vector.Counts, 'freqs': word_vector.Freqs}[args.vector] kwargs = {'seq_lengths': seq_records.length_list} for p in patterns: v = vecklas(patterns=p, **kwargs) vecs.append(v) dist = word_d2.Distance(vecs) <|code_end|> . Use current file imports: (import argparse import sys from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__) and context including class names, function names, or small code snippets from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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 greater than 0") elif args.min_word_size >= args.max_word_size: parser.error("max_word_size must be greater than min_word_size") if args.char_weights: try: weights = word_vector.read_weightfile(args.char_weights) args.char_weights = weights except Exception: e = 'Invalid format for --char_weights {0}'.format( args.char_weights.name) parser.error(e) return args def main(): parser = get_parser() args = validate_args(parser) <|code_end|> with the help of current file imports: import argparse import sys from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may contain function names, class names, or code. Output only the next line.
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.add_argument('--max_word_size', '-u', help='maximum word size [default: %(default)s]', type=int, metavar="WORD_SIZE", default=3, ) veclist = ['counts', 'freqs'] group.add_argument('--vector', '-v', choices=veclist, help='choose from: {} [DEFAULT: %(default)s]'.format( ", ".join(veclist)), metavar='', default="counts") group.add_argument('--char_weights', '-W', metavar="FILE", help='''file w/ weights of background sequence characters (nt/aa)''', type=argparse.FileType('r')) 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', 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_argument('--version', action='version', <|code_end|> , generate the next line using the imports in this file: import argparse import sys from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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 exit") group.add_argument('--version', action='version', 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() try: args.alphabet = get_alphabet(args.molecule) except KeyError: parser.error("Unknown alphabet {}".format(args.molecule)) return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) <|code_end|> , determine the next line of code. You have imports: import argparse import sys from alfpy import bbc from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.utils.data.seqcontent import get_alphabet from alfpy.version import __version__ and context (class names, function names, or code) available: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/utils/data/seqcontent.py # def get_alphabet(mol): # return ALPHABET[mol] # # Path: alfpy/version.py . Output only the next line.
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(__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() try: args.alphabet = get_alphabet(args.molecule) except KeyError: parser.error("Unknown alphabet {}".format(args.molecule)) return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) vector = bbc.create_vectors(seq_records, args.k, alphabet=args.alphabet) dist = bbc.Distance(vector) <|code_end|> . Use current file imports: import argparse import sys from alfpy import bbc from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.utils.data.seqcontent import get_alphabet from alfpy.version import __version__ and context (classes, functions, or code) from other files: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/utils/data/seqcontent.py # def get_alphabet(mol): # return ALPHABET[mol] # # Path: alfpy/version.py . Output only the next line.
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", action="help", help="show this help message and exit") group.add_argument('--version', action='version', 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() try: args.alphabet = get_alphabet(args.molecule) except KeyError: parser.error("Unknown alphabet {}".format(args.molecule)) return args def main(): parser = get_parser() args = validate_args(parser) <|code_end|> , predict the immediate next line with the help of imports: import argparse import sys from alfpy import bbc from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.utils.data.seqcontent import get_alphabet from alfpy.version import __version__ and context (classes, functions, sometimes code) from other files: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/utils/data/seqcontent.py # def get_alphabet(mol): # return ALPHABET[mol] # # Path: alfpy/version.py . Output only the next line.
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') group.add_argument('--k', '-k', help='''maximum distance to observe correlation between bases [default: %(default)s]''', type=int, default=10, metavar="INT") group.add_argument('--out', '-o', help="output filename", 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.add_argument("-h", "--help", action="help", help="show this help message and exit") group.add_argument('--version', action='version', 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() try: <|code_end|> , generate the next line using the imports in this file: import argparse import sys from alfpy import bbc from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.utils.data.seqcontent import get_alphabet from alfpy.version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/utils/data/seqcontent.py # def get_alphabet(mol): # return ALPHABET[mol] # # Path: alfpy/version.py . Output only the next line.
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 ARGUMENTS') group.add_argument('--fasta', '-f', help='input FASTA sequence filename', required=True, 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') group.add_argument('--k', '-k', help='''maximum distance to observe correlation between bases [default: %(default)s]''', type=int, default=10, metavar="INT") group.add_argument('--out', '-o', help="output filename", 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.add_argument("-h", "--help", action="help", help="show this help message and exit") group.add_argument('--version', action='version', <|code_end|> , generate the next line using the imports in this file: import argparse import sys from alfpy import bbc from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.utils.data.seqcontent import get_alphabet from alfpy.version import __version__ and context (functions, classes, or occasionally code) from other files: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/utils/data/seqcontent.py # def get_alphabet(mol): # return ALPHABET[mol] # # Path: alfpy/version.py . Output only the next line.
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 = [] self.counts = [] self.freqs = [] for i in range(1, 5): p = word_pattern.create(self.pep_records.seq_list, i) self.patterns.append(p) c = word_vector.Counts(self.pep_records.length_list, p) self.counts.append(c) f = word_vector.Freqs(self.pep_records.length_list, p) self.freqs.append(f) def test_counts_from1_to4(self): <|code_end|> , predict the next line using imports from the current file: import unittest from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from . import utils and context including class names, function names, and sometimes code from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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 = [] self.counts = [] self.freqs = [] for i in range(1, 5): <|code_end|> , predict the next line using imports from the current file: import unittest from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from . import utils and context including class names, function names, and sometimes code from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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 = [] self.counts = [] self.freqs = [] for i in range(1, 5): p = word_pattern.create(self.pep_records.seq_list, i) self.patterns.append(p) <|code_end|> , predict the next line using imports from the current file: import unittest from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from . import utils and context including class names, function names, and sometimes code from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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.freqs = [] for i in range(1, 5): p = word_pattern.create(self.pep_records.seq_list, i) self.patterns.append(p) c = word_vector.Counts(self.pep_records.length_list, p) self.counts.append(c) f = word_vector.Freqs(self.pep_records.length_list, p) self.freqs.append(f) def test_counts_from1_to4(self): dist = word_d2.Distance(self.counts) <|code_end|> . Write the next line using the current file imports: import unittest from alfpy import word_d2 from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distmatrix from . import utils and context from other files: # Path: alfpy/word_d2.py # class Distance: # def __init__(self, vector_list): # def pwdist_d2(self, seqidx1, seqidx2): # def pwdist_d2_squareroot(self, seqidx1, seqidx2): # def set_disttype(self, disttype): # def main(): # # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/word_vector.py # class Counts: # class Bools(Counts): # class Freqs(Counts): # class FreqsStd(Freqs): # class WeightModel: # class CountsWeight(Counts): # class FreqsWeight(Freqs): # class WordModel: # class EqualFreqs(WordModel): # class EquilibriumFreqs(WordModel): # class Composition(Counts): # def __init__(self, seq_lengths, patterns): # def _get_counts_occurrence(seq_count, patterns): # def __getitem__(self, seqidx): # def __str__(self): # def format(self, decimal_places=3): # def __init__(self, seq_lengths, patterns): # def __init__(self, seq_lengths, patterns): # def __relative_freqs(self): # def __init__(self, seq_lengths, patterns, freqmodel): # def __overlaps(self, freqmodel): # def __standardize_freqs(self, freqmodel): # def __init__(self, char_weights, wtype='content'): # def content(self, vector, patterns): # def __init__(self, seq_lengths, patterns, weightmodel): # def __init__(self, seq_lengths, patterns, weightmodel): # def probabilities(self, word): # def overlap_capability(self, word): # def var(self, word, seq_len, word_len=None, overlap_capability=None, # word_probs=None): # def __init__(self, alphabet_size): # def probabilities(self, word): # def __init__(self, equilibrium_frequencies): # def probabilities(self, word): # def __init__(self, seq_lengths, patterns, patterns1, patterns2): # def __check_patlen(self): # def __markov_chain_freqs(self, seqnum, seqlen, patnum, patlen, pattern): # def __composition(self, seqnum, seqlen): # def _read_charval_file(handle): # def main(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): , which may include functions, classes, or code. Output only the next line.
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 [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_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) <|code_end|> with the help of current file imports: import argparse import sys from alfpy import ncd from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may contain function names, class names, or code. Output only the next line.
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.add_argument("-h", "--help", action="help", help="show this help message and exit") group.add_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) dist = ncd.Distance(seq_records) <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import sys from alfpy import ncd from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py which might include code, classes, or functions. Output only the next line.
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', 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_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) <|code_end|> . Use current file imports: import argparse import sys from alfpy import ncd from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context (classes, functions, or code) from other files: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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=False, prog='calc_ncd.py' ) 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 = 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', 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_argument('--version', action='version', <|code_end|> . Use current file imports: import argparse import sys from alfpy import ncd from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context (classes, functions, or code) from other files: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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_argument('--version', action='version', 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' and args.ndim is None: parser.error("--vector 2DMV requires the --ndim") # TODO: mk as a range # stackoverflow.com/questions/18700634/python-argparse-integer-condition-12 return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) if args.vector == '2DSV': <|code_end|> with the help of current file imports: import argparse import sys from alfpy import graphdna from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may contain function names, class names, or code. Output only the next line.
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' and args.ndim is None: parser.error("--vector 2DMV requires the --ndim") # TODO: mk as a range # stackoverflow.com/questions/18700634/python-argparse-integer-condition-12 return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) if args.vector == '2DSV': vector = graphdna.create_2DSGraphVectors(seq_records) elif args.vector == '2DNV': vector = graphdna.create_2DNGraphVectors(seq_records) else: vector = graphdna.create_2DMGraphVectors(seq_records, args.ndim) dist = graphdna.Distance(vector) <|code_end|> . Write the next line using the current file imports: import argparse import sys from alfpy import graphdna from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may include functions, classes, or code. Output only the next line.
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("-h", "--help", action="help", help="show this help message and exit") group.add_argument('--version', action='version', 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' and args.ndim is None: parser.error("--vector 2DMV requires the --ndim") # TODO: mk as a range # stackoverflow.com/questions/18700634/python-argparse-integer-condition-12 return args def main(): parser = get_parser() args = validate_args(parser) <|code_end|> with the help of current file imports: import argparse import sys from alfpy import graphdna from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may contain function names, class names, or code. Output only the next line.
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_argument_group('REQUIRED ARGUMENTS') group.add_argument('--fasta', '-f', help='input FASTA sequence filename', required=True, type=argparse.FileType('r'), metavar="FILE") group = parser.add_argument_group('OPTIONAL ARGUMENTS') group.add_argument('--vector', '-v', choices=['2DSV', '2DNV', '2DMV'], help='vector type [default: %(default)s]', default='2DNV') group.add_argument('--ndim', '-n', type=int, metavar='N', help='''number of dimensions representing a sequence. (required if --vector 2DMV) [default: %(default)s]''', default=10) 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', 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_argument('--version', action='version', <|code_end|> with the help of current file imports: import argparse import sys from alfpy import graphdna from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may contain function names, class names, or code. Output only the next line.
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', 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_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) <|code_end|> , predict the immediate next line with the help of imports: import argparse import sys from alfpy import lempelziv from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context (classes, functions, sometimes code) from other files: # Path: alfpy/lempelziv.py # def complexity(s): # def complexity1(seq): # def is_reproducible(seq, index, hist_len, last_match=0): # def __init__(self, seq_records, disttype='d1_star'): # def __precompute_complexity(self): # def __get_complexity(self, seq1idx, seq2idx): # def pwdist_d(self, seq1idx, seq2idx): # def pwdist_d_star(self, seq1idx, seq2idx): # def pwdist_d1(self, seq1idx, seq2idx): # def pwdist_d1_star(self, seq1idx, seq2idx): # def pwdist_d1_star2(self, seq1idx, seq2idx): # def set_disttype(self, disttype): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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 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_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) seq_records = seqrecords.read_fasta(args.fasta) dist = lempelziv.Distance(seq_records, args.distance) <|code_end|> , predict the next line using imports from the current file: import argparse import sys from alfpy import lempelziv from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and context including class names, function names, and sometimes code from other files: # Path: alfpy/lempelziv.py # def complexity(s): # def complexity1(seq): # def is_reproducible(seq, index, hist_len, last_match=0): # def __init__(self, seq_records, disttype='d1_star'): # def __precompute_complexity(self): # def __get_complexity(self, seq1idx, seq2idx): # def pwdist_d(self, seq1idx, seq2idx): # def pwdist_d_star(self, seq1idx, seq2idx): # def pwdist_d1(self, seq1idx, seq2idx): # def pwdist_d1_star(self, seq1idx, seq2idx): # def pwdist_d1_star2(self, seq1idx, seq2idx): # def set_disttype(self, disttype): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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='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 exit") group.add_argument('--version', action='version', 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() return args def main(): parser = get_parser() args = validate_args(parser) <|code_end|> using the current file's imports: import argparse import sys from alfpy import lempelziv from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and any relevant context from other files: # Path: alfpy/lempelziv.py # def complexity(s): # def complexity1(seq): # def is_reproducible(seq, index, hist_len, last_match=0): # def __init__(self, seq_records, disttype='d1_star'): # def __precompute_complexity(self): # def __get_complexity(self, seq1idx, seq2idx): # def pwdist_d(self, seq1idx, seq2idx): # def pwdist_d_star(self, seq1idx, seq2idx): # def pwdist_d1(self, seq1idx, seq2idx): # def pwdist_d1_star(self, seq1idx, seq2idx): # def pwdist_d1_star2(self, seq1idx, seq2idx): # def set_disttype(self, disttype): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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_group('REQUIRED ARGUMENTS') group.add_argument('--fasta', '-f', help='input FASTA sequence filename', required=True, type=argparse.FileType('r'), metavar="FILE") group = parser.add_argument_group('OPTIONAL ARGUMENTS') distlist = ['d', 'd_star', 'd1', 'd1_star', 'd1_star2'] group.add_argument('--distance', '-d', choices=distlist, help='choose from: {} [DEFAULT: %(default)s]'.format( ", ".join(distlist)), metavar='', default="d1_star2") 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', 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_argument('--version', action='version', <|code_end|> using the current file's imports: import argparse import sys from alfpy import lempelziv from alfpy.utils import distmatrix from alfpy.utils import seqrecords from alfpy.version import __version__ and any relevant context from other files: # Path: alfpy/lempelziv.py # def complexity(s): # def complexity1(seq): # def is_reproducible(seq, index, hist_len, last_match=0): # def __init__(self, seq_records, disttype='d1_star'): # def __precompute_complexity(self): # def __get_complexity(self, seq1idx, seq2idx): # def pwdist_d(self, seq1idx, seq2idx): # def pwdist_d_star(self, seq1idx, seq2idx): # def pwdist_d1(self, seq1idx, seq2idx): # def pwdist_d1_star(self, seq1idx, seq2idx): # def pwdist_d1_star2(self, seq1idx, seq2idx): # def set_disttype(self, disttype): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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: parser.error("Teiresias requires --k") if args.word_size < 2: parser.error("Teiresias requires --word_size to be >= 2") if args.l < 2: parser.error("--l must be at least 2") if args.l > args.word_size: parser.error("--word_size must be >= than --l") elif args.word_size < 1: parser.error("--word_size must be >= 1") return args def main(): parser = get_parser() args = validate_args(parser) if args.teiresias: args.fasta.close() <|code_end|> . Use current file imports: (import argparse import sys from alfpy import word_pattern from alfpy.utils import seqrecords from alfpy.version import __version__) and context including class names, function names, or small code snippets from other files: # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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: parser.error("Teiresias requires --word_size to be >= 2") if args.l < 2: parser.error("--l must be at least 2") if args.l > args.word_size: parser.error("--word_size must be >= than --l") elif args.word_size < 1: parser.error("--word_size must be >= 1") return args def main(): parser = get_parser() args = validate_args(parser) if args.teiresias: args.fasta.close() p = word_pattern.run_teiresias(args.fasta.name, w=args.word_size, l=args.l, k=args.k, output_filename=args.out) else: <|code_end|> . Use current file imports: (import argparse import sys from alfpy import word_pattern from alfpy.utils import seqrecords from alfpy.version import __version__) and context including class names, function names, or small code snippets from other files: # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py . Output only the next line.
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', required=True, type=int, metavar="k", help='word size (>=1)') group = parser.add_argument_group('OPTIONAL ARGUMENTS') group.add_argument('--word_position', '-p', action="store_true", help='''report word positions in output''') group.add_argument('--out', '-o', help="output pattern filename", metavar="FILE") t = ' Teiresias options' d = ' more info @ https://cm.jefferson.edu/data-tools-downloads/' d += 'teiresias-code/\n' group = parser.add_argument_group(t, d) group.add_argument('--teiresias', '-t', action="store_true", help='''Teiresias program creates word patterns. [by default: disabled]''', ) group.add_argument('--l', '-l', type=int, help='minimum number of literals and/or brackets') group.add_argument('--k', '-k', type=int, help='minimum support that any word can have') 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', <|code_end|> . Write the next line using the current file imports: import argparse import sys from alfpy import word_pattern from alfpy.utils import seqrecords from alfpy.version import __version__ and context from other files: # Path: alfpy/word_pattern.py # class Pattern: # def __init__(self, pat_list, occr_list, pos_list=None): # def _alfree_format(self): # def _teiresias_format(self): # def format(self, formattype=None): # def reduce_alphabet(self, alphabet_dict): # def merge_revcomp(self): # def revcomp(s): # def __repr__(self): # def __str__(self): # def _create_wordpattern(seq_list, k): # def _create_wordpattern_positions(seq_list, k): # def create(seq_list, word_size=1, wordpos=False): # def create_from_fasta(handle, word_size=1, wordpos=False): # def create_from_bigfasta(filename, k=1): # def run_teiresias(input_filename, w=2, l=2, k=2, output_filename=None): # def read(handle): # def main(): # # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): # # Path: alfpy/version.py , which may include functions, classes, or code. Output only the next line.
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_end|> . Use current file imports: (import unittest from alfpy import ncd from alfpy.utils import distmatrix from . import utils) and context including class names, function names, or small code snippets from other files: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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.complexity(seq) self.assertEqual(c, 26) def test_complexity2(self): seq = 'MFTDNAKIIIVQLNASVEINCTRPNNNTR' c = ncd.complexity(seq) self.assertEqual(c, 37) def test_complexities(self): dist = ncd.Distance(self.pep_records) exp = [ ((0,), 63.0), ((0, 1), 77.0), ((0, 2), 85.0), ((0, 3), 70.0), ((1,), 60.0), ((1, 2), 78.0), ((1, 3), 65.0), ((2,), 61.0), ((2, 3), 66.0), ((3,), 37.0) ] self.assertEqual(exp, sorted(dist._complexity.items())) def test_distance(self): dist = ncd.Distance(self.pep_records) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from alfpy import ncd from alfpy.utils import distmatrix from . import utils and context: # Path: alfpy/ncd.py # def complexity(s): # def __init__(self, seq_records): # def __precompute_complexity(self): # def pairwise_distance(self, seq1idx, seq2idx): # class Distance(): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): which might include code, classes, or functions. Output only the next line.
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 import subsmat from . import utils and context: # Path: alfpy/wmetric.py # def count_seq_chars(seq, alphabet): # def freq_seq_chars(counts): # def freq_seqs_chars(seq_records, alphabet): # def __init__(self, seq_records, matrix): # def pairwise_distance(self, seqnum1, seqnum2): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/data/subsmat.py # class SubsMat: # def __init__(self, name, data, alphabet_list): # def get_alphabet_list(name): # def get(name): # def list_subsmats(): # def main(): which might include code, classes, or functions. Output only the next line.
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 = 'MKSTGWXXXXXXXOOOOOOOHFSG' 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_freq_seq_chars(self): seq = 'MKSTGWXXXXXXXOOOOOOOHFSG' l = wmetric.count_seq_chars(seq, utils.ALPHABET_PEP) freq = wmetric.freq_seq_chars(l) expfreq = [0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.1, 0.0, 0.1, 0.0, 0.1, 0.0, 0.0, 0.0, 0.2, 0.1, 0.0, 0.1, 0.0, 0.0] self.assertEqual(freq, expfreq) class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*args, **kwargs) utils.ModulesCommonTest.set_test_data() def test_wmetric_blosum62(self): # The result of this method is identical to that from decaf+py. matrix = subsmat.get('blosum62') dist = wmetric.Distance(self.pep_records, matrix) <|code_end|> . Write the next line using the current file imports: import unittest from alfpy import wmetric from alfpy.utils import distmatrix from alfpy.utils.data import subsmat from . import utils and context from other files: # Path: alfpy/wmetric.py # def count_seq_chars(seq, alphabet): # def freq_seq_chars(counts): # def freq_seqs_chars(seq_records, alphabet): # def __init__(self, seq_records, matrix): # def pairwise_distance(self, seqnum1, seqnum2): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/data/subsmat.py # class SubsMat: # def __init__(self, name, data, alphabet_list): # def get_alphabet_list(name): # def get(name): # def list_subsmats(): # def main(): , which may include functions, classes, or code. Output only the next line.
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(self): seq = 'MKSTGWXXXXXXXOOOOOOOHFSG' 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_freq_seq_chars(self): seq = 'MKSTGWXXXXXXXOOOOOOOHFSG' l = wmetric.count_seq_chars(seq, utils.ALPHABET_PEP) freq = wmetric.freq_seq_chars(l) expfreq = [0.0, 0.0, 0.0, 0.0, 0.1, 0.2, 0.1, 0.0, 0.1, 0.0, 0.1, 0.0, 0.0, 0.0, 0.2, 0.1, 0.0, 0.1, 0.0, 0.0] self.assertEqual(freq, expfreq) class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*args, **kwargs) utils.ModulesCommonTest.set_test_data() def test_wmetric_blosum62(self): # The result of this method is identical to that from decaf+py. <|code_end|> , generate the next line using the imports in this file: import unittest from alfpy import wmetric from alfpy.utils import distmatrix from alfpy.utils.data import subsmat from . import utils and context (functions, classes, or occasionally code) from other files: # Path: alfpy/wmetric.py # def count_seq_chars(seq, alphabet): # def freq_seq_chars(counts): # def freq_seqs_chars(seq_records, alphabet): # def __init__(self, seq_records, matrix): # def pairwise_distance(self, seqnum1, seqnum2): # def main(): # class Distance: # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): # # Path: alfpy/utils/data/subsmat.py # class SubsMat: # def __init__(self, name, data, alphabet_list): # def get_alphabet_list(name): # def get(name): # def list_subsmats(): # def main(): . Output only the next line.
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 next line with the help of imports: import os import unittest from alfpy import fcgr from alfpy.utils import distmatrix from . import utils and context (classes, functions, sometimes code) from other files: # Path: alfpy/fcgr.py # def fcgr_vector(dnaseq, word_size): # def create_vectors(seq_records, word_size): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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.0, 1.0, 0.0] self.assertEqual(vec, exp) def test_fcgr_vector3(self): vec = fcgr.fcgr_vector('CTAGGGAACATACCXXA', 1) self.assertEqual(vec, [3.0, 6.0, 3.0]) def test_create_vectors(self): vecs = fcgr.create_vectors(self.dna_records, 2) exp = [[0, 3, 1, 4, 0, 1, 1, 1, 1, 1, 3, 2, 4, 1, 1], [0, 0, 4, 1, 2, 2, 0, 0, 1, 4, 0, 0, 3, 1, 1], [0, 0, 2, 2, 1, 1, 0, 2, 1, 2, 0, 1, 2, 1, 0]] self.assertEqual(vecs.tolist(), exp) class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*args, **kwargs) utils.ModulesCommonTest.set_test_data() def test_distance1(self): vecs = fcgr.create_vectors(self.dna_records, 2) dist = fcgr.Distance(vecs) <|code_end|> . Use current file imports: import os import unittest from alfpy import fcgr from alfpy.utils import distmatrix from . import utils and context (classes, functions, or code) from other files: # Path: alfpy/fcgr.py # def fcgr_vector(dnaseq, word_size): # def create_vectors(seq_records, word_size): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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 test_base_base_correlation_on_dna_k1(self): seq = 'CTAGGGAACATACCA' <|code_end|> , determine the next line of code. You have imports: import unittest from alfpy import bbc from alfpy.utils import distmatrix from . import utils and context (class names, function names, or code) available: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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_vectors_on_pep_k1(self): vec = bbc.create_vectors(self.pep_records, 1, utils.ALPHABET_PEP) md5 = utils.calc_md5(vec) self.assertEqual(vec.shape, (4, 400)) self.assertEqual(md5, 'd901d93d0d71102d0727633a67fc14a3') def test_create_vectors_throws_exception(self): with self.assertRaises(Exception) as context: bbc.create_vectors(self.dna_records, 60, utils.ALPHABET_DNA) self.assertIn('Sequence too short', str(context.exception)) class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): """Shared methods and tests for Distances calculations.""" def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*args, **kwargs) utils.ModulesCommonTest.set_test_data() self.vector = bbc.create_vectors(self.dna_records, 10, utils.ALPHABET_DNA) def test_distance_dna_euclidnorm(self): dist = bbc.Distance(self.vector) <|code_end|> . Write the next line using the current file imports: import unittest from alfpy import bbc from alfpy.utils import distmatrix from . import utils and context from other files: # Path: alfpy/bbc.py # def base_base_correlation(seq, k, alphabet=None): # def create_vectors(seq_records, k=10, alphabet="ATGC"): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # L = len(alphabet) # D = l_dist_correlations - np.dot(p.T, p) # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): , which may include functions, classes, or code. Output only the next line.
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 desc', ''] self.SEQ_LIST = [ 'MEVVIRSANFTDNAKIIIVQLNASVEINCTRPNNYTRKGIRIGPGRAVYAAEEIIGDNTLKQVVTKLRE', 'MVIRSANFTDNAKIIIVQLNASVEINCTRPNNNTRKGIRIGPGRAVYAAEEIIGDIRRAHCNIS', 'MFTDNAKIIIVQLNASVEINCTRPNNNTRKGIHIGPGRAFYATGEIIGDIRQAHCNISGAKW', 'MFTDNAKIIIVQLNASVEINCTRPNNNTR' ] def _validate_seqrecords(self, rec): self.assertEqual(rec.id_list, self.ID_LIST) self.assertEqual(rec.seq_list, self.SEQ_LIST) self.assertEqual(rec.length_list, [len(s) for s in self.SEQ_LIST]) self.assertEqual(rec.count, len(self.SEQ_LIST)) def test_SeqRecords_init(self): <|code_end|> with the help of current file imports: import unittest from alfpy.utils import seqrecords from . import utils and context from other files: # Path: alfpy/utils/seqrecords.py # class SeqRecords: # def __init__(self, id_list=None, seq_list=None): # def add(self, seqid, seq): # def fasta(self, wrap=70): # def length_list(self): # def __iter__(self): # def __len__(self): # def __repr__(self): # def read_fasta(handle): # def main(): , which may contain function names, class names, or code. Output only the next line.
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): seq = 'CTAGGGAACATACCA' <|code_end|> , predict the next line using imports from the current file: import numpy as np import unittest from alfpy import graphdna from alfpy.utils import distmatrix from . import utils and context including class names, function names, and sometimes code from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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_records) md5 = utils.calc_md5(data) self.assertEqual(md5, 'e2399897bb7eaa5ca3a81c84e2eeac84') def test_create_2DMGraphVectors(self): data = graphdna.create_2DMGraphVectors(self.dna_records, 10) md5 = utils.calc_md5(data) self.assertEqual(md5, '8c7d4dca912aeaf7c88d325799dadf00') def test_create_2DNGraphVectors(self): data = graphdna.create_2DNGraphVectors(self.dna_records) md5 = utils.calc_md5(data) self.assertEqual(md5, '3211fc3837b876521a6ab8b6a22b411c') class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*args, **kwargs) utils.ModulesCommonTest.set_test_data() def test_distance_2DSG(self): data = graphdna.create_2DSGraphVectors(self.dna_records) dist = graphdna.Distance(data) <|code_end|> , generate the next line using the imports in this file: import numpy as np import unittest from alfpy import graphdna from alfpy.utils import distmatrix from . import utils and context (functions, classes, or occasionally code) from other files: # Path: alfpy/graphdna.py # def _2DSGraphVector(seq): # def _2DMGraphVector(seq, n): # def _2DNGraphVector(genomeseq): # def create_2DSGraphVectors(seq_records): # def create_2DMGraphVectors(seq_records, n): # def create_2DNGraphVectors(seq_records): # def __init__(self, vector, disttype='euclid_norm'): # def main(): # class Distance(distance.Distance): # # Path: alfpy/utils/distmatrix.py # def create(id_list, distance): # def read_highcharts_matrix(id_list, data): # def __init__(self, id_list, data): # def normalize(self): # def __iter__(self): # def writer(self, handle, f, decimal_places): # def display(self, f="phylip", decimal_places=7): # def write_to_file(self, handle, f="phylip", decimal_places=7): # def highcharts(self): # def format(self, decimal_places=7): # def min(self): # def max(self): # def is_zero(self): # def __repr__(self): # class Matrix(): . Output only the next line.
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 vectors Args: seqcount (int): number of sequences pattern (obj: word_pattern.Pattern) Returns: ndarray: matrix of RTD vectors (shape: number of seqs, doubled number of words) """ words = pattern.pat_list data = np.zeros(shape=(seqcount, len(words) * 2)) for wordidx in range(len(words)): for seqidx in pattern.pos_list[wordidx]: word_positions = pattern.pos_list[wordidx][seqidx] mean, std = calc_rtd(word_positions) data[seqidx, wordidx * 2] = mean data[seqidx, wordidx * 2 + 1] = std return data <|code_end|> , predict the next line using imports from the current file: import numpy as np from .utils import distance from .utils.seqrecords import main from . import word_pattern from .utils import distmatrix and context including class names, function names, and sometimes code from other files: # Path: alfpy/utils/distance.py # class Distance(object): # def __getitem__(self, seqnum): # def get_disttypes(cls): # def set_disttype(self, disttype): # def __init__(self, vector, disttype): # def pwdist_euclid_squared(self, seq1idx, seq2idx): # def pwdist_euclid_norm(self, seq1idx, seq2idx): # def pwdist_google(self, seq1idx, seq2idx): . Output only the next line.
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: tuple of four numbers Examples: >>> u = np.array([True, False, True]) >>> v = np.array([True, True, False]) >>> print(_nbool_correspond_all(u, v)) (0, 1, 1, 1) """ not_u = ~u not_v = ~v nff = (not_u & not_v).sum() nft = (not_u & v).sum() ntf = (u & not_v).sum() ntt = (u & v).sum() return (nff, nft, ntf, ntt) <|code_end|> , determine the next line of code. You have imports: import numpy as np from .utils import distance from .utils.seqrecords import SeqRecords from . import word_vector from . import word_pattern from .utils import distmatrix and context (class names, function names, or code) available: # Path: alfpy/utils/distance.py # class Distance(object): # def __getitem__(self, seqnum): # def get_disttypes(cls): # def set_disttype(self, disttype): # def __init__(self, vector, disttype): # def pwdist_euclid_squared(self, seq1idx, seq2idx): # def pwdist_euclid_norm(self, seq1idx, seq2idx): # def pwdist_google(self, seq1idx, seq2idx): . Output only the next line.
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 ### def _get_words_from_dataset(dataset): """Return a set of all words in a dataset. :param dataset: A list of tuples of the form ``(words, label)`` where ``words`` is either a string of a list of tokens. """ # Words may be either a string or a list of tokens. Return an iterator # of tokens accordingly def tokenize(words): if isinstance(words, basestring): <|code_end|> , determine the next line of code. You have imports: from itertools import chain from textblob.utils import strip_punc from textblob.decorators import cached_property from textblob_de.tokenizers import word_tokenize from textblob_de.compat import basestring import nltk import textblob.formats as formats and context (class names, function names, or code) available: # Path: textblob_de/tokenizers.py # def word_tokenize(self, text, include_punc=True): # """The Treebank tokenizer uses regular expressions to tokenize text as # in Penn Treebank. # # It assumes that the text has already been segmented into sentences, # e.g. using ``self.sent_tokenize()``. # # This tokenizer performs the following steps: # # - split standard contractions, e.g. ``don't`` -> ``do n't`` and ``they'll`` -> ``they 'll`` # - treat most punctuation characters as separate tokens # - split off commas and single quotes, when followed by whitespace # - separate periods that appear at the end of line # # Source: NLTK's docstring of ``TreebankWordTokenizer`` (accessed: 02/10/2014) # # """ # #: Do not process empty strings (Issue #3) # if text.strip() == "": # return [] # _tokens = self.word_tok.tokenize(text) # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) # # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): . Output only the next line.
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 (``textblob``) """ from __future__ import absolute_import ### Basic feature extractors ### def _get_words_from_dataset(dataset): """Return a set of all words in a dataset. :param dataset: A list of tuples of the form ``(words, label)`` where ``words`` is either a string of a list of tokens. """ # Words may be either a string or a list of tokens. Return an iterator # of tokens accordingly def tokenize(words): <|code_end|> , predict the immediate next line with the help of imports: from itertools import chain from textblob.utils import strip_punc from textblob.decorators import cached_property from textblob_de.tokenizers import word_tokenize from textblob_de.compat import basestring import nltk import textblob.formats as formats and context (classes, functions, sometimes code) from other files: # Path: textblob_de/tokenizers.py # def word_tokenize(self, text, include_punc=True): # """The Treebank tokenizer uses regular expressions to tokenize text as # in Penn Treebank. # # It assumes that the text has already been segmented into sentences, # e.g. using ``self.sent_tokenize()``. # # This tokenizer performs the following steps: # # - split standard contractions, e.g. ``don't`` -> ``do n't`` and ``they'll`` -> ``they 'll`` # - treat most punctuation characters as separate tokens # - split off commas and single quotes, when followed by whitespace # - separate periods that appear at the end of line # # Source: NLTK's docstring of ``TreebankWordTokenizer`` (accessed: 02/10/2014) # # """ # #: Do not process empty strings (Issue #3) # if text.strip() == "": # return [] # _tokens = self.word_tok.tokenize(text) # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) # # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): . Output only the next line.
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> # """Default parsers for German. >>> from textblob_de.parsers import PatternParser or >>> from textblob_de import PatternParser """ from __future__ import absolute_import <|code_end|> , predict the next line using imports from the current file: import string from textblob.base import BaseParser from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer and context including class names, function names, and sometimes code from other files: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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.PatternTokenizer>`. :param tokenize: (optional) Split punctuation marks from words? (Default ``True``) :param pprint: (optional) Use ``pattern``'s ``pprint`` function to display parse trees (Default ``False``) :param tags: (optional) Parse part-of-speech tags? (NN, JJ, ...) (Default ``True``) :param chunks: (optional) Parse chunks? (NP, VP, PNP, ...) (Default ``True``) :param relations: (optional) Parse chunk relations? (-SBJ, -OBJ, ...) (Default ``False``) :param lemmata: (optional) Parse lemmata? (schönes => schön) (Default ``False``) :param encoding: (optional) Input string encoding. (Default ``utf-8``) :param tagset: (optional) Penn Treebank II (default) or ('penn'|'universal'|'stts'). ''' def __init__( self, tokenizer=None, tokenize=True, pprint=False, tags=True, chunks=True, relations=False, lemmata=False, encoding='utf-8', tagset=None): <|code_end|> . Use current file imports: (import string from textblob.base import BaseParser from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer) and context including class names, function names, or small code snippets from other files: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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 subprocess import time from textblob_de.compat import _open, get_external_executable and context from other files: # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): , which may contain function names, class names, or code. Output only the next line.
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("-->"): f.write(3 * "\t") if format_as_code: f.write("\t" + line.strip()) f.write("\n") else: f.write(line) f.write("\n") if "README" in path_to_rst: f.write(get_rst_title("Credits", "^")) f.write(get_credits()) print("\ncmd:{} in dir:{} --> RST generated:\n\t{}\n\n".format( help_cmd, cwd, path_to_rst)) def update_docs(readme=True, makefiles=True): """Update documentation (ready for publishing new release) Usually called by ``make docs`` :param bool make_doc: generate DOC page from Makefile help messages """ if readme: <|code_end|> , predict the next line using imports from the current file: import os import re import subprocess import time from textblob_de.compat import _open, get_external_executable and context including class names, function names, and sometimes code from other files: # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): . Output only the next line.
_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 = get_argv() success = nose.run(argv=args) sys.exit(0) if success else sys.exit(1) def get_argv(): args = [sys.argv[0], ] attr_conditions = [] # Use nose's attribselect plugin to filter tests if "force-all" in sys.argv: # Don't exclude any tests return args if PY26: # Exclude tests that don't work on python2.6 attr_conditions.append("not py27_only") <|code_end|> . Use current file imports: import nose import sys from textblob_de.compat import PY2, PY26 and context (classes, functions, or code) from other files: # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # # PY26 = PY2 and int(sys.version_info[1]) < 7 . Output only the next line.
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 def main(): args = get_argv() success = nose.run(argv=args) sys.exit(0) if success else sys.exit(1) def get_argv(): args = [sys.argv[0], ] attr_conditions = [] # Use nose's attribselect plugin to filter tests if "force-all" in sys.argv: # Don't exclude any tests return args <|code_end|> . Use current file imports: (import nose import sys from textblob_de.compat import PY2, PY26) and context including class names, function names, or small code snippets from other files: # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # # PY26 = PY2 and int(sys.version_info[1]) < 7 . Output only the next line.
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()]) + line.strip().split(',')) setattr(_get_verb_lexicon, "cached", verb_lexicon) return verb_lexicon class PatternParserNPExtractor(BaseNPExtractor): """Extract noun phrases (NP) from PatternParser() output. Very naïve and resource hungry approach: * get parser output * try to correct as many obvious parser errors as you can (e.g. eliminate wrongly tagged verbs) * filter insignificant words :param tokenizer: (optional) A tokenizer instance. If ``None``, defaults to :class:`PatternTokenizer() <textblob_de.tokenizers.PatternTokenizer>`. """ def __init__(self, tokenizer=None): <|code_end|> , determine the next line of code. You have imports: import os from collections import defaultdict from textblob.base import BaseNPExtractor from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer, sent_tokenize and context (class names, function names, or code) available: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) # # @requires_nltk_corpus # def sent_tokenize(self, text, **kwargs): # """NLTK's sentence tokenizer (currently PunktSentenceTokenizer). # # Uses an unsupervised algorithm to build a model for abbreviation # words, collocations, and words that start sentences, then uses # that to find sentence boundaries. # # """ # sentences = self.sent_tok.tokenize( # text, # realign_boundaries=kwargs.get( # "realign_boundaries", # True)) # return sentences . Output only the next line.
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. 'welcher die ...' if _np[0] in INSIGNIFICANT: _np.pop(0) except IndexError: _np = [] if len(_np) > 0: _filtered.append(" ".join(_np)) return _filtered def _parse_text(self, text): """Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/(LEMMA) (separated by a forward slash '/') :param str text: A string. """ if isinstance(self.tokenizer, PatternTokenizer): parsed_text = pattern_parse(text, tokenize=True, lemmata=False) else: _tokenized = [] <|code_end|> , predict the next line using imports from the current file: import os from collections import defaultdict from textblob.base import BaseNPExtractor from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer, sent_tokenize and context including class names, function names, and sometimes code from other files: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) # # @requires_nltk_corpus # def sent_tokenize(self, text, **kwargs): # """NLTK's sentence tokenizer (currently PunktSentenceTokenizer). # # Uses an unsupervised algorithm to build a model for abbreviation # words, collocations, and words that start sentences, then uses # that to find sentence boundaries. # # """ # sentences = self.sent_tok.tokenize( # text, # realign_boundaries=kwargs.get( # "realign_boundaries", # True)) # return sentences . Output only the next line.
_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 __future__ import absolute_import find_sentences = pattern_text.find_tokens replacements = pattern_text.replacements PUNCTUATION = string.punctuation <|code_end|> , continue by predicting the next line. Consider current file imports: import string import nltk from itertools import chain from textblob.utils import strip_punc from textblob.base import BaseTokenizer from textblob.decorators import requires_nltk_corpus from textblob_de.packages import pattern_de from textblob_de.packages import pattern_text and context: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) which might include code, classes, or functions. Output only the next line.
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(__file__)) except: MODULE = "" <|code_end|> , predict the immediate next line with the help of imports: import os import string from textblob_de.base import BaseLemmatizer from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer and context (classes, functions, sometimes code) from other files: # Path: textblob_de/base.py # class BaseLemmatizer(with_metaclass(ABCMeta)): # # """Abstract base class from which all Lemmatizer classes inherit. # Descendant classes must implement a ``lemmatize(text)`` method that returns # a WordList of Word object with updated lemma properties. # # .. versionadded:: 0.2.3 (``textblob_de``) # # """ # # @abstractmethod # def lemmatize(self, text): # """Return a list of (lemma, tag) tuples.""" # return # # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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() output. Very naïve and resource hungry approach: * get parser output * return a list of (lemma, pos_tag) tuples :param tokenizer: (optional) A tokenizer instance. If ``None``, defaults to :class:`PatternTokenizer() <textblob_de.tokenizers.PatternTokenizer>`. .. versionadded:: 0.3.0 (``textblob_de``) """ def __init__(self, tokenizer=None): <|code_end|> using the current file's imports: import os import string from textblob_de.base import BaseLemmatizer from textblob_de.packages import pattern_de from textblob_de.tokenizers import PatternTokenizer and any relevant context from other files: # Path: textblob_de/base.py # class BaseLemmatizer(with_metaclass(ABCMeta)): # # """Abstract base class from which all Lemmatizer classes inherit. # Descendant classes must implement a ``lemmatize(text)`` method that returns # a WordList of Word object with updated lemma properties. # # .. versionadded:: 0.2.3 (``textblob_de``) # # """ # # @abstractmethod # def lemmatize(self, text): # """Return a list of (lemma, tag) tuples.""" # return # # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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. >>> from textblob_de.taggers import PatternTagger or >>> from textblob_de import PatternTagger """ from __future__ import absolute_import <|code_end|> . Use current file imports: (import string from textblob.base import BaseTagger from textblob.utils import PUNCTUATION_REGEX from textblob_de.packages import pattern_de from textblob_de.compat import unicode from textblob_de.tokenizers import PatternTokenizer) and context including class names, function names, or small code snippets from other files: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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 PUNCTUATION: if self.include_punc: _sym = sentence.strip() if _sym in tuple('.?!'): _tag = "." else: _tag = _sym return [(_sym, _tag)] else: return [] if tokenize: _tokenized = " ".join(self.tokenizer.tokenize(sentence)) sentence = _tokenized # Sentence is tokenized before it is passed on to pattern.de.tag # (i.e. it is either submitted tokenized or if ) _tagged = pattern_tag(sentence, tokenize=False, encoding=self.encoding, tagset=self.tagset) if self.include_punc: return _tagged else: _tagged = [ (word, t) for word, t in _tagged if not PUNCTUATION_REGEX.match( <|code_end|> . Use current file imports: (import string from textblob.base import BaseTagger from textblob.utils import PUNCTUATION_REGEX from textblob_de.packages import pattern_de from textblob_de.compat import unicode from textblob_de.tokenizers import PatternTokenizer) and context including class names, function names, or small code snippets from other files: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) . Output only the next line.
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: (optional) A tokenizer instance. If ``None``, defaults to :class:`PatternTokenizer() <textblob_de.tokenizers.PatternTokenizer>`. :param include_punc: (optional) whether to include punctuation as separate tokens. Default to ``False``. :param encoding: (optional) Input string encoding. (Default ``utf-8``) :param tagset: (optional) Penn Treebank II (default) or ('penn'|'universal'|'stts'). ''' def __init__(self, tokenizer=None, include_punc=False, encoding='utf-8', tagset=None): <|code_end|> , continue by predicting the next line. Consider current file imports: import string from textblob.base import BaseTagger from textblob.utils import PUNCTUATION_REGEX from textblob_de.packages import pattern_de from textblob_de.compat import unicode from textblob_de.tokenizers import PatternTokenizer and context: # Path: textblob_de/packages.py # HERE = os.path.dirname(os.path.abspath(__file__)) # # Path: textblob_de/compat.py # PY2 = int(sys.version[0]) == 2 # PY26 = PY2 and int(sys.version_info[1]) < 7 # def implements_to_string(cls): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def decode_string(v, encoding="utf-8"): # def encode_string(v, encoding="utf-8"): # def get_external_executable(_exec): # def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # def _access_check(fn, mode): # class metaclass(meta): # # Path: textblob_de/tokenizers.py # class PatternTokenizer(BaseTokenizer): # # """Tokenizer included in ``pattern.de`` package. # # **PROs:** # # * handling of emoticons # * flexible implementations of abbreviations # * can be adapted very easily # # **CONs:** # # * ordinal numbers cause sentence breaks # * indices of Sentence() objects cannot be computed # # """ # # def __init__(self): # self.tokens = [] # # def tokenize(self, text, include_punc=True, nested=False): # """Return a list of word tokens. # # :param text: string of text. # :param include_punc: (optional) whether to include punctuation as separate # tokens. Default to True. # # """ # self.tokens = [ # w for w in ( # self.word_tokenize( # s, # include_punc) for s in self.sent_tokenize(text))] # if nested: # return self.tokens # else: # return list(chain.from_iterable(self.tokens)) # # def sent_tokenize(self, text, **kwargs): # """Returns a list of sentences. # # Each sentence is a space-separated string of tokens (words). # Handles common cases of abbreviations (e.g., etc., ...). # Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. # Headings without an ending period are inferred by line breaks. # # """ # # sentences = find_sentences(text, # punctuation=kwargs.get( # "punctuation", # PUNCTUATION), # abbreviations=kwargs.get( # "abbreviations", # ABBREVIATIONS_DE), # replace=kwargs.get("replace", replacements), # linebreak=r"\n{2,}") # return sentences # # def word_tokenize(self, sentences, include_punc=True): # #: Do not process empty strings (Issue #3) # if sentences.strip() == "": # return [] # _tokens = sentences.split(" ") # #: Handle strings consisting of a single punctuation mark seperately (Issue #4) # if len(_tokens) == 1: # if _tokens[0] in PUNCTUATION: # if include_punc: # return _tokens # else: # return [] # if include_punc: # last_word = _tokens[-1] # # Make sure that you do not separate '.' tokens into ['', '.'] # # (Issue #5) # if last_word.endswith('.') and len(last_word) > 1: # _tokens = _tokens[:-1] + [last_word[:-1], '.'] # return _tokens # else: # # Return each word token # # Strips punctuation unless the word comes from a contraction # # e.g. "gibt's" => ["gibt", "'s"] in "Heute gibt's viel zu tun!" # # e.g. "hat's" => ["hat", "'s"] # # e.g. "home." => ['home'] # words = [ # word if word.startswith("'") else strip_punc( # word, # all=False) for word in _tokens if strip_punc( # word, # all=False)] # return list(words) which might include code, classes, or functions. Output only the next line.
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, 'trace': None, 'style': 'braces'} # XXX I need a __repr__! def __init__(self, level, format_spec, fields, options, args, kwargs): """ :arg LogLevel level: the level of the message :arg string format_spec: the human-readable message template. Should match the ``style`` in options. :arg dict fields: dictionary of fields for :ref:`structured logging <structured-logging>` :arg tuple args: substitution arguments for ``format_spec``. :arg dict kwargs: substitution keyword arguments for ``format_spec``. :arg dict options: a dictionary of :ref:`options <message-options>` to control message creation. """ <|code_end|> . Use current file imports: import sys import traceback from string import Template from six import iteritems from .lib.text import to_text and context (classes, functions, or code) from other files: # Path: twiggy/lib/text.py # def to_text(obj, encoding='utf-8', errors=None, nonstring='simplerepr'): # """Make sure that a string is a text string # # :arg obj: An object to make sure is a text string. In most cases this # will be either a text string or a byte string. However, with # ``nonstring='simplerepr'``, this can be used as a traceback-free # version of ``str(obj)``. # :kwarg encoding: The encoding to use to transform from a byte string to # a text string. Defaults to using 'utf-8'. # :kwarg errors: The error handler to use if the byte string is not # decodable using the specified encoding. Any valid `codecs error # handler <https://docs.python.org/2/library/codecs.html#codec-base-classes>`_ # may be specified. We support three additional error strategies # specifically aimed at helping people to port code: # # :surrogate_or_strict: Will use surrogateescape if it is a valid # handler, otherwise it will use strict # :surrogate_or_replace: Will use surrogateescape if it is a valid # handler, otherwise it will use replace. # :surrogate_then_replace: Does the same as surrogate_or_replace but # `was added for symmetry with the error handlers in # :func:`ansible.module_utils._text.to_bytes` (Added in Ansible 2.3) # # Because surrogateescape was added in Python3 this usually means that # Python3 will use `surrogateescape` and Python2 will use the fallback # error handler. Note that the code checks for surrogateescape when the # module is imported. If you have a backport of `surrogateescape` for # python2, be sure to register the error handler prior to importing this # module. # # The default until Ansible-2.2 was `surrogate_or_replace` # In Ansible-2.3 this defaults to `surrogate_then_replace` for symmetry # with :func:`ansible.module_utils._text.to_bytes` . # :kwarg nonstring: The strategy to use if a nonstring is specified in # ``obj``. Default is 'simplerepr'. Valid values are: # # :simplerepr: The default. This takes the ``str`` of the object and # then returns the text version of that string. # :empty: Return an empty text string # :passthru: Return the object passed in # :strict: Raise a :exc:`TypeError` # # :returns: Typically this returns a text string. If a nonstring object is # passed in this may be a different type depending on the strategy # specified by nonstring. This will never return a byte string. # From Ansible-2.3 onwards, the default is `surrogate_then_replace`. # # .. version_changed:: 2.3 # # Added the surrogate_then_replace error handler and made it the default error handler. # """ # if isinstance(obj, text_type): # return obj # # if errors in _COMPOSED_ERROR_HANDLERS: # if HAS_SURROGATEESCAPE: # errors = 'surrogateescape' # elif errors == 'surrogate_or_strict': # errors = 'strict' # else: # errors = 'replace' # # if isinstance(obj, binary_type): # # Note: We don't need special handling for surrogate_then_replace # # because all bytes will either be made into surrogates or are valid # # to decode. # return obj.decode(encoding, errors) # # # Note: We do these last even though we have to call to_text again on the # # value because we're optimizing the common case # if nonstring == 'simplerepr': # try: # value = str(obj) # except UnicodeError: # try: # value = repr(obj) # except UnicodeError: # # Giving up # return u'' # elif nonstring == 'passthru': # return obj # elif nonstring == 'empty': # return u'' # elif nonstring == 'strict': # raise TypeError('obj must be a string type') # else: # raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring) # # return to_text(value, encoding, errors) . Output only the next line.
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 import twiggy as _twiggy import unittest import unittest2 as unittest from six import StringIO, string_types from twiggy import logger, outputs, levels, filters and any relevant context from other files: # Path: twiggy/logger.py # def emit(level): # def decorator(f): # def wrapper(self, *args, **kwargs): # def __init__(self, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def fields(self, **kwargs): # def fields_dict(self, d): # def options(self, **kwargs): # def trace(self, trace='error'): # def name(self, name): # def debug(self, format_spec='', *args, **kwargs): # def info(self, format_spec='', *args, **kwargs): # def notice(self, format_spec='', *args, **kwargs): # def warning(self, format_spec='', *args, **kwargs): # def error(self, format_spec='', *args, **kwargs): # def critical(self, format_spec='', *args, **kwargs): # def __init__(self, output, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def _feature_noop(self, *args, **kwargs): # def addFeature(cls, func, name=None): # def disableFeature(cls, name): # def delFeature(cls, name): # def __init__(self, fields=None, options=None, emitters=None, # min_level=None, filter=None): # def _clone(self): # def struct(self, **kwargs): # def struct_dict(self, d): # def _emit(self, level, format_spec, args, kwargs): # class BaseLogger(object): # class InternalLogger(BaseLogger): # class Logger(BaseLogger): # # Path: twiggy/outputs.py # class Output(object): # class AsyncOutput(Output): # class NullOutput(Output): # class ListOutput(Output): # class FileOutput(AsyncOutput): # class StreamOutput(Output): # def _noop_format(msg): # def __init__(self, format=None, close_atexit=True): # def _sync_init(self): # def _open(self): # def _close(self): # def _write(self, x): # def __sync_output_locked(self, msg): # def __sync_output_unlocked(self, msg): # def __init__(self, format=None, msg_buffer=0, close_atexit=True): # def _async_init(self, msg_buffer, close_atexit): # def __child_main(self): # def __async_output(self, msg): # def __async_close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def __init__(self, name, format, mode='a', buffering=1, msg_buffer=0, close_atexit=True): # def _open(self): # def _close(self): # def _write(self, x): # def __init__(self, format, stream=sys.stderr): # def _open(self): # def _close(self): # def _write(self, x): # # Path: twiggy/levels.py # class LogLevelMeta(type): # class LogLevel(with_metaclass(LogLevelMeta, object)): # def __new__(meta, name, bases, dct): # def __init__(self, name, value): # def __str__(self): # def __repr__(self): # def _lt(self, other): # pragma: no py2 cover # def _le(self, other): # pragma: no py2 cover # def _gt(self, other): # pragma: no py2 cover # def _ge(self, other): # pragma: no py2 cover # def __eq__(self, other): # def __ne__(self, other): # def __cmp__(self, other): # pragma: no py3 cover # def __hash__(self): # def name2level(name): # DEBUG = LogLevel('DEBUG', 1) # INFO = LogLevel('INFO', 2) # NOTICE = LogLevel('NOTICE', 3) # WARNING = LogLevel('WARNING', 4) # ERROR = LogLevel('ERROR', 5) # CRITICAL = LogLevel('CRITICAL', 6) # DISABLED = LogLevel('DISABLED', 7) # # Path: twiggy/filters.py # def msg_filter(x): # def list_wrapper(lst): # def wrapped(msg): # def regex_wrapper(regexp): # def wrapped(msg): # def names(*names): # def set_names_filter(msg): # def glob_names(*names): # def glob_names_filter(msg): # def __init__(self, min_level, filter, output): # def filter(self): # def filter(self, f): # class Emitter(object): . Output only the next line.
@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|> using the current file's imports: import itertools import re import sys import pytest import twiggy as _twiggy import unittest import unittest2 as unittest from six import StringIO, string_types from twiggy import logger, outputs, levels, filters and any relevant context from other files: # Path: twiggy/logger.py # def emit(level): # def decorator(f): # def wrapper(self, *args, **kwargs): # def __init__(self, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def fields(self, **kwargs): # def fields_dict(self, d): # def options(self, **kwargs): # def trace(self, trace='error'): # def name(self, name): # def debug(self, format_spec='', *args, **kwargs): # def info(self, format_spec='', *args, **kwargs): # def notice(self, format_spec='', *args, **kwargs): # def warning(self, format_spec='', *args, **kwargs): # def error(self, format_spec='', *args, **kwargs): # def critical(self, format_spec='', *args, **kwargs): # def __init__(self, output, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def _feature_noop(self, *args, **kwargs): # def addFeature(cls, func, name=None): # def disableFeature(cls, name): # def delFeature(cls, name): # def __init__(self, fields=None, options=None, emitters=None, # min_level=None, filter=None): # def _clone(self): # def struct(self, **kwargs): # def struct_dict(self, d): # def _emit(self, level, format_spec, args, kwargs): # class BaseLogger(object): # class InternalLogger(BaseLogger): # class Logger(BaseLogger): # # Path: twiggy/outputs.py # class Output(object): # class AsyncOutput(Output): # class NullOutput(Output): # class ListOutput(Output): # class FileOutput(AsyncOutput): # class StreamOutput(Output): # def _noop_format(msg): # def __init__(self, format=None, close_atexit=True): # def _sync_init(self): # def _open(self): # def _close(self): # def _write(self, x): # def __sync_output_locked(self, msg): # def __sync_output_unlocked(self, msg): # def __init__(self, format=None, msg_buffer=0, close_atexit=True): # def _async_init(self, msg_buffer, close_atexit): # def __child_main(self): # def __async_output(self, msg): # def __async_close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def __init__(self, name, format, mode='a', buffering=1, msg_buffer=0, close_atexit=True): # def _open(self): # def _close(self): # def _write(self, x): # def __init__(self, format, stream=sys.stderr): # def _open(self): # def _close(self): # def _write(self, x): # # Path: twiggy/levels.py # class LogLevelMeta(type): # class LogLevel(with_metaclass(LogLevelMeta, object)): # def __new__(meta, name, bases, dct): # def __init__(self, name, value): # def __str__(self): # def __repr__(self): # def _lt(self, other): # pragma: no py2 cover # def _le(self, other): # pragma: no py2 cover # def _gt(self, other): # pragma: no py2 cover # def _ge(self, other): # pragma: no py2 cover # def __eq__(self, other): # def __ne__(self, other): # def __cmp__(self, other): # pragma: no py3 cover # def __hash__(self): # def name2level(name): # DEBUG = LogLevel('DEBUG', 1) # INFO = LogLevel('INFO', 2) # NOTICE = LogLevel('NOTICE', 3) # WARNING = LogLevel('WARNING', 4) # ERROR = LogLevel('ERROR', 5) # CRITICAL = LogLevel('CRITICAL', 6) # DISABLED = LogLevel('DISABLED', 7) # # Path: twiggy/filters.py # def msg_filter(x): # def list_wrapper(lst): # def wrapped(msg): # def regex_wrapper(regexp): # def wrapped(msg): # def names(*names): # def set_names_filter(msg): # def glob_names(*names): # def glob_names_filter(msg): # def __init__(self, min_level, filter, output): # def filter(self): # def filter(self, f): # class Emitter(object): . Output only the next line.
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 = outputs.ListOutput(close_atexit=False) if issubclass(request.param, logger.InternalLogger): yield request.param(output=output) else: log = request.param() emitters = log._emitters <|code_end|> using the current file's imports: import itertools import re import sys import pytest import twiggy as _twiggy import unittest import unittest2 as unittest from six import StringIO, string_types from twiggy import logger, outputs, levels, filters and any relevant context from other files: # Path: twiggy/logger.py # def emit(level): # def decorator(f): # def wrapper(self, *args, **kwargs): # def __init__(self, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def fields(self, **kwargs): # def fields_dict(self, d): # def options(self, **kwargs): # def trace(self, trace='error'): # def name(self, name): # def debug(self, format_spec='', *args, **kwargs): # def info(self, format_spec='', *args, **kwargs): # def notice(self, format_spec='', *args, **kwargs): # def warning(self, format_spec='', *args, **kwargs): # def error(self, format_spec='', *args, **kwargs): # def critical(self, format_spec='', *args, **kwargs): # def __init__(self, output, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def _feature_noop(self, *args, **kwargs): # def addFeature(cls, func, name=None): # def disableFeature(cls, name): # def delFeature(cls, name): # def __init__(self, fields=None, options=None, emitters=None, # min_level=None, filter=None): # def _clone(self): # def struct(self, **kwargs): # def struct_dict(self, d): # def _emit(self, level, format_spec, args, kwargs): # class BaseLogger(object): # class InternalLogger(BaseLogger): # class Logger(BaseLogger): # # Path: twiggy/outputs.py # class Output(object): # class AsyncOutput(Output): # class NullOutput(Output): # class ListOutput(Output): # class FileOutput(AsyncOutput): # class StreamOutput(Output): # def _noop_format(msg): # def __init__(self, format=None, close_atexit=True): # def _sync_init(self): # def _open(self): # def _close(self): # def _write(self, x): # def __sync_output_locked(self, msg): # def __sync_output_unlocked(self, msg): # def __init__(self, format=None, msg_buffer=0, close_atexit=True): # def _async_init(self, msg_buffer, close_atexit): # def __child_main(self): # def __async_output(self, msg): # def __async_close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def __init__(self, name, format, mode='a', buffering=1, msg_buffer=0, close_atexit=True): # def _open(self): # def _close(self): # def _write(self, x): # def __init__(self, format, stream=sys.stderr): # def _open(self): # def _close(self): # def _write(self, x): # # Path: twiggy/levels.py # class LogLevelMeta(type): # class LogLevel(with_metaclass(LogLevelMeta, object)): # def __new__(meta, name, bases, dct): # def __init__(self, name, value): # def __str__(self): # def __repr__(self): # def _lt(self, other): # pragma: no py2 cover # def _le(self, other): # pragma: no py2 cover # def _gt(self, other): # pragma: no py2 cover # def _ge(self, other): # pragma: no py2 cover # def __eq__(self, other): # def __ne__(self, other): # def __cmp__(self, other): # pragma: no py3 cover # def __hash__(self): # def name2level(name): # DEBUG = LogLevel('DEBUG', 1) # INFO = LogLevel('INFO', 2) # NOTICE = LogLevel('NOTICE', 3) # WARNING = LogLevel('WARNING', 4) # ERROR = LogLevel('ERROR', 5) # CRITICAL = LogLevel('CRITICAL', 6) # DISABLED = LogLevel('DISABLED', 7) # # Path: twiggy/filters.py # def msg_filter(x): # def list_wrapper(lst): # def wrapped(msg): # def regex_wrapper(regexp): # def wrapped(msg): # def names(*names): # def set_names_filter(msg): # def glob_names(*names): # def glob_names_filter(msg): # def __init__(self, min_level, filter, output): # def filter(self): # def filter(self, f): # class Emitter(object): . Output only the next line.
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 = outputs.ListOutput(close_atexit=False) if issubclass(request.param, logger.InternalLogger): yield request.param(output=output) else: log = request.param() emitters = log._emitters <|code_end|> using the current file's imports: import itertools import re import sys import pytest import twiggy as _twiggy import unittest import unittest2 as unittest from six import StringIO, string_types from twiggy import logger, outputs, levels, filters and any relevant context from other files: # Path: twiggy/logger.py # def emit(level): # def decorator(f): # def wrapper(self, *args, **kwargs): # def __init__(self, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def fields(self, **kwargs): # def fields_dict(self, d): # def options(self, **kwargs): # def trace(self, trace='error'): # def name(self, name): # def debug(self, format_spec='', *args, **kwargs): # def info(self, format_spec='', *args, **kwargs): # def notice(self, format_spec='', *args, **kwargs): # def warning(self, format_spec='', *args, **kwargs): # def error(self, format_spec='', *args, **kwargs): # def critical(self, format_spec='', *args, **kwargs): # def __init__(self, output, fields=None, options=None, min_level=None): # def _clone(self): # def _emit(self, level, format_spec, args, kwargs): # def _feature_noop(self, *args, **kwargs): # def addFeature(cls, func, name=None): # def disableFeature(cls, name): # def delFeature(cls, name): # def __init__(self, fields=None, options=None, emitters=None, # min_level=None, filter=None): # def _clone(self): # def struct(self, **kwargs): # def struct_dict(self, d): # def _emit(self, level, format_spec, args, kwargs): # class BaseLogger(object): # class InternalLogger(BaseLogger): # class Logger(BaseLogger): # # Path: twiggy/outputs.py # class Output(object): # class AsyncOutput(Output): # class NullOutput(Output): # class ListOutput(Output): # class FileOutput(AsyncOutput): # class StreamOutput(Output): # def _noop_format(msg): # def __init__(self, format=None, close_atexit=True): # def _sync_init(self): # def _open(self): # def _close(self): # def _write(self, x): # def __sync_output_locked(self, msg): # def __sync_output_unlocked(self, msg): # def __init__(self, format=None, msg_buffer=0, close_atexit=True): # def _async_init(self, msg_buffer, close_atexit): # def __child_main(self): # def __async_output(self, msg): # def __async_close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def _open(self): # def _write(self, msg): # def _close(self): # def __init__(self, name, format, mode='a', buffering=1, msg_buffer=0, close_atexit=True): # def _open(self): # def _close(self): # def _write(self, x): # def __init__(self, format, stream=sys.stderr): # def _open(self): # def _close(self): # def _write(self, x): # # Path: twiggy/levels.py # class LogLevelMeta(type): # class LogLevel(with_metaclass(LogLevelMeta, object)): # def __new__(meta, name, bases, dct): # def __init__(self, name, value): # def __str__(self): # def __repr__(self): # def _lt(self, other): # pragma: no py2 cover # def _le(self, other): # pragma: no py2 cover # def _gt(self, other): # pragma: no py2 cover # def _ge(self, other): # pragma: no py2 cover # def __eq__(self, other): # def __ne__(self, other): # def __cmp__(self, other): # pragma: no py3 cover # def __hash__(self): # def name2level(name): # DEBUG = LogLevel('DEBUG', 1) # INFO = LogLevel('INFO', 2) # NOTICE = LogLevel('NOTICE', 3) # WARNING = LogLevel('WARNING', 4) # ERROR = LogLevel('ERROR', 5) # CRITICAL = LogLevel('CRITICAL', 6) # DISABLED = LogLevel('DISABLED', 7) # # Path: twiggy/filters.py # def msg_filter(x): # def list_wrapper(lst): # def wrapped(msg): # def regex_wrapper(regexp): # def wrapped(msg): # def names(*names): # def set_names_filter(msg): # def glob_names(*names): # def glob_names_filter(msg): # def __init__(self, min_level, filter, output): # def filter(self): # def filter(self, f): # class Emitter(object): . Output only the next line.
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_item(self): o1 = object() o2 = object() x1, x2 = same_item(o1, o2) assert o1 is x1 assert o2 is x2 class ConverterTestCase(unittest.TestCase): def test_repr(self): <|code_end|> . Use current file imports: import sys import unittest import unittest2 as unittest from twiggy.lib.converter import Converter, ConversionTable, same_item, same_value, drop and context (classes, functions, or code) from other files: # Path: twiggy/lib/converter.py # class Converter(object): # """Holder for `.ConversionTable` items # # :ivar key: the key to apply the conversion to # :ivar function convert_value: one-argument function to convert the value # :ivar function convert_item: two-argument function converting the key and converted value # :ivar bool required: is the item required to present. Items are optional by default. # """ # # __slots__ = ['key', 'convert_value', 'convert_item', 'required'] # # def __init__(self, key, convert_value, convert_item, required=False): # self.key = key # self.convert_value = convert_value # self.convert_item = convert_item # self.required = required # # def __repr__(self): # # XXX perhaps poke around in convert_value/convert_item to see if we can extract # # a meaningful `"some_string".format`? eh. # return "<Converter({0!r})>".format(self.key) # # class ConversionTable(list): # """Converts dictionaries using Converters""" # # def __init__(self, seq=None): # """ # :arg seq: a sequence of Converters # # You may also pass 3-or-4 item arg tuples or kwarg dicts (which will be used to create # `Converters <.Converter>`) # """ # # super(ConversionTable, self).__init__([]) # if seq is None: # return # for i in seq: # if isinstance(i, Converter): # self.append(i) # elif isinstance(i, (tuple, list)) and len(i) in (3, 4): # self.add(*i) # elif isinstance(i, dict): # self.add(**i) # else: # raise ValueError("Bad converter: {0!r}".format(i)) # # XXX cache converts & requireds below # # @staticmethod # def generic_value(value): # """convert values for which no specific Converter is supplied""" # return value # # @staticmethod # def generic_item(key, value): # """convert items for which no specific Converter is supplied""" # return key, value # # @staticmethod # def aggregate(converteds): # """aggregate the list of converted items""" # return dict(converteds) # # def convert(self, d): # """do the conversion # # :arg dict d: the data to convert. Keys should be strings. # """ # # XXX I could be much faster & efficient! # # XXX I have written this pattern at least 10 times # converts = set(x.key for x in self) # avail = set(k for k in d) # required = set(x.key for x in self if x.required) # missing = required - avail # # if missing: # raise ValueError("Missing fields {0}".format(list(missing))) # # item_list = [] # for c in self: # if c.key in d: # item = c.convert_item(c.key, c.convert_value(d[c.key])) # if item is not None: # item_list.append(item) # # for key in sorted(avail - converts): # item = self.generic_item(key, self.generic_value(d[key])) # if item is not None: # item_list.append(item) # # return self.aggregate(item_list) # # def copy(self): # """make an independent copy of this ConversionTable""" # return copy.deepcopy(self) # # def get(self, key): # """return the *first* converter for key""" # for c in self: # if c.key == key: # return c # # def get_all(self, key): # """return a list of all converters for key""" # return [c for c in self if c.key == key] # # def add(self, *args, **kwargs): # """ # Append a `.Converter`. # # ``args`` & ``kwargs`` will be passed through to its constructor # """ # self.append(Converter(*args, **kwargs)) # # def delete(self, key): # """delete the *all* of the converters for key""" # # this weird idiom creates a new list without the deleted items and # # replaces the contents of self. Can't iterate and remove() items at # # the same time (indexes get messed up. # self[:] = [c for c in self if c.key != key] # # def same_item(k, v): # """return the item unchanged""" # return k, v # # def same_value(v): # """return the value unchanged""" # return v # # def drop(k, v): # """return None, indicating the item should be dropped""" # return None . Output only the next line.
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, x2 = same_item(o1, o2) assert o1 is x1 assert o2 is x2 class ConverterTestCase(unittest.TestCase): def test_repr(self): c = Converter("pants", conv_val, conv_item) assert repr(c) == "<Converter('pants')>" class ConversionTableTestCase(unittest.TestCase): def test_init_None(self): <|code_end|> . Use current file imports: import sys import unittest import unittest2 as unittest from twiggy.lib.converter import Converter, ConversionTable, same_item, same_value, drop and context (classes, functions, or code) from other files: # Path: twiggy/lib/converter.py # class Converter(object): # """Holder for `.ConversionTable` items # # :ivar key: the key to apply the conversion to # :ivar function convert_value: one-argument function to convert the value # :ivar function convert_item: two-argument function converting the key and converted value # :ivar bool required: is the item required to present. Items are optional by default. # """ # # __slots__ = ['key', 'convert_value', 'convert_item', 'required'] # # def __init__(self, key, convert_value, convert_item, required=False): # self.key = key # self.convert_value = convert_value # self.convert_item = convert_item # self.required = required # # def __repr__(self): # # XXX perhaps poke around in convert_value/convert_item to see if we can extract # # a meaningful `"some_string".format`? eh. # return "<Converter({0!r})>".format(self.key) # # class ConversionTable(list): # """Converts dictionaries using Converters""" # # def __init__(self, seq=None): # """ # :arg seq: a sequence of Converters # # You may also pass 3-or-4 item arg tuples or kwarg dicts (which will be used to create # `Converters <.Converter>`) # """ # # super(ConversionTable, self).__init__([]) # if seq is None: # return # for i in seq: # if isinstance(i, Converter): # self.append(i) # elif isinstance(i, (tuple, list)) and len(i) in (3, 4): # self.add(*i) # elif isinstance(i, dict): # self.add(**i) # else: # raise ValueError("Bad converter: {0!r}".format(i)) # # XXX cache converts & requireds below # # @staticmethod # def generic_value(value): # """convert values for which no specific Converter is supplied""" # return value # # @staticmethod # def generic_item(key, value): # """convert items for which no specific Converter is supplied""" # return key, value # # @staticmethod # def aggregate(converteds): # """aggregate the list of converted items""" # return dict(converteds) # # def convert(self, d): # """do the conversion # # :arg dict d: the data to convert. Keys should be strings. # """ # # XXX I could be much faster & efficient! # # XXX I have written this pattern at least 10 times # converts = set(x.key for x in self) # avail = set(k for k in d) # required = set(x.key for x in self if x.required) # missing = required - avail # # if missing: # raise ValueError("Missing fields {0}".format(list(missing))) # # item_list = [] # for c in self: # if c.key in d: # item = c.convert_item(c.key, c.convert_value(d[c.key])) # if item is not None: # item_list.append(item) # # for key in sorted(avail - converts): # item = self.generic_item(key, self.generic_value(d[key])) # if item is not None: # item_list.append(item) # # return self.aggregate(item_list) # # def copy(self): # """make an independent copy of this ConversionTable""" # return copy.deepcopy(self) # # def get(self, key): # """return the *first* converter for key""" # for c in self: # if c.key == key: # return c # # def get_all(self, key): # """return a list of all converters for key""" # return [c for c in self if c.key == key] # # def add(self, *args, **kwargs): # """ # Append a `.Converter`. # # ``args`` & ``kwargs`` will be passed through to its constructor # """ # self.append(Converter(*args, **kwargs)) # # def delete(self, key): # """delete the *all* of the converters for key""" # # this weird idiom creates a new list without the deleted items and # # replaces the contents of self. Can't iterate and remove() items at # # the same time (indexes get messed up. # self[:] = [c for c in self if c.key != key] # # def same_item(k, v): # """return the item unchanged""" # return k, v # # def same_value(v): # """return the value unchanged""" # return v # # def drop(k, v): # """return None, indicating the item should be dropped""" # return None . Output only the next line.
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): 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() <|code_end|> . Use current file imports: (import sys import unittest import unittest2 as unittest from twiggy.lib.converter import Converter, ConversionTable, same_item, same_value, drop) and context including class names, function names, or small code snippets from other files: # Path: twiggy/lib/converter.py # class Converter(object): # """Holder for `.ConversionTable` items # # :ivar key: the key to apply the conversion to # :ivar function convert_value: one-argument function to convert the value # :ivar function convert_item: two-argument function converting the key and converted value # :ivar bool required: is the item required to present. Items are optional by default. # """ # # __slots__ = ['key', 'convert_value', 'convert_item', 'required'] # # def __init__(self, key, convert_value, convert_item, required=False): # self.key = key # self.convert_value = convert_value # self.convert_item = convert_item # self.required = required # # def __repr__(self): # # XXX perhaps poke around in convert_value/convert_item to see if we can extract # # a meaningful `"some_string".format`? eh. # return "<Converter({0!r})>".format(self.key) # # class ConversionTable(list): # """Converts dictionaries using Converters""" # # def __init__(self, seq=None): # """ # :arg seq: a sequence of Converters # # You may also pass 3-or-4 item arg tuples or kwarg dicts (which will be used to create # `Converters <.Converter>`) # """ # # super(ConversionTable, self).__init__([]) # if seq is None: # return # for i in seq: # if isinstance(i, Converter): # self.append(i) # elif isinstance(i, (tuple, list)) and len(i) in (3, 4): # self.add(*i) # elif isinstance(i, dict): # self.add(**i) # else: # raise ValueError("Bad converter: {0!r}".format(i)) # # XXX cache converts & requireds below # # @staticmethod # def generic_value(value): # """convert values for which no specific Converter is supplied""" # return value # # @staticmethod # def generic_item(key, value): # """convert items for which no specific Converter is supplied""" # return key, value # # @staticmethod # def aggregate(converteds): # """aggregate the list of converted items""" # return dict(converteds) # # def convert(self, d): # """do the conversion # # :arg dict d: the data to convert. Keys should be strings. # """ # # XXX I could be much faster & efficient! # # XXX I have written this pattern at least 10 times # converts = set(x.key for x in self) # avail = set(k for k in d) # required = set(x.key for x in self if x.required) # missing = required - avail # # if missing: # raise ValueError("Missing fields {0}".format(list(missing))) # # item_list = [] # for c in self: # if c.key in d: # item = c.convert_item(c.key, c.convert_value(d[c.key])) # if item is not None: # item_list.append(item) # # for key in sorted(avail - converts): # item = self.generic_item(key, self.generic_value(d[key])) # if item is not None: # item_list.append(item) # # return self.aggregate(item_list) # # def copy(self): # """make an independent copy of this ConversionTable""" # return copy.deepcopy(self) # # def get(self, key): # """return the *first* converter for key""" # for c in self: # if c.key == key: # return c # # def get_all(self, key): # """return a list of all converters for key""" # return [c for c in self if c.key == key] # # def add(self, *args, **kwargs): # """ # Append a `.Converter`. # # ``args`` & ``kwargs`` will be passed through to its constructor # """ # self.append(Converter(*args, **kwargs)) # # def delete(self, key): # """delete the *all* of the converters for key""" # # this weird idiom creates a new list without the deleted items and # # replaces the contents of self. Can't iterate and remove() items at # # the same time (indexes get messed up. # self[:] = [c for c in self if c.key != key] # # def same_item(k, v): # """return the item unchanged""" # return k, v # # def same_value(v): # """return the value unchanged""" # return v # # def drop(k, v): # """return None, indicating the item should be dropped""" # return None . Output only the next line.
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 drop(1, 2) is None def test_same_value(self): o = object() <|code_end|> , determine the next line of code. You have imports: import sys import unittest import unittest2 as unittest from twiggy.lib.converter import Converter, ConversionTable, same_item, same_value, drop and context (class names, function names, or code) available: # Path: twiggy/lib/converter.py # class Converter(object): # """Holder for `.ConversionTable` items # # :ivar key: the key to apply the conversion to # :ivar function convert_value: one-argument function to convert the value # :ivar function convert_item: two-argument function converting the key and converted value # :ivar bool required: is the item required to present. Items are optional by default. # """ # # __slots__ = ['key', 'convert_value', 'convert_item', 'required'] # # def __init__(self, key, convert_value, convert_item, required=False): # self.key = key # self.convert_value = convert_value # self.convert_item = convert_item # self.required = required # # def __repr__(self): # # XXX perhaps poke around in convert_value/convert_item to see if we can extract # # a meaningful `"some_string".format`? eh. # return "<Converter({0!r})>".format(self.key) # # class ConversionTable(list): # """Converts dictionaries using Converters""" # # def __init__(self, seq=None): # """ # :arg seq: a sequence of Converters # # You may also pass 3-or-4 item arg tuples or kwarg dicts (which will be used to create # `Converters <.Converter>`) # """ # # super(ConversionTable, self).__init__([]) # if seq is None: # return # for i in seq: # if isinstance(i, Converter): # self.append(i) # elif isinstance(i, (tuple, list)) and len(i) in (3, 4): # self.add(*i) # elif isinstance(i, dict): # self.add(**i) # else: # raise ValueError("Bad converter: {0!r}".format(i)) # # XXX cache converts & requireds below # # @staticmethod # def generic_value(value): # """convert values for which no specific Converter is supplied""" # return value # # @staticmethod # def generic_item(key, value): # """convert items for which no specific Converter is supplied""" # return key, value # # @staticmethod # def aggregate(converteds): # """aggregate the list of converted items""" # return dict(converteds) # # def convert(self, d): # """do the conversion # # :arg dict d: the data to convert. Keys should be strings. # """ # # XXX I could be much faster & efficient! # # XXX I have written this pattern at least 10 times # converts = set(x.key for x in self) # avail = set(k for k in d) # required = set(x.key for x in self if x.required) # missing = required - avail # # if missing: # raise ValueError("Missing fields {0}".format(list(missing))) # # item_list = [] # for c in self: # if c.key in d: # item = c.convert_item(c.key, c.convert_value(d[c.key])) # if item is not None: # item_list.append(item) # # for key in sorted(avail - converts): # item = self.generic_item(key, self.generic_value(d[key])) # if item is not None: # item_list.append(item) # # return self.aggregate(item_list) # # def copy(self): # """make an independent copy of this ConversionTable""" # return copy.deepcopy(self) # # def get(self, key): # """return the *first* converter for key""" # for c in self: # if c.key == key: # return c # # def get_all(self, key): # """return a list of all converters for key""" # return [c for c in self if c.key == key] # # def add(self, *args, **kwargs): # """ # Append a `.Converter`. # # ``args`` & ``kwargs`` will be passed through to its constructor # """ # self.append(Converter(*args, **kwargs)) # # def delete(self, key): # """delete the *all* of the converters for key""" # # this weird idiom creates a new list without the deleted items and # # replaces the contents of self. Can't iterate and remove() items at # # the same time (indexes get messed up. # self[:] = [c for c in self if c.key != key] # # def same_item(k, v): # """return the item unchanged""" # return k, v # # def same_value(v): # """return the value unchanged""" # return v # # def drop(k, v): # """return None, indicating the item should be dropped""" # return None . Output only the next line.
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_end|> . Write the next line using the current file imports: import sys import unittest import unittest2 as unittest from twiggy.lib.converter import Converter, ConversionTable, same_item, same_value, drop and context from other files: # Path: twiggy/lib/converter.py # class Converter(object): # """Holder for `.ConversionTable` items # # :ivar key: the key to apply the conversion to # :ivar function convert_value: one-argument function to convert the value # :ivar function convert_item: two-argument function converting the key and converted value # :ivar bool required: is the item required to present. Items are optional by default. # """ # # __slots__ = ['key', 'convert_value', 'convert_item', 'required'] # # def __init__(self, key, convert_value, convert_item, required=False): # self.key = key # self.convert_value = convert_value # self.convert_item = convert_item # self.required = required # # def __repr__(self): # # XXX perhaps poke around in convert_value/convert_item to see if we can extract # # a meaningful `"some_string".format`? eh. # return "<Converter({0!r})>".format(self.key) # # class ConversionTable(list): # """Converts dictionaries using Converters""" # # def __init__(self, seq=None): # """ # :arg seq: a sequence of Converters # # You may also pass 3-or-4 item arg tuples or kwarg dicts (which will be used to create # `Converters <.Converter>`) # """ # # super(ConversionTable, self).__init__([]) # if seq is None: # return # for i in seq: # if isinstance(i, Converter): # self.append(i) # elif isinstance(i, (tuple, list)) and len(i) in (3, 4): # self.add(*i) # elif isinstance(i, dict): # self.add(**i) # else: # raise ValueError("Bad converter: {0!r}".format(i)) # # XXX cache converts & requireds below # # @staticmethod # def generic_value(value): # """convert values for which no specific Converter is supplied""" # return value # # @staticmethod # def generic_item(key, value): # """convert items for which no specific Converter is supplied""" # return key, value # # @staticmethod # def aggregate(converteds): # """aggregate the list of converted items""" # return dict(converteds) # # def convert(self, d): # """do the conversion # # :arg dict d: the data to convert. Keys should be strings. # """ # # XXX I could be much faster & efficient! # # XXX I have written this pattern at least 10 times # converts = set(x.key for x in self) # avail = set(k for k in d) # required = set(x.key for x in self if x.required) # missing = required - avail # # if missing: # raise ValueError("Missing fields {0}".format(list(missing))) # # item_list = [] # for c in self: # if c.key in d: # item = c.convert_item(c.key, c.convert_value(d[c.key])) # if item is not None: # item_list.append(item) # # for key in sorted(avail - converts): # item = self.generic_item(key, self.generic_value(d[key])) # if item is not None: # item_list.append(item) # # return self.aggregate(item_list) # # def copy(self): # """make an independent copy of this ConversionTable""" # return copy.deepcopy(self) # # def get(self, key): # """return the *first* converter for key""" # for c in self: # if c.key == key: # return c # # def get_all(self, key): # """return a list of all converters for key""" # return [c for c in self if c.key == key] # # def add(self, *args, **kwargs): # """ # Append a `.Converter`. # # ``args`` & ``kwargs`` will be passed through to its constructor # """ # self.append(Converter(*args, **kwargs)) # # def delete(self, key): # """delete the *all* of the converters for key""" # # this weird idiom creates a new list without the deleted items and # # replaces the contents of self. Can't iterate and remove() items at # # the same time (indexes get messed up. # self[:] = [c for c in self if c.key != key] # # def same_item(k, v): # """return the item unchanged""" # return k, v # # def same_value(v): # """return the value unchanged""" # return v # # def drop(k, v): # """return None, indicating the item should be dropped""" # return None , which may include functions, classes, or code. Output only the next line.
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.exist', 'Could not find {0} named does.not.exist in module' ' itertools'), ('os.nonexistent', 'Could not find {0} named nonexistent in module os'), ) INVALID_FUNCTIONS = INVALID_ATTRIBUTES[1:] + ( (5, "Identifier named 5 is not a function"), ('os.F_OK', 'Identifier named os.F_OK is not a function'), ) def function_for_testing(value): pass def test_import_module_backport(): <|code_end|> , generate the next line using the imports in this file: import re import sys import pytest import os import os.path import itertools import itertools import itertools from twiggy.lib.validators import (_import_module, _string_to_attribute, _parse_external) from os import F_OK from os import F_OK from itertools import chain from itertools import chain from tarfile import TarInfo from tarfile import TarInfo and context (functions, classes, or occasionally code) from other files: # Path: twiggy/lib/validators.py # def _import_module(module_name): # # Python 2.6 compatibility # fromlist = [] # try: # fromlist.append(module_name[:module_name.rindex('.')]) # except ValueError: # pass # # return __import__(module_name, fromlist=fromlist) # # def _string_to_attribute(value, type_='attribute'): # """ # Tests whether a string is an importable attribute and returns the attribute # # :arg value: The string naming the attribute # :returns: The attribute # :raises ValueError: if the string is not an importable attribute # """ # # For exception messages # if type_[0] in ('a', 'e', 'i', 'o', 'u'): # article = 'an' # else: # article = 'a' # # if not isinstance(value, string_types): # raise ValueError('This value must be a string naming {0} {1}, not {2} of' # ' type {3}'.format(article, type_, value, type(value))) # parts = value.split('.') # # # Test for an attribute in builtins named value # if len(parts) == 1: # try: # attribute = getattr(builtins, value) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2}'.format(article, type_, value)) # # return attribute # # # Find a module that we can import # module = None # for idx in range(len(parts) - 1, 0, -1): # try: # module = import_module('.'.join(parts[:idx])) # except Exception: # pass # else: # remainder = parts[idx:] # break # else: # For-else # raise ValueError('Could not import a module with {0} {1} named' # ' {2}'.format(article, type_, value)) # # # Handle both Staticmethod (ClassName.staticmethod) and module global # # attribute (attributename) # prev_part = module # for next_part in remainder: # try: # prev_part = getattr(prev_part, next_part) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2} in module' # ' {3}'.format(article, type_, '.'.join(remainder), # '.'.join(parts[:idx]))) # attribute = prev_part # return attribute # # def _parse_external(value, function=False): # """ # Check whether a string is marked as being an external resource and return the resource # # This function checks whether a string begins with ``ext://`` and if so it removes the ``ext://`` # and tries to import an attribute with that name. # # :arg value: The string to process # :kwarg function: If True, make sure that the attribute found is a callable. This will convert # a string into a function or fail validation regardless of whether the string starts with # ``ext://``. (Default False) # :returns: If ``ext://`` was present or always is True then the imported attribute is returned. # If not, then ``value`` is returned. # :raises ValueError: if the string is not importable # """ # external = False # if isinstance(value, string_types): # if value.startswith('ext://'): # value = value[6:] # external = True # # if not (external or function): # return value # # if isinstance(value, string_types): # attribute = _string_to_attribute(value, type_='function' if function else 'attribute') # else: # attribute = value # # if function: # # Finally check that it is a callable # if not callable(attribute): # raise ValueError('Identifier named {0} is not a function'.format(value)) # return attribute . Output only the next line.
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} named does.not.exist in module' ' itertools'), ('os.nonexistent', 'Could not find {0} named nonexistent in module os'), ) INVALID_FUNCTIONS = INVALID_ATTRIBUTES[1:] + ( (5, "Identifier named 5 is not a function"), ('os.F_OK', 'Identifier named os.F_OK is not a function'), ) def function_for_testing(value): pass def test_import_module_backport(): os_via_import_module = _import_module('os') assert os_via_import_module == os os_path_via_import_module = _import_module('os.path') assert os_path_via_import_module == os.path class TestStringToAttribute(object): def test_valid_builtin(self): # A toplevel function <|code_end|> , generate the next line using the imports in this file: import re import sys import pytest import os import os.path import itertools import itertools import itertools from twiggy.lib.validators import (_import_module, _string_to_attribute, _parse_external) from os import F_OK from os import F_OK from itertools import chain from itertools import chain from tarfile import TarInfo from tarfile import TarInfo and context (functions, classes, or occasionally code) from other files: # Path: twiggy/lib/validators.py # def _import_module(module_name): # # Python 2.6 compatibility # fromlist = [] # try: # fromlist.append(module_name[:module_name.rindex('.')]) # except ValueError: # pass # # return __import__(module_name, fromlist=fromlist) # # def _string_to_attribute(value, type_='attribute'): # """ # Tests whether a string is an importable attribute and returns the attribute # # :arg value: The string naming the attribute # :returns: The attribute # :raises ValueError: if the string is not an importable attribute # """ # # For exception messages # if type_[0] in ('a', 'e', 'i', 'o', 'u'): # article = 'an' # else: # article = 'a' # # if not isinstance(value, string_types): # raise ValueError('This value must be a string naming {0} {1}, not {2} of' # ' type {3}'.format(article, type_, value, type(value))) # parts = value.split('.') # # # Test for an attribute in builtins named value # if len(parts) == 1: # try: # attribute = getattr(builtins, value) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2}'.format(article, type_, value)) # # return attribute # # # Find a module that we can import # module = None # for idx in range(len(parts) - 1, 0, -1): # try: # module = import_module('.'.join(parts[:idx])) # except Exception: # pass # else: # remainder = parts[idx:] # break # else: # For-else # raise ValueError('Could not import a module with {0} {1} named' # ' {2}'.format(article, type_, value)) # # # Handle both Staticmethod (ClassName.staticmethod) and module global # # attribute (attributename) # prev_part = module # for next_part in remainder: # try: # prev_part = getattr(prev_part, next_part) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2} in module' # ' {3}'.format(article, type_, '.'.join(remainder), # '.'.join(parts[:idx]))) # attribute = prev_part # return attribute # # def _parse_external(value, function=False): # """ # Check whether a string is marked as being an external resource and return the resource # # This function checks whether a string begins with ``ext://`` and if so it removes the ``ext://`` # and tries to import an attribute with that name. # # :arg value: The string to process # :kwarg function: If True, make sure that the attribute found is a callable. This will convert # a string into a function or fail validation regardless of whether the string starts with # ``ext://``. (Default False) # :returns: If ``ext://`` was present or always is True then the imported attribute is returned. # If not, then ``value`` is returned. # :raises ValueError: if the string is not importable # """ # external = False # if isinstance(value, string_types): # if value.startswith('ext://'): # value = value[6:] # external = True # # if not (external or function): # return value # # if isinstance(value, string_types): # attribute = _string_to_attribute(value, type_='function' if function else 'attribute') # else: # attribute = value # # if function: # # Finally check that it is a callable # if not callable(attribute): # raise ValueError('Identifier named {0} is not a function'.format(value)) # return attribute . Output only the next line.
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_import(self): # Test that it returns a classmethod from_file_via_validator = _string_to_attribute('tarfile.TarInfo.frombuf', type_='function') assert from_file_via_validator == TarInfo.frombuf def test_valid_method_post_import(self): # Test that it returns a classmethod after the module has been imported from_file_via_validator = _string_to_attribute('tarfile.TarInfo.frombuf', type_='function') assert from_file_via_validator == TarInfo.frombuf @pytest.mark.parametrize("value, message", INVALID_ATTRIBUTES) def test_invalid_attributes(self, value, message): with pytest.raises(ValueError) as exc: _string_to_attribute(value, type_='attribute') assert re.search(message.format('an attribute'), exc.value.args[0]) @pytest.mark.parametrize("value, message", INVALID_ATTRIBUTES) def test_invalid_functions(self, value, message): with pytest.raises(ValueError) as exc: _string_to_attribute(value, type_='function') assert re.search(message.format('a function'), exc.value.args[0]) class TestParseExternal(object): def test_not_external_string(self): <|code_end|> . Write the next line using the current file imports: import re import sys import pytest import os import os.path import itertools import itertools import itertools from twiggy.lib.validators import (_import_module, _string_to_attribute, _parse_external) from os import F_OK from os import F_OK from itertools import chain from itertools import chain from tarfile import TarInfo from tarfile import TarInfo and context from other files: # Path: twiggy/lib/validators.py # def _import_module(module_name): # # Python 2.6 compatibility # fromlist = [] # try: # fromlist.append(module_name[:module_name.rindex('.')]) # except ValueError: # pass # # return __import__(module_name, fromlist=fromlist) # # def _string_to_attribute(value, type_='attribute'): # """ # Tests whether a string is an importable attribute and returns the attribute # # :arg value: The string naming the attribute # :returns: The attribute # :raises ValueError: if the string is not an importable attribute # """ # # For exception messages # if type_[0] in ('a', 'e', 'i', 'o', 'u'): # article = 'an' # else: # article = 'a' # # if not isinstance(value, string_types): # raise ValueError('This value must be a string naming {0} {1}, not {2} of' # ' type {3}'.format(article, type_, value, type(value))) # parts = value.split('.') # # # Test for an attribute in builtins named value # if len(parts) == 1: # try: # attribute = getattr(builtins, value) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2}'.format(article, type_, value)) # # return attribute # # # Find a module that we can import # module = None # for idx in range(len(parts) - 1, 0, -1): # try: # module = import_module('.'.join(parts[:idx])) # except Exception: # pass # else: # remainder = parts[idx:] # break # else: # For-else # raise ValueError('Could not import a module with {0} {1} named' # ' {2}'.format(article, type_, value)) # # # Handle both Staticmethod (ClassName.staticmethod) and module global # # attribute (attributename) # prev_part = module # for next_part in remainder: # try: # prev_part = getattr(prev_part, next_part) # except AttributeError: # raise ValueError('Could not find {0} {1} named {2} in module' # ' {3}'.format(article, type_, '.'.join(remainder), # '.'.join(parts[:idx]))) # attribute = prev_part # return attribute # # def _parse_external(value, function=False): # """ # Check whether a string is marked as being an external resource and return the resource # # This function checks whether a string begins with ``ext://`` and if so it removes the ``ext://`` # and tries to import an attribute with that name. # # :arg value: The string to process # :kwarg function: If True, make sure that the attribute found is a callable. This will convert # a string into a function or fail validation regardless of whether the string starts with # ``ext://``. (Default False) # :returns: If ``ext://`` was present or always is True then the imported attribute is returned. # If not, then ``value`` is returned. # :raises ValueError: if the string is not importable # """ # external = False # if isinstance(value, string_types): # if value.startswith('ext://'): # value = value[6:] # external = True # # if not (external or function): # return value # # if isinstance(value, string_types): # attribute = _string_to_attribute(value, type_='function' if function else 'attribute') # else: # attribute = value # # if function: # # Finally check that it is a callable # if not callable(attribute): # raise ValueError('Identifier named {0} is not a function'.format(value)) # return attribute , which may include functions, classes, or code. Output only the next line.
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') except ValueError as e: app_log.exception(e) self.set_status(400) self.finish( {'error': { 'code': 400, 'status': 'BAD_REQUEST', 'message': str(e) }}) return try: headers = AuthProvider.get().get_header() except: self.set_status(403) self.finish({ 'error': { 'code': 403, 'status': 'UNAUTHORIZED', 'message': 'Unable to obtain authentication token' } }) return headers['Content-Type'] = 'application/json' <|code_end|> with the help of current file imports: import json import os import ssl import google.auth from base64 import b64decode from google.auth.exceptions import GoogleAuthError from google.auth.transport.requests import Request from notebook.base.handlers import APIHandler, app_log from tornado import web from tornado.httpclient import AsyncHTTPClient, HTTPClientError, HTTPRequest from .version import VERSION and context from other files: # Path: shared/gcp_jupyterlab_shared/version.py # VERSION = '1.1.3' , which may contain function names, class names, or code. Output only the next line.
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 return mock_fetch def _make_url(self, path): gcp_path = base64.b64encode((self.GCP_URL + path).encode()).decode() return '{}/{}'.format(self.URL, gcp_path) def get_app(self): return Application([ (self.URL + '/(.+)', handlers.ProxyHandler), ]) def test_get(self, mock_auth_provider, mock_client): gcp_path = '/services?consumerId=project:TEST' self._configure_mock_auth_provider(mock_auth_provider) mock_fetch = self._configure_mock_client(mock_client) response = self.fetch(self._make_url(gcp_path)) request = mock_fetch.call_args[0][0] self.assertEqual(200, response.code) self.assertEqual(self.RESPONSE_BODY, response.body) self.assertEqual( '{}{}'.format(self.GCP_URL, '/services?consumerId=project:TEST'), request.url) self.assertEqual('GET', request.method) self.assertEqual(None, request.body) <|code_end|> , predict the next line using imports from the current file: import asyncio import base64 import json import unittest import tornado.testing from unittest.mock import patch, MagicMock from google.auth.exceptions import RefreshError from tornado.web import Application from tornado.httpclient import HTTPClientError from gcp_jupyterlab_shared import handlers, test_data from .version import VERSION and context including class names, function names, and sometimes code from other files: # Path: shared/gcp_jupyterlab_shared/version.py # VERSION = '1.1.3' . Output only the next line.
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 import_roles(self, request, obj): g = GlassFrogImporter(api_key=obj.glassfrog_api_key, organization=obj) g.import_circles(anchor_circle_id=obj.glassfrog_anchor_circle_id) self.message_user(request, 'Roles imported.') import_roles.label = _('Import roles for this organization') def archive_roles(self, request, obj): obj.roles.update(archived=True) self.message_user(request, 'Roles archived.') archive_roles.label = _('Archive existing roles for this organization') def send_reminder(self, request, obj): try: obj.message_for_reminder() self.message_user(request, 'Reminder sent.') except IntegrationError as e: self.message_user(request, 'There was an integration error: %s' % e) send_reminder.label = _('Send reminder') send_reminder.short_description = _('Send a reminder to users that have unfinished feedback older than a week.') change_actions = ('import_users', 'import_roles', 'archive_roles', 'send_reminder') <|code_end|> . Use current file imports: from django.contrib import admin from django.utils.translation import ugettext as _ from django_object_actions import DjangoObjectActions from flindt.integrations.importer import GlassFrogImporter from flindt.round.manager import IntegrationError from .models import Organization and context (classes, functions, or code) from other files: # Path: backend/flindt/organization/models.py # class Organization(FlindtBaseModel): # """ # An organization couples roles and users to a specific organization. # This is useful to archive all roles for an organization. # An organization can also have API_KEYS for different integrations. # """ # # name = models.CharField(unique=True, max_length=255) # glassfrog_api_key = models.CharField(max_length=255, blank=True) # slack_bot_api_key = models.CharField(max_length=255, blank=True) # glassfrog_anchor_circle_id = models.IntegerField(blank=True, null=True) # users = models.ManyToManyField(User, blank=True) # roles = models.ManyToManyField( # Role, # blank=True, # # Don't show archived roles in the admin. # limit_choices_to={'archived': False}, # ) # # def __str__(self): # return self.name # # def message_for_reminder(self): # """ # Send a message to all users that have unfinished feedbacks that is # older than 7 days. # """ # now = timezone.now() # week_ago = now - datetime.timedelta(days=7) # # message = _( # _('Hey, we noticed that people are waiting for your feedback, please help your colleagues by giving them ' # 'some feedback at {}/give-feedback.'). # format(settings.FRONTEND_HOSTNAME) # ) # for user in self.users.all(): # if user.feedback_sent_feedback.filter(status=Feedback.INCOMPLETE, round__start_date__lt=week_ago).exists(): # messenger = Messenger(user=user) # messenger.send_message(message) . Output only the next line.
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: <|code_end|> . Use current file imports: from rest_framework import serializers from .models import ExtraUserInfo, ExtraUserInfoCategory, User and context (classes, functions, or code) from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin . Output only the next line.
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 = ExtraUserInfo fields = ('id', 'category', 'link', 'description') depth = 1 class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): class Meta: <|code_end|> . Use current file imports: from rest_framework import serializers from .models import ExtraUserInfo, ExtraUserInfoCategory, User and context (classes, functions, or code) from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin . Output only the next line.
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(sent_feedback) serializer = FeedbackSerializer(sent_feedback, many=True) return Response(serializer.data) @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( recipient=self.request.user, status=Feedback.COMPLETE) page = self.paginate_queryset(self.filter_queryset(received_feedback)) if page is not None: serializer = FeedbackSerializer(page, many=True) return self.get_paginated_response(serializer.data) received_feedback = self.filter_queryset(received_feedback) serializer = FeedbackSerializer(received_feedback, many=True) return Response(serializer.data) class ExtraUserInfoViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ <|code_end|> with the help of current file imports: from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.filters import OrderingFilter from rest_framework.response import Response from flindt.feedback.models import Feedback from flindt.feedback.serializers import FeedbackSerializer from .models import ExtraUserInfo, ExtraUserInfoCategory, User from .serializers import ExtraUserInfoCategorySerializer, ExtraUserInfoSerializer, UserSerializer and context from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin # # Path: backend/flindt/user/serializers.py # class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfoCategory # fields = ('id', 'name',) # # class ExtraUserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfo # fields = ('id', 'category', 'link', 'description') # depth = 1 # # class UserSerializer(serializers.ModelSerializer): # class Meta: # model = User # fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info') # depth = 2 , which may contain function names, class names, or code. Output only the next line.
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( recipient=self.request.user, status=Feedback.COMPLETE) page = self.paginate_queryset(self.filter_queryset(received_feedback)) if page is not None: serializer = FeedbackSerializer(page, many=True) return self.get_paginated_response(serializer.data) received_feedback = self.filter_queryset(received_feedback) serializer = FeedbackSerializer(received_feedback, many=True) return Response(serializer.data) class ExtraUserInfoViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = ExtraUserInfo.objects.all() serializer_class = ExtraUserInfoSerializer class ExtraUserInfoCategoryViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ <|code_end|> . Use current file imports: from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.filters import OrderingFilter from rest_framework.response import Response from flindt.feedback.models import Feedback from flindt.feedback.serializers import FeedbackSerializer from .models import ExtraUserInfo, ExtraUserInfoCategory, User from .serializers import ExtraUserInfoCategorySerializer, ExtraUserInfoSerializer, UserSerializer and context (classes, functions, or code) from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin # # Path: backend/flindt/user/serializers.py # class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfoCategory # fields = ('id', 'name',) # # class ExtraUserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfo # fields = ('id', 'category', 'link', 'description') # depth = 1 # # class UserSerializer(serializers.ModelSerializer): # class Meta: # model = User # fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info') # depth = 2 . Output only the next line.
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( recipient=self.request.user, status=Feedback.COMPLETE) page = self.paginate_queryset(self.filter_queryset(received_feedback)) if page is not None: serializer = FeedbackSerializer(page, many=True) return self.get_paginated_response(serializer.data) received_feedback = self.filter_queryset(received_feedback) serializer = FeedbackSerializer(received_feedback, many=True) return Response(serializer.data) class ExtraUserInfoViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = ExtraUserInfo.objects.all() serializer_class = ExtraUserInfoSerializer class ExtraUserInfoCategoryViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = ExtraUserInfoCategory.objects.all() <|code_end|> , predict the immediate next line with the help of imports: from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.filters import OrderingFilter from rest_framework.response import Response from flindt.feedback.models import Feedback from flindt.feedback.serializers import FeedbackSerializer from .models import ExtraUserInfo, ExtraUserInfoCategory, User from .serializers import ExtraUserInfoCategorySerializer, ExtraUserInfoSerializer, UserSerializer and context (classes, functions, sometimes code) from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin # # Path: backend/flindt/user/serializers.py # class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfoCategory # fields = ('id', 'name',) # # class ExtraUserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfo # fields = ('id', 'category', 'link', 'description') # depth = 1 # # class UserSerializer(serializers.ModelSerializer): # class Meta: # model = User # fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info') # depth = 2 . Output only the next line.
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_feedback, many=True) return Response(serializer.data) @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( recipient=self.request.user, status=Feedback.COMPLETE) page = self.paginate_queryset(self.filter_queryset(received_feedback)) if page is not None: serializer = FeedbackSerializer(page, many=True) return self.get_paginated_response(serializer.data) received_feedback = self.filter_queryset(received_feedback) serializer = FeedbackSerializer(received_feedback, many=True) return Response(serializer.data) class ExtraUserInfoViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = ExtraUserInfo.objects.all() <|code_end|> with the help of current file imports: from rest_framework import viewsets from rest_framework.decorators import list_route from rest_framework.filters import OrderingFilter from rest_framework.response import Response from flindt.feedback.models import Feedback from flindt.feedback.serializers import FeedbackSerializer from .models import ExtraUserInfo, ExtraUserInfoCategory, User from .serializers import ExtraUserInfoCategorySerializer, ExtraUserInfoSerializer, UserSerializer and context from other files: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin # # Path: backend/flindt/user/serializers.py # class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfoCategory # fields = ('id', 'name',) # # class ExtraUserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfo # fields = ('id', 'category', 'link', 'description') # depth = 1 # # class UserSerializer(serializers.ModelSerializer): # class Meta: # model = User # fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info') # depth = 2 , which may contain function names, class names, or code. Output only the next line.
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.decorators import list_route from rest_framework.filters import OrderingFilter from rest_framework.response import Response from flindt.feedback.models import Feedback from flindt.feedback.serializers import FeedbackSerializer from .models import ExtraUserInfo, ExtraUserInfoCategory, User from .serializers import ExtraUserInfoCategorySerializer, ExtraUserInfoSerializer, UserSerializer and context (class names, function names, or code) available: # Path: backend/flindt/user/models.py # class ExtraUserInfo(FlindtBaseModel): # """ # Used to link extra user information to a user. This can be used to add # arbitrary information on a user. It also features a category, so that # information can be presented with a corresponding category. # # Example: # This can be used to link a DISC profile to a user like so: # >>> category = ExtraUserInfoCategory.objects.create(name='DISC profile') # >>> extrauserinfo = ExtraUserInfo.object.create(category=category,link='http://example.com/keycardforjohndoe') # >>> User.objects.create(extra_info=[extrauserinfo], first_name='John', last_name='Doe') # """ # category = models.ForeignKey('ExtraUserInfoCategory', on_delete=models.CASCADE) # link = models.URLField(_('link'), blank=True) # description = models.TextField(_('description'), blank=True) # # def __str__(self): # ret = '{category}: {info}' # if self.link: # return ret.format(category=self.category, info=self.link) # if self.description: # return ret.format(category=self.category, info=self.description) # else: # return ret.format(category=self.category, info='empty') # # class ExtraUserInfoCategory(FlindtBaseModel): # """ # Provide a category for extrauserinfo. # """ # name = models.CharField(_('name'), max_length=255) # # def __str__(self): # return self.name # # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin # # Path: backend/flindt/user/serializers.py # class ExtraUserInfoCategorySerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfoCategory # fields = ('id', 'name',) # # class ExtraUserInfoSerializer(serializers.ModelSerializer): # class Meta: # model = ExtraUserInfo # fields = ('id', 'category', 'link', 'description') # depth = 1 # # class UserSerializer(serializers.ModelSerializer): # class Meta: # model = User # fields = ('id', 'first_name', 'last_name', 'prefix', 'glassfrog_id', 'extra_info') # depth = 2 . Output only the next line.
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 other files: # Path: backend/flindt/role/tests/factories.py # class RoleFactory(factory.django.DjangoModelFactory): # name = LazyAttribute(lambda o: faker.word()) # purpose = LazyAttribute(lambda o: faker.bs()) # # @factory.post_generation # def users(self, create, extracted, **kwargs): # if create: # # Get all users, convert to list, shuffle and get between 1 and 6 users. # users = list(User.objects.all()) # random.shuffle(users) # self.users.add(*users[:random.randint(1, 6)]) # # class Meta: # model = Role , which may include functions, classes, or code. Output only the next line.
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 and context (classes, functions, sometimes code) from other files: # Path: backend/flindt/feedback/tests/factories.py # class FeedbackFactory(DjangoModelFactory): # date = FuzzyDateTime(past_date, future_date) # recipient = factory.Iterator(User.objects.all()) # sender = factory.Iterator(User.objects.all()) # status = FuzzyChoice(dict(Feedback.STATUS_CHOICES).keys()) # how_recognizable = FuzzyInteger(0, 10) # how_valuable = FuzzyInteger(0, 10) # actionable = FuzzyChoice([True, False]) # individual = SubFactory(FeedbackOnIndividualFactory) # # class Meta: # model = Feedback . Output only the next line.
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 anchor_circle. """ API_BASE_URL = 'https://glassfrog.holacracy.org/api/v3/' def __init__(self, api_key, organization=None): self.api_key = api_key self.organization = organization <|code_end|> , generate the next line using the imports in this file: import json import logging import requests from flindt.role.models import Role from flindt.user.models import User from .models import RoleImportRun and context (functions, classes, or occasionally code) from other files: # Path: backend/flindt/integrations/models.py # class RoleImportRun(FlindtBaseModel): # """ # RoleImport is used to relate import roles to a specific import run. # """ # # started = models.DateTimeField(auto_now=True) # roles = models.ManyToManyField(Role) # # def __str__(self): # return 'import started at {}'.format(self.started) . Output only the next line.
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='Password confirmation', widget=forms.PasswordInput) class Meta: <|code_end|> . Use current file imports: from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Group from .models import User and context (classes, functions, or code) from other files: # Path: backend/flindt/user/models.py # class User(PermissionsMixin, AbstractBaseUser): # USERNAME_FIELD = 'email' # # email = models.EmailField( # unique=True # ) # first_name = models.CharField( # max_length=255, # blank=True, # ) # last_name = models.CharField( # max_length=255, # blank=True # ) # prefix = models.CharField( # max_length=255, # blank=True, # ) # # TODO: FEED-26: Use ExtraUserInfo for the glassfrog_id. That way we can # # cleanly extend the import to work for Nestr et al. # glassfrog_id = models.IntegerField( # blank=True, # null=True, # ) # slack_user_name = models.CharField( # blank=True, # max_length=255, # ) # extra_info = models.ManyToManyField( # 'ExtraUserInfo', # blank=True, # ) # is_active = models.BooleanField(default=True) # is_admin = models.BooleanField(default=False) # # objects = UserManager() # # def get_full_name(self): # return self.first_name # # def get_short_name(self): # return '{} {}'.format(self.first_name, self.last_name) # # def __str__(self): # return self.email # # def has_perm(self, perm, obj=None): # """ # Does the user have a specific permission? # """ # # TODO: FEED-27: Implement the correct permission system. # # Simplest possible answer for now: Yes, always # return True # # def has_module_perms(self, app_label): # """ # Does the user have permissions to view the app `app_label`? # """ # # Simplest possible answer: Yes, always # return True # # @property # def is_staff(self): # """ # Is the user a member of staff? # """ # # Simplest possible answer: All admins are staff # return self.is_admin . Output only the next line.
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_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return (('is_circle', _('Is circle')), ('is_not_circle', _('Is not circle')),) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ if self.value() == 'is_circle': return queryset.filter(children__isnull=False) elif self.value() == 'is_not_circle': return queryset.filter(children__isnull=True) <|code_end|> , generate the next line using the imports in this file: from django.contrib import admin from django.utils.translation import ugettext as _ from .models import Role and context (functions, classes, or occasionally code) from other files: # Path: backend/flindt/role/models.py # class Role(FlindtBaseModel): # """ # The Role model is used to store information about roles. # # It is primarily designed to capture information about roles # in the holacratic sense of the word, but can also be used to # reflect a more traditional organisation. # """ # name = models.TextField() # purpose = models.TextField(blank=True, default='') # accountabilities = models.TextField(blank=True, default='') # Used to store JSON # domains = models.TextField(blank=True, default='') # Used to store JSON # parent = models.ForeignKey('Role', related_name='children', blank=True, null=True, on_delete=models.CASCADE) # users = models.ManyToManyField(User, blank=True) # archived = models.BooleanField(default=False) # # def __str__(self): # return self.name # # @property # def is_circle(self): # """ # True if the circle has children. # """ # return self.children.exists() is True # # @property # def is_anchor(self): # """ # True if the circle has no parents. # """ # return self.parent is None # # def descendants(self): # """ # Return all descendants of `self` in a list. # # TODO: FEED-50: descendants should be a method on a manager returning a # queryset. # """ # descendants = [] # children = self.children.all() # descendants.extend(children) # for child in children: # descendants.extend(child.descendants()) # return descendants # # def archive(self): # """ # Archive this role and all roles under it. # # TODO: FEED-50: If descendants is a queryset, replace this with one # update() # """ # self.archived = True # self.save() # for role in self.descendants(): # role.archived = True # role.save() # logger.info('role: {} and all its descendants have been archived.'.format(self)) . Output only the next line.
@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 convert the domains to a correct json format. """ # Try to load the obj.accountabilities as a json. If this fails return the # string. try: return json.loads(obj.accountabilities) except ValueError: return obj.accountabilities def get_domains(self, obj): """ Override the getter for domains to try and convert the domains to a correct json format. """ # Try to load the obj.domains as a json. If this fails return the # string. try: return json.loads(obj.domains) except ValueError: return obj.domains class Meta: <|code_end|> using the current file's imports: import json from rest_framework import serializers from .models import Role and any relevant context from other files: # Path: backend/flindt/role/models.py # class Role(FlindtBaseModel): # """ # The Role model is used to store information about roles. # # It is primarily designed to capture information about roles # in the holacratic sense of the word, but can also be used to # reflect a more traditional organisation. # """ # name = models.TextField() # purpose = models.TextField(blank=True, default='') # accountabilities = models.TextField(blank=True, default='') # Used to store JSON # domains = models.TextField(blank=True, default='') # Used to store JSON # parent = models.ForeignKey('Role', related_name='children', blank=True, null=True, on_delete=models.CASCADE) # users = models.ManyToManyField(User, blank=True) # archived = models.BooleanField(default=False) # # def __str__(self): # return self.name # # @property # def is_circle(self): # """ # True if the circle has children. # """ # return self.children.exists() is True # # @property # def is_anchor(self): # """ # True if the circle has no parents. # """ # return self.parent is None # # def descendants(self): # """ # Return all descendants of `self` in a list. # # TODO: FEED-50: descendants should be a method on a manager returning a # queryset. # """ # descendants = [] # children = self.children.all() # descendants.extend(children) # for child in children: # descendants.extend(child.descendants()) # return descendants # # def archive(self): # """ # Archive this role and all roles under it. # # TODO: FEED-50: If descendants is a queryset, replace this with one # update() # """ # self.archived = True # self.save() # for role in self.descendants(): # role.archived = True # role.save() # logger.info('role: {} and all its descendants have been archived.'.format(self)) . Output only the next line.
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: <|code_end|> , generate the next line using the imports in this file: import os import json from sysdescrparser import sysdescrparser and context (functions, classes, or occasionally code) from other files: # Path: sysdescrparser/sysdescrparser.py # def sysdescrparser(sysdescr): # """SNMP sysDescr parsing. # # Args: # # :sysdescr(str): SNMP sysDescr raw string. # # Returns: # # :SysDescr sub-class instance: SysDescr is abstract super class. # Each vendor class extends Sysdescr class and following attributes. # # :vendor(str): Vendor name. # :model(str): Product Model name. # :os(str): OS name. # :version(str): OS version name. # # Example: # # .. code-block:: python # # >>> from sysdescrparser import sysdescrparser # >>> sysdescr = sysdescrparser('Juniper Networks, Inc. ...') # >>> sysdescr.vendor # 'JUNIPER' # >>> sysdescr.model # 'ex2200-48t-4g' # >>> sysdescr.os # 'JUNOS' # >>> sysdescr.version # '10.2R1.8' # # Support: # # Currently supported Vendor and OS. # # https://github.com/mtoshi/sysdescrparser/blob/master/samples/sample_data.json # # See also: # # https://github.com/mtoshi/sysdescrparser/blob/master/README.rst # # """ # # # # cisco nxos # # # obj = CiscoNXOS(sysdescr) # if obj.parse(): # return obj # # # # cisco iosxr # # # obj = CiscoIOSXR(sysdescr) # if obj.parse(): # return obj # # # # cisco ios # # # obj = CiscoIOS(sysdescr) # if obj.parse(): # return obj # # # # juniper junos # # # obj = JuniperJunos(sysdescr) # if obj.parse(): # return obj # # # # juniper screenos # # # obj = JuniperScreenOS(sysdescr) # if obj.parse(): # return obj # # # # brocade ironware # # # obj = BrocadeIronWare(sysdescr) # if obj.parse(): # return obj # # # # brocade serveriron # # # obj = BrocadeServerIron(sysdescr) # if obj.parse(): # return obj # # # # brocade networkos # # # obj = BrocadeNetworkOS(sysdescr) # if obj.parse(): # return obj # # # # foundry ironware # # # obj = FoundryIronWare(sysdescr) # if obj.parse(): # return obj # # # # arista eos # # # obj = AristaEOS(sysdescr) # if obj.parse(): # return obj # # # # extreme xos # # # obj = ExtremeXOS(sysdescr) # if obj.parse(): # return obj # # # # hp procurve # # # obj = HPProCurve(sysdescr) # if obj.parse(): # return obj # # # # paloalto panos # # # obj = PaloAltoPANOS(sysdescr) # if obj.parse(): # return obj # # # # a10 acos # # # obj = A10ACOS(sysdescr) # if obj.parse(): # return obj # # # # citrix netscaler # # # obj = CitrixNetscaler(sysdescr) # if obj.parse(): # return obj # # # # linux # # # obj = Linux(sysdescr) # if obj.parse(): # return obj # # # # sun sunos # # # obj = SunSUNOS(sysdescr) # if obj.parse(): # return obj # # # # freebsd # # # obj = FreeBSD(sysdescr) # if obj.parse(): # return obj # # # # iij seil # # # obj = IIJSeil(sysdescr) # if obj.parse(): # return obj # # # # yamaha rtx # # # obj = YamahaRTX(sysdescr) # if obj.parse(): # return obj # # # # Unknown # # # obj = Unknown(sysdescr) # if obj.parse(): # return obj # # return None . Output only the next line.
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) modified because the # whole @reader/@writer synchronization relies on it! class Node(object): """ Wrapper for h5py.Node """ def __init__(self, file, path): """ Args: file: full path to hdf5 file path: full path to the hdf5 node (not to be confused with path of the file) """ self.file = file self._path = path self.attrs = AttributeManager(self.file, self._path) <|code_end|> . Use current file imports: import os import h5py from .sync import reader, writer from hurray.server.log import app_log and context (classes, functions, or code) from other files: # Path: hurray/swmr/sync.py # def reader(f): # """ # Decorates methods reading a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps reading functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_read(self.file) # result = f(self, *args, **kwargs) # critical section # return result # finally: # SWMR_SYNC.end_read(self.file) # # return func_wrapper # # def writer(f): # """ # Decorates methods writing to a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps writing functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_write(self.file) # return_val = f(self, *args, **kwargs) # return return_val # finally: # SWMR_SYNC.end_write(self.file) # # return func_wrapper # # Path: hurray/server/log.py # def _stderr_supports_color(): # def _unicode(value): # def _safe_unicode(s): # def __init__(self, color=True, fmt=DEFAULT_FORMAT, # datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS): # def format(self, record): # def enable_pretty_logging(options=None, logger=None): # def define_logging_options(options=None): # _TO_UNICODE_TYPES = (unicode_type, type(None)) # DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s' # DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S' # DEFAULT_COLORS = { # logging.DEBUG: 4, # Blue # logging.INFO: 2, # Green # logging.WARNING: 3, # Yellow # logging.ERROR: 1, # Red # } # class LogFormatter(logging.Formatter): . Output only the next line.
@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 File(name=self.file, mode="r") if isinstance(node, h5py.Group): return Group(file=self.file, path=node.name) elif isinstance(node, h5py.Dataset): return Dataset(file=self.file, path=node.name) else: raise TypeError('unknown h5py node object') class Group(Node): """ Wrapper for h5py.Group """ def __init__(self, file, path): Node.__init__(self, file, path) def __repr__(self): return "<HDF5 Group (path={0})>".format(self.path) <|code_end|> , generate the next line using the imports in this file: import os import h5py from .sync import reader, writer from hurray.server.log import app_log and context (functions, classes, or occasionally code) from other files: # Path: hurray/swmr/sync.py # def reader(f): # """ # Decorates methods reading a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps reading functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_read(self.file) # result = f(self, *args, **kwargs) # critical section # return result # finally: # SWMR_SYNC.end_read(self.file) # # return func_wrapper # # def writer(f): # """ # Decorates methods writing to a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps writing functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_write(self.file) # return_val = f(self, *args, **kwargs) # return return_val # finally: # SWMR_SYNC.end_write(self.file) # # return func_wrapper # # Path: hurray/server/log.py # def _stderr_supports_color(): # def _unicode(value): # def _safe_unicode(s): # def __init__(self, color=True, fmt=DEFAULT_FORMAT, # datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS): # def format(self, record): # def enable_pretty_logging(options=None, logger=None): # def define_logging_options(options=None): # _TO_UNICODE_TYPES = (unicode_type, type(None)) # DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s' # DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S' # DEFAULT_COLORS = { # logging.DEBUG: 4, # Blue # logging.INFO: 2, # Green # logging.WARNING: 3, # Yellow # logging.ERROR: 1, # Red # } # class LogFormatter(logging.Formatter): . Output only the next line.
@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__(self, key): with h5py.File(self.file, 'r') as f: group = f[self.path] return key in group @writer def __delitem__(self, key): with h5py.File(self.file, 'r+') as f: group = f[self.path] del group[key] class File(Group): """ Wrapper for h5py.File """ def __init__(self, name, mode="r", *args, **kwargs): """ try to open/create an h5py.File object """ <|code_end|> , predict the next line using imports from the current file: import os import h5py from .sync import reader, writer from hurray.server.log import app_log and context including class names, function names, and sometimes code from other files: # Path: hurray/swmr/sync.py # def reader(f): # """ # Decorates methods reading a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps reading functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_read(self.file) # result = f(self, *args, **kwargs) # critical section # return result # finally: # SWMR_SYNC.end_read(self.file) # # return func_wrapper # # def writer(f): # """ # Decorates methods writing to a shared resource # """ # # @wraps(f) # def func_wrapper(self, *args, **kwargs): # """ # Wraps writing functions. # """ # with handle_exit(append=True): # try: # SWMR_SYNC.start_write(self.file) # return_val = f(self, *args, **kwargs) # return return_val # finally: # SWMR_SYNC.end_write(self.file) # # return func_wrapper # # Path: hurray/server/log.py # def _stderr_supports_color(): # def _unicode(value): # def _safe_unicode(s): # def __init__(self, color=True, fmt=DEFAULT_FORMAT, # datefmt=DEFAULT_DATE_FORMAT, colors=DEFAULT_COLORS): # def format(self, record): # def enable_pretty_logging(options=None, logger=None): # def define_logging_options(options=None): # _TO_UNICODE_TYPES = (unicode_type, type(None)) # DEFAULT_FORMAT = '%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s' # DEFAULT_DATE_FORMAT = '%y%m%d %H:%M:%S' # DEFAULT_COLORS = { # logging.DEBUG: 4, # Blue # logging.INFO: 2, # Green # logging.WARNING: 3, # Yellow # logging.ERROR: 1, # Red # } # class LogFormatter(logging.Formatter): . Output only the next line.
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): try: sum = datetime.timedelta() start = 0 while start < len(value): m = self._TIMEDELTA_PATTERN.match(value, start) if not m: raise Exception() num = float(m.group(1)) units = m.group(2) or 'seconds' units = self._TIMEDELTA_ABBREV_DICT.get(units, units) sum += datetime.timedelta(**{units: num}) start = m.end() return sum except Exception: raise def _parse_bool(self, value): return value.lower() not in ("false", "0", "f") def _parse_string(self, value): <|code_end|> with the help of current file imports: import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in and context from other files: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): , which may contain function names, class names, or code. Output only the next line.
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 final: self.run_parse_callbacks() return remaining def parse_config_file(self, path, final=True): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. .. versionchanged:: 4.1 Config files are now always interpreted as utf-8 instead of the system default encoding. .. versionchanged:: 4.4 The special variable ``__file__`` is available inside config files, specifying the absolute path to the config file itself. """ config = {'__file__': os.path.abspath(path)} with open(path, 'rb') as f: <|code_end|> . Use current file imports: import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in and context (classes, functions, or code) from other files: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): . Output only the next line.
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 options.parse_config_file(path, final=final) def print_help(file=None): """Prints all the command line options to stderr (or another file). See `OptionParser.print_help`. """ return options.print_help(file) def add_parse_callback(callback): """Adds a parse callback, to be invoked when option parsing is done. See `OptionParser.add_parse_callback` """ options.add_parse_callback(callback) # Default options <|code_end|> with the help of current file imports: import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in and context from other files: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): , which may contain function names, class names, or code. Output only the next line.
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.sort(key=lambda option: option.name) for option in o: # Always print names with dashes in a CLI context. prefix = self._normalize_name(option.name) if option.metavar: prefix += "=" + option.metavar description = option.help or "" if option.default is not None and option.default != '': description += " (default %s)" % option.default lines = textwrap.wrap(description, 79 - 35) if len(prefix) > 30 or len(lines) == 0: lines.insert(0, '') print(" --%-30s %s" % (prefix, lines[0]), file=file) for line in lines[1:]: print("%-34s %s" % (' ', line), file=file) print(file=file) def _help_callback(self, value): if value: self.print_help() sys.exit(0) def add_parse_callback(self, callback): """Adds a parse callback, to be invoked when option parsing is done.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in and context: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): which might include code, classes, or functions. Output only the next line.
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 a new attribute in ``__dict__``). _Mockable's getattr and setattr pass through to the underlying OptionParser, and delattr undoes the effect of a previous setattr. """ def __init__(self, options): # Modify __dict__ directly to bypass __setattr__ self.__dict__['_options'] = options self.__dict__['_originals'] = {} def __getattr__(self, name): return getattr(self._options, name) def __setattr__(self, name, value): assert name not in self._originals, "don't reuse mockable objects" self._originals[name] = getattr(self._options, name) setattr(self._options, name, value) def __delattr__(self, name): setattr(self._options, name, self._originals.pop(name)) class _Option(object): UNSET = object() <|code_end|> . Use current file imports: (import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in) and context including class names, function names, or small code snippets from other files: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): . Output only the next line.
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 final: self.run_parse_callbacks() return remaining def parse_config_file(self, path, final=True): """Parses and loads the Python config file at the given path. If ``final`` is ``False``, parse callbacks will not be run. This is useful for applications that wish to combine configurations from multiple sources. .. versionchanged:: 4.1 Config files are now always interpreted as utf-8 instead of the system default encoding. .. versionchanged:: 4.4 The special variable ``__file__`` is available inside config files, specifying the absolute path to the config file itself. """ config = {'__file__': os.path.abspath(path)} with open(path, 'rb') as f: <|code_end|> . Use current file imports: import datetime import numbers import re import sys import os import textwrap from hurray.server.escape import _unicode, native_str from hurray.server.log import define_logging_options from hurray.server import stack_context from hurray.server.util import basestring_type, exec_in and context (classes, functions, or code) from other files: # Path: hurray/server/escape.py # _UTF8_TYPES = (bytes, type(None)) # _TO_UNICODE_TYPES = (unicode_type, type(None)) # def utf8(value): # def to_unicode(value): # # Path: hurray/server/log.py # def define_logging_options(options=None): # """Add logging-related flags to ``options``. # # These options are present automatically on the default options instance; # this method is only necessary if you have created your own `.OptionParser`. # # .. versionadded:: 4.2 # This function existed in prior versions but was broken and undocumented until 4.2. # """ # if options is None: # # late import to prevent cycle # import hurray.options # options = hurray.options.options # options.define("logging", default="info", # help=("Set the Python log level. If 'none', hurray won't touch the " # "logging configuration."), # metavar="debug|info|warning|error|none") # options.define("log_to_stderr", type=bool, default=None, # help=("Send log output to stderr (colorized if possible). " # "By default use stderr if --log_file_prefix is not set and " # "no other logging is configured.")) # options.define("log_file_prefix", type=str, default=None, metavar="PATH", # help=("Path prefix for log files. " # "Note that if you are running multiple hurray processes, " # "log_file_prefix must be different for each of them (e.g. " # "include the port number)")) # options.define("log_file_max_size", type=int, default=100 * 1000 * 1000, # help="max size of log files before rollover") # options.define("log_file_num_backups", type=int, default=10, # help="number of log files to keep") # # options.define("log_rotate_when", type=str, default='midnight', # help=("specify the type of TimedRotatingFileHandler interval " # "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) # options.define("log_rotate_interval", type=int, default=1, # help="The interval value of timed rotating") # # options.define("log_rotate_mode", type=str, default='size', # help="The mode of rotating files(time or size)") # # options.add_parse_callback(lambda: enable_pretty_logging(options)) # # Path: hurray/server/stack_context.py # class StackContextInconsistentError(Exception): # class _State(threading.local): # class StackContext(object): # class ExceptionStackContext(object): # class NullContext(object): # def __init__(self): # def __init__(self, context_factory): # def _deactivate(self): # def enter(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __init__(self, exception_handler): # def _deactivate(self): # def exit(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def __enter__(self): # def __exit__(self, type, value, traceback): # def _remove_deactivated(contexts): # def wrap(fn): # def null_wrapper(*args, **kwargs): # def wrapped(*args, **kwargs): # def _handle_exception(tail, exc): # def run_with_stack_context(context, func): # # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): . Output only the next line.
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.msgpack_ext import encode, decode from numpy.testing import assert_array_equal and any relevant context from other files: # Path: hurray/msgpack_ext.py # def encode(obj): # """ # Encode numpy arrays and slices # :param obj: object to serialize # :return: dictionary with encoded array or slice # """ # if isinstance(obj, np.ndarray): # arr = header_data_from_array_1_0(obj) # arr['arraydata'] = obj.tostring() # arr['__ndarray__'] = True # return arr # elif isinstance(obj, slice): # return { # '__slice__': (obj.start, obj.stop, obj.step) # } # elif isclass(obj) and issubclass(obj, np.number): # # make sure numpy type classes such as np.float64 (used, e.g., as dtype # # arguments) are serialized to strings # return obj().dtype.name # elif isinstance(obj, np.dtype): # return obj.name # elif isinstance(obj, np.number): # # convert to Python scalar # return np.asscalar(obj) # elif isinstance(obj, File): # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_FILE, # RESPONSE_NODE_PATH: obj.path, # } # return data # elif isinstance(obj, Group): # # TODO include attrs? # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_GROUP, # RESPONSE_NODE_PATH: obj.path, # } # return data # elif isinstance(obj, Dataset): # # TODO include attrs? # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_DATASET, # RESPONSE_NODE_PATH: obj.path, # RESPONSE_NODE_SHAPE: obj.shape, # RESPONSE_NODE_DTYPE: obj.dtype, # } # return data # # return obj # # def decode(obj): # """ # Decode numpy arrays and slices # :param obj: object to decode # :return: numpy array or slice # """ # # if '__ndarray__' in obj: # arr = np.fromstring(obj['arraydata'], dtype=np.dtype(obj['descr'])) # shape = obj['shape'] # arr.shape = shape # if obj['fortran_order']: # arr.shape = shape[::-1] # arr = arr.transpose() # return arr # elif '__slice__' in obj: # return slice(*obj['__slice__']) # # return obj . Output only the next line.
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) unpacked_nparray = msgpack.unpackb(packed_nparray, <|code_end|> . Use current file imports: import unittest import msgpack import numpy as np from hurray.msgpack_ext import encode, decode from numpy.testing import assert_array_equal and context (classes, functions, or code) from other files: # Path: hurray/msgpack_ext.py # def encode(obj): # """ # Encode numpy arrays and slices # :param obj: object to serialize # :return: dictionary with encoded array or slice # """ # if isinstance(obj, np.ndarray): # arr = header_data_from_array_1_0(obj) # arr['arraydata'] = obj.tostring() # arr['__ndarray__'] = True # return arr # elif isinstance(obj, slice): # return { # '__slice__': (obj.start, obj.stop, obj.step) # } # elif isclass(obj) and issubclass(obj, np.number): # # make sure numpy type classes such as np.float64 (used, e.g., as dtype # # arguments) are serialized to strings # return obj().dtype.name # elif isinstance(obj, np.dtype): # return obj.name # elif isinstance(obj, np.number): # # convert to Python scalar # return np.asscalar(obj) # elif isinstance(obj, File): # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_FILE, # RESPONSE_NODE_PATH: obj.path, # } # return data # elif isinstance(obj, Group): # # TODO include attrs? # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_GROUP, # RESPONSE_NODE_PATH: obj.path, # } # return data # elif isinstance(obj, Dataset): # # TODO include attrs? # data = { # RESPONSE_H5FILE: obj.file, # RESPONSE_NODE_TYPE: NODE_TYPE_DATASET, # RESPONSE_NODE_PATH: obj.path, # RESPONSE_NODE_SHAPE: obj.shape, # RESPONSE_NODE_DTYPE: obj.dtype, # } # return data # # return obj # # def decode(obj): # """ # Decode numpy arrays and slices # :param obj: object to decode # :return: numpy array or slice # """ # # if '__ndarray__' in obj: # arr = np.fromstring(obj['arraydata'], dtype=np.dtype(obj['descr'])) # shape = obj['shape'] # arr.shape = shape # if obj['fortran_order']: # arr.shape = shape[::-1] # arr = arr.transpose() # return arr # elif '__slice__' in obj: # return slice(*obj['__slice__']) # # return obj . Output only the next line.
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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Posix implementations of platform-specific functionality.""" from __future__ import absolute_import, division, print_function, with_statement def set_close_exec(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) def _set_nonblocking(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) <|code_end|> , generate the next line using the imports in this file: import fcntl import os from hurray.server.platform import interface and context (functions, classes, or occasionally code) from other files: # Path: hurray/server/platform/interface.py # def set_close_exec(fd): # def fileno(self): # def write_fileno(self): # def wake(self): # def consume(self): # def close(self): # def monotonic_time(): # class Waker(object): . Output only the next line.
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: except ImportError: curses = None # Logger objects for internal hurray use access_log = logging.getLogger("hurray.access") app_log = logging.getLogger("hurray.application") gen_log = logging.getLogger("hurray.general") def _stderr_supports_color(): color = False if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): try: curses.setupterm() if curses.tigetnum("colors") > 0: color = True except Exception: pass return color <|code_end|> . Use current file imports: import logging import logging.handlers import sys import curses # type: ignore import hurray.options import hurray.options from hurray.server.util import unicode_type, basestring_type and context (classes, functions, or code) from other files: # Path: hurray/server/util.py # PY3 = sys.version_info >= (3,) # def cast(typ, x): # def import_object(name): # def raise_exc_info(exc_info): # def exec_in(code, glob, loc=None): # def errno_from_exception(e): # def __new__(cls, *args, **kwargs): # def configurable_base(cls): # def configurable_default(cls): # def initialize(self): # def configure(cls, impl, **kwargs): # def configured_class(cls): # def _save_configuration(cls): # def _restore_configuration(cls, saved): # def __init__(self, func, name): # def _getargnames(self, func): # def get_old_value(self, args, kwargs, default=None): # def replace(self, new_value, args, kwargs): # def timedelta_to_seconds(td): # class Configurable(object): # class ArgReplacer(object): . Output only the next line.
_TO_UNICODE_TYPES = (unicode_type, type(None))