Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>__author__ = 'amelie' def branch_and_bound_side_effect(node_creator, y_length, alphabet, max_time): solution_dict = {1: ('a', 1), 2: ('ba', 3)} return solution_dict[y_length] class TestGenericStringModel(unittest2.TestCase): def setUp(self): self.setup_feature_space() self.setup_fit_parameters() self.setup_graph_builder() self.setup_branch_and_bound() self.alphabet = ['a', 'b', 'c'] self.sigma_position = 0.5 <|code_end|> using the current file's imports: import unittest2 import numpy import numpy.testing from mock import patch, Mock from preimage.models.generic_string_model import GenericStringModel from preimage.learners.structured_krr import InferenceFitParameters and any relevant context from other files: # Path: preimage/models/generic_string_model.py # class GenericStringModel(Model): # def __init__(self, alphabet, n, is_using_length=True, seed=42, max_time=30, sigma_position=1.): # Model.__init__(self, alphabet, n, is_using_length) # self._graph_builder = GraphBuilder(alphabet, n) # self._is_normalized = True # self._seed = seed # self._max_time = max_time # self._sigma_position = sigma_position # self._n_grams = list(get_n_grams(alphabet, n)) # self._n_gram_to_index = get_n_gram_to_index(alphabet, n) # # def fit(self, inference_parameters): # Model.fit(self, inference_parameters) # self._feature_space_ = GenericStringFeatureSpace(self._alphabet, self._n, inference_parameters.Y_train, # self._sigma_position, self._is_normalized) # # def predict(self, Y_weights, y_lengths): # if self._is_using_length: # self._verify_y_lengths_is_not_none_when_use_length(y_lengths) # Y_predictions = self._predict_with_length(Y_weights, y_lengths) # else: # Y_predictions = self._predict_without_length(Y_weights) # return Y_predictions # # def _predict_with_length(self, Y_weights, y_lengths): # Y_predictions = [] # for y_weights, y_length in zip(Y_weights, y_lengths): # n_gram_weights = self._feature_space_.compute_weights(y_weights, y_length) # graph = self._graph_builder.build_graph(n_gram_weights, y_length) # node_creator = get_gs_node_creator(self._n, graph, n_gram_weights, y_length, self._n_gram_to_index, # self._n_grams, self._sigma_position) # y_predicted, y_bound = branch_and_bound(node_creator, y_length, self._alphabet, self._max_time) # Y_predictions.append(y_predicted) # return Y_predictions # # def _predict_without_length(self, Y_weights): # Y_predictions = [] # for y_weights in Y_weights: # n_gram_weights = self._feature_space_.compute_weights(y_weights, self._max_length_) # graph = self._graph_builder.build_graph(n_gram_weights, self._max_length_) # node_creator = get_gs_node_creator(self._n, graph, n_gram_weights, self._max_length_, # self._n_gram_to_index, self._n_grams, self._sigma_position) # y_predicted, y_bound = branch_and_bound_no_length(node_creator, self._min_length_, self._max_length_, # self._alphabet, self._max_time) # Y_predictions.append(y_predicted) # return Y_predictions # # Path: preimage/learners/structured_krr.py # class InferenceFitParameters: # """Parameters for the inference model. # # That way inference_model.fit(parameters) doesn't have unused parameters but only access the one it needs # . # Attributes # ---------- # weights : array, shape = [n_samples, n_samples] # Learned weights, where n_samples is the number of training samples. # gram_matrix : array, shape = [n_samples, n_samples] # Gram_matrix of the training samples. # Y_train : array, shape = [n_samples, ] # Training strings. # y_lengths : array, shape = [n_samples] # Length of each training string in Y_train. # """ # def __init__(self, weights, gram_matrix, Y, y_lengths): # self.weights = weights # self.gram_matrix = gram_matrix # self.Y_train = Y # self.y_lengths = y_lengths . Output only the next line.
self.model_with_length = GenericStringModel(self.alphabet, n=1, is_using_length=True,
Next line prediction: <|code_start|>__author__ = 'amelie' def branch_and_bound_side_effect(node_creator, y_length, alphabet, max_time): solution_dict = {1: ('a', 1), 2: ('ba', 3)} return solution_dict[y_length] class TestGenericStringModel(unittest2.TestCase): def setUp(self): self.setup_feature_space() self.setup_fit_parameters() self.setup_graph_builder() self.setup_branch_and_bound() self.alphabet = ['a', 'b', 'c'] self.sigma_position = 0.5 self.model_with_length = GenericStringModel(self.alphabet, n=1, is_using_length=True, sigma_position=self.sigma_position) self.model_no_length = GenericStringModel(self.alphabet, n=1, is_using_length=False, sigma_position=self.sigma_position) self.Y_weights = numpy.array([[1], [0]]) self.y_lengths = [1, 2] def setup_fit_parameters(self): self.max_train_length = 2 self.min_train_length = 1 self.weights = numpy.array([[1, 2]]) self.gram_matrix = numpy.array([[1, 0], [0, 1]]) <|code_end|> . Use current file imports: (import unittest2 import numpy import numpy.testing from mock import patch, Mock from preimage.models.generic_string_model import GenericStringModel from preimage.learners.structured_krr import InferenceFitParameters) and context including class names, function names, or small code snippets from other files: # Path: preimage/models/generic_string_model.py # class GenericStringModel(Model): # def __init__(self, alphabet, n, is_using_length=True, seed=42, max_time=30, sigma_position=1.): # Model.__init__(self, alphabet, n, is_using_length) # self._graph_builder = GraphBuilder(alphabet, n) # self._is_normalized = True # self._seed = seed # self._max_time = max_time # self._sigma_position = sigma_position # self._n_grams = list(get_n_grams(alphabet, n)) # self._n_gram_to_index = get_n_gram_to_index(alphabet, n) # # def fit(self, inference_parameters): # Model.fit(self, inference_parameters) # self._feature_space_ = GenericStringFeatureSpace(self._alphabet, self._n, inference_parameters.Y_train, # self._sigma_position, self._is_normalized) # # def predict(self, Y_weights, y_lengths): # if self._is_using_length: # self._verify_y_lengths_is_not_none_when_use_length(y_lengths) # Y_predictions = self._predict_with_length(Y_weights, y_lengths) # else: # Y_predictions = self._predict_without_length(Y_weights) # return Y_predictions # # def _predict_with_length(self, Y_weights, y_lengths): # Y_predictions = [] # for y_weights, y_length in zip(Y_weights, y_lengths): # n_gram_weights = self._feature_space_.compute_weights(y_weights, y_length) # graph = self._graph_builder.build_graph(n_gram_weights, y_length) # node_creator = get_gs_node_creator(self._n, graph, n_gram_weights, y_length, self._n_gram_to_index, # self._n_grams, self._sigma_position) # y_predicted, y_bound = branch_and_bound(node_creator, y_length, self._alphabet, self._max_time) # Y_predictions.append(y_predicted) # return Y_predictions # # def _predict_without_length(self, Y_weights): # Y_predictions = [] # for y_weights in Y_weights: # n_gram_weights = self._feature_space_.compute_weights(y_weights, self._max_length_) # graph = self._graph_builder.build_graph(n_gram_weights, self._max_length_) # node_creator = get_gs_node_creator(self._n, graph, n_gram_weights, self._max_length_, # self._n_gram_to_index, self._n_grams, self._sigma_position) # y_predicted, y_bound = branch_and_bound_no_length(node_creator, self._min_length_, self._max_length_, # self._alphabet, self._max_time) # Y_predictions.append(y_predicted) # return Y_predictions # # Path: preimage/learners/structured_krr.py # class InferenceFitParameters: # """Parameters for the inference model. # # That way inference_model.fit(parameters) doesn't have unused parameters but only access the one it needs # . # Attributes # ---------- # weights : array, shape = [n_samples, n_samples] # Learned weights, where n_samples is the number of training samples. # gram_matrix : array, shape = [n_samples, n_samples] # Gram_matrix of the training samples. # Y_train : array, shape = [n_samples, ] # Training strings. # y_lengths : array, shape = [n_samples] # Length of each training string in Y_train. # """ # def __init__(self, weights, gram_matrix, Y, y_lengths): # self.weights = weights # self.gram_matrix = gram_matrix # self.Y_train = Y # self.y_lengths = y_lengths . Output only the next line.
self.fit_parameters = InferenceFitParameters(self.weights, self.gram_matrix, Y=['a', 'ab'],
Predict the next line after this snippet: <|code_start|> class NGramFeatureSpace: """Output feature space for the N-Gram Kernel Creates a sparse matrix representation of the n-grams in each training string. This is used to compute the weights of the graph during the inference phase. Attributes ---------- feature_space : sparse matrix, shape = [n_samples, len(alphabet)**n] Sparse matrix representation of the n-grams in each training string, where n_samples is the number of training samples. """ def __init__(self, alphabet, n, Y, is_normalized): """Create the output feature space for the N-Gram Kernel Parameters ---------- alphabet : list list of letters n : int N-gram length. Y : array, [n_samples, ] The training strings. is_normalized : bool True if the feature space should be normalized, False otherwise. """ <|code_end|> using the current file's imports: import numpy from preimage.features.string_feature_space import build_feature_space_without_positions and any relevant context from other files: # Path: preimage/features/string_feature_space.py # def build_feature_space_without_positions(alphabet, n, Y): # """Create the feature space without considering the position of the n-gram in the strings # # Parameters # ---------- # alphabet : list # List of letters. # n : int # N-gram length. # Y : array, [n_samples, ] # Training strings. # # Returns # ------- # feature_space : sparse matrix, shape = [n_samples, len(alphabet)**n] # Sparse matrix representation of the n-grams in each training string, where n_samples is the number of samples # in Y. # """ # n = int(n) # n_examples = numpy.array(Y).shape[0] # n_gram_to_index = get_n_gram_to_index(alphabet, n) # index_pointers, indexes, data = __initialize_pointers_indexes_data(n_examples) # __build_y_pointers_indexes_data(index_pointers, indexes, data, n, n_gram_to_index, Y) # feature_space = __build_csr_matrix(index_pointers, indexes, data, n_examples, len(n_gram_to_index)) # return feature_space . Output only the next line.
self.feature_space = build_feature_space_without_positions(alphabet, n, Y)
Using the snippet: <|code_start|>__author__ = 'amelie' class TestStructuredOutputMetrics(unittest2.TestCase): def setUp(self): self.unicorn = ['unicorn'] self.unicarn = ['unicarn'] self.nicornu = ['nicornu'] self.unicor = ['unicor'] self.potato = ['potato'] self.tomato = ['tomato'] self.a = ['a'] self.unicorn_potato = self.unicorn + self.potato self.unicor_tomato = self.unicor + self.tomato self.unicor_potato = self.unicor + self.potato self.unicarn_tomato = self.unicarn + self.tomato self.nicornu_tomato = self.nicornu + self.tomato self.hamming_loss_unicarn_potato = (1. / 7 + 2. / 6) / 2 self.leveinshtein_loss_nicornu_tomato = (2. / 7 + 2. / 6) / 2 def test_same_word_zero_one_loss_is_zero(self): <|code_end|> , determine the next line of code. You have imports: import unittest2 from preimage.metrics.structured_output import zero_one_loss, hamming_loss, levenshtein_loss and context (class names, function names, or code) available: # Path: preimage/metrics/structured_output.py # def zero_one_loss(Y_true, Y_predicted): # """Zero one loss. # # Returns the number of incorrectly predicted strings on the total number of strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The number of incorrectly predicted strings on the total number of strings. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # n_errors = __get_n_errors_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(n_errors) # return loss # # def hamming_loss(Y_true, Y_predicted): # """Average hamming loss. # # Computes the average fraction of incorrectly predicted letters in the predicted strings. The ground truth and the # predicted strings must have the same length. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of incorrectly predicted letters. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # y_true_lengths = __get_length_of_each_y(Y_true) # y_predicted_lengths = __get_length_of_each_y(Y_predicted) # __check_each_tuple_y_true_y_predicted_has_same_length(y_true_lengths, y_predicted_lengths) # n_errors = __get_n_letter_errors_for_each_y_predicted(Y_true, Y_predicted, y_true_lengths) # loss = numpy.mean(n_errors / numpy.array(y_true_lengths, dtype=numpy.float)) # return loss # # def levenshtein_loss(Y_true, Y_predicted): # """Average levenshtein loss. # # Computes the average fraction of levenshtein distance between the ground truth strings and the predicted strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of levenshtein distance. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # max_lengths = __get_max_length_of_each_tuple_y_true_y_predicted(Y_true, Y_predicted) # distances = __get_levenshtein_distance_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(distances / numpy.array(max_lengths, dtype=numpy.float)) # return loss . Output only the next line.
loss = zero_one_loss(self.unicorn, self.unicorn)
Here is a snippet: <|code_start|> self.tomato = ['tomato'] self.a = ['a'] self.unicorn_potato = self.unicorn + self.potato self.unicor_tomato = self.unicor + self.tomato self.unicor_potato = self.unicor + self.potato self.unicarn_tomato = self.unicarn + self.tomato self.nicornu_tomato = self.nicornu + self.tomato self.hamming_loss_unicarn_potato = (1. / 7 + 2. / 6) / 2 self.leveinshtein_loss_nicornu_tomato = (2. / 7 + 2. / 6) / 2 def test_same_word_zero_one_loss_is_zero(self): loss = zero_one_loss(self.unicorn, self.unicorn) self.assertEqual(loss, 0.) def test_not_same_word_zero_one_loss_is_one(self): loss = zero_one_loss(self.unicorn, self.unicor) self.assertEqual(loss, 1.) def test_one_same_word_on_two_zero_one_loss_is_one_half(self): loss = zero_one_loss(self.unicorn_potato, self.unicor_potato) self.assertEqual(loss, 0.5) def test_not_same_word_count_zero_one_loss_throws_value_error(self): with self.assertRaises(ValueError): zero_one_loss(self.unicorn_potato, self.unicorn) def test_same_word_hamming_loss_is_zero(self): <|code_end|> . Write the next line using the current file imports: import unittest2 from preimage.metrics.structured_output import zero_one_loss, hamming_loss, levenshtein_loss and context from other files: # Path: preimage/metrics/structured_output.py # def zero_one_loss(Y_true, Y_predicted): # """Zero one loss. # # Returns the number of incorrectly predicted strings on the total number of strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The number of incorrectly predicted strings on the total number of strings. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # n_errors = __get_n_errors_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(n_errors) # return loss # # def hamming_loss(Y_true, Y_predicted): # """Average hamming loss. # # Computes the average fraction of incorrectly predicted letters in the predicted strings. The ground truth and the # predicted strings must have the same length. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of incorrectly predicted letters. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # y_true_lengths = __get_length_of_each_y(Y_true) # y_predicted_lengths = __get_length_of_each_y(Y_predicted) # __check_each_tuple_y_true_y_predicted_has_same_length(y_true_lengths, y_predicted_lengths) # n_errors = __get_n_letter_errors_for_each_y_predicted(Y_true, Y_predicted, y_true_lengths) # loss = numpy.mean(n_errors / numpy.array(y_true_lengths, dtype=numpy.float)) # return loss # # def levenshtein_loss(Y_true, Y_predicted): # """Average levenshtein loss. # # Computes the average fraction of levenshtein distance between the ground truth strings and the predicted strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of levenshtein distance. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # max_lengths = __get_max_length_of_each_tuple_y_true_y_predicted(Y_true, Y_predicted) # distances = __get_levenshtein_distance_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(distances / numpy.array(max_lengths, dtype=numpy.float)) # return loss , which may include functions, classes, or code. Output only the next line.
loss = hamming_loss(self.unicorn, self.unicorn)
Given the code snippet: <|code_start|> def test_same_word_hamming_loss_is_zero(self): loss = hamming_loss(self.unicorn, self.unicorn) self.assertEqual(loss, 0.) def test_one_wrong_letter_on_seven_hamming_loss_is_one_on_seven(self): loss = hamming_loss(self.unicorn, self.unicarn) self.assertEqual(loss, 1. / 7) def test_all_wrong_letters_hamming_loss_is_one(self): loss = hamming_loss(self.unicorn, self.nicornu) self.assertEqual(loss, 1.) def test_two_words_with_errors_hamming_loss_is_mean_of_errors(self): loss = hamming_loss(self.unicorn_potato, self.unicarn_tomato) self.assertEqual(loss, self.hamming_loss_unicarn_potato) def test_not_same_word_count_hamming_loss_throws_value_error(self): with self.assertRaises(ValueError): hamming_loss(self.unicorn_potato, self.unicorn) def test_not_same_letter_count_hamming_loss_throws_value_error(self): with self.assertRaises(ValueError): hamming_loss(self.unicorn, self.unicor) def test_same_word_levenshtein_loss_is_zero(self): <|code_end|> , generate the next line using the imports in this file: import unittest2 from preimage.metrics.structured_output import zero_one_loss, hamming_loss, levenshtein_loss and context (functions, classes, or occasionally code) from other files: # Path: preimage/metrics/structured_output.py # def zero_one_loss(Y_true, Y_predicted): # """Zero one loss. # # Returns the number of incorrectly predicted strings on the total number of strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The number of incorrectly predicted strings on the total number of strings. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # n_errors = __get_n_errors_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(n_errors) # return loss # # def hamming_loss(Y_true, Y_predicted): # """Average hamming loss. # # Computes the average fraction of incorrectly predicted letters in the predicted strings. The ground truth and the # predicted strings must have the same length. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of incorrectly predicted letters. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # y_true_lengths = __get_length_of_each_y(Y_true) # y_predicted_lengths = __get_length_of_each_y(Y_predicted) # __check_each_tuple_y_true_y_predicted_has_same_length(y_true_lengths, y_predicted_lengths) # n_errors = __get_n_letter_errors_for_each_y_predicted(Y_true, Y_predicted, y_true_lengths) # loss = numpy.mean(n_errors / numpy.array(y_true_lengths, dtype=numpy.float)) # return loss # # def levenshtein_loss(Y_true, Y_predicted): # """Average levenshtein loss. # # Computes the average fraction of levenshtein distance between the ground truth strings and the predicted strings. # # Parameters # ---------- # Y_true : array, shape = [n_samples, ] # Ground truth (correct) strings. # Y_predicted : array, shape = [n_samples, ] # Predicted strings, as returned by the structured output predictor. # # Returns # ------- # loss : float # The average fraction of levenshtein distance. # """ # Y_true = numpy.array(Y_true) # Y_predicted = numpy.array(Y_predicted) # __check_same_number_of_y(Y_true, Y_predicted) # max_lengths = __get_max_length_of_each_tuple_y_true_y_predicted(Y_true, Y_predicted) # distances = __get_levenshtein_distance_for_each_y_predicted(Y_true, Y_predicted) # loss = numpy.mean(distances / numpy.array(max_lengths, dtype=numpy.float)) # return loss . Output only the next line.
loss = levenshtein_loss(self.unicorn, self.unicorn)
Using the snippet: <|code_start|> merge the paths together when the graph is not connected. We chose to find the longest path and merge the remaining paths after, but this might differ from what Cortes et al. did in their work. The n-gram kernel also has a non-unique pre-image. For instance if the string to predict has the n-grams "ab" and "ba" both "aba" and "bab" are valid pre-image. In that case we chose randomly a pre-image among the possible ones (this is done by visiting the edges and the nodes in a random order). Note that the code could also be faster but we only cared about implementing the algorithm correctly. References ---------- .. [1] Cortes, Corinna, Mehryar Mohri, and Jason Weston. "A general regression framework for learning string-to-string mappings." Predicting Structured Data (2007): 143-168. """ def __init__(self, alphabet, n, min_length=1, is_merging_path=True): """Initialize the eulerian path algorithm Parameters ---------- alphabet : list list of letters. n : int n-gram length. min_length :int Minimum length of the predicted string. is_merging_path : bool True if merges path when the graph is not connected, False otherwise (choose the longest path instead). """ self.n = int(n) self.is_merging_path = is_merging_path self.min_n_gram_count = 1 if min_length <= self.n else min_length - self.n + 1 <|code_end|> , determine the next line of code. You have imports: from copy import deepcopy from preimage.utils.alphabet import get_index_to_n_gram from preimage.exceptions.n_gram import InvalidNGramLengthError, InvalidYLengthError, NoThresholdsError from preimage.exceptions.shape import InvalidShapeError import numpy and context (class names, function names, or code) available: # Path: preimage/utils/alphabet.py # def get_index_to_n_gram(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # index_to_n_gram = dict(zip(indexes, n_grams)) # return index_to_n_gram # # Path: preimage/exceptions/n_gram.py # class InvalidNGramLengthError(ValueError): # def __init__(self, n, min_n=0): # self.n = n # self.min_n = min_n # # def __str__(self): # error_message = 'n must be greater than {:d}. Got: n={:d}'.format(self.min_n, self.n) # return error_message # # class InvalidYLengthError(ValueError): # def __init__(self, n, y_length): # self.n = n # self.y_length = y_length # # def __str__(self): # error_message = 'y_length must be >= n. Got: y_length={:d}, n={:d}'.format(self.y_length, self.n) # return error_message # # class NoThresholdsError(ValueError): # def __str__(self): # error_message = 'thresholds must be provided when y_length is None' # return error_message # # Path: preimage/exceptions/shape.py # class InvalidShapeError(ValueError): # def __init__(self, parameter_name, parameter_shape, valid_shapes): # self.parameter_name = parameter_name # self.parameter_shape = parameter_shape # self.valid_shapes = [str(valid_shape) for valid_shape in valid_shapes] # # def __str__(self): # valid_shapes_string = ' or '.join(self.valid_shapes) # error_message = "{} wrong shape: Expected: {} Got: {}".format(self.parameter_name, valid_shapes_string, # str(self.parameter_shape)) # return error_message . Output only the next line.
self._index_to_n_gram = get_index_to_n_gram(alphabet, self.n)
Given snippet: <|code_start|> References ---------- .. [1] Cortes, Corinna, Mehryar Mohri, and Jason Weston. "A general regression framework for learning string-to-string mappings." Predicting Structured Data (2007): 143-168. """ def __init__(self, alphabet, n, min_length=1, is_merging_path=True): """Initialize the eulerian path algorithm Parameters ---------- alphabet : list list of letters. n : int n-gram length. min_length :int Minimum length of the predicted string. is_merging_path : bool True if merges path when the graph is not connected, False otherwise (choose the longest path instead). """ self.n = int(n) self.is_merging_path = is_merging_path self.min_n_gram_count = 1 if min_length <= self.n else min_length - self.n + 1 self._index_to_n_gram = get_index_to_n_gram(alphabet, self.n) self._n_gram_count = len(alphabet) ** self.n self._verify_n(self.n) def _verify_n(self, n): if n <= 1: <|code_end|> , continue by predicting the next line. Consider current file imports: from copy import deepcopy from preimage.utils.alphabet import get_index_to_n_gram from preimage.exceptions.n_gram import InvalidNGramLengthError, InvalidYLengthError, NoThresholdsError from preimage.exceptions.shape import InvalidShapeError import numpy and context: # Path: preimage/utils/alphabet.py # def get_index_to_n_gram(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # index_to_n_gram = dict(zip(indexes, n_grams)) # return index_to_n_gram # # Path: preimage/exceptions/n_gram.py # class InvalidNGramLengthError(ValueError): # def __init__(self, n, min_n=0): # self.n = n # self.min_n = min_n # # def __str__(self): # error_message = 'n must be greater than {:d}. Got: n={:d}'.format(self.min_n, self.n) # return error_message # # class InvalidYLengthError(ValueError): # def __init__(self, n, y_length): # self.n = n # self.y_length = y_length # # def __str__(self): # error_message = 'y_length must be >= n. Got: y_length={:d}, n={:d}'.format(self.y_length, self.n) # return error_message # # class NoThresholdsError(ValueError): # def __str__(self): # error_message = 'thresholds must be provided when y_length is None' # return error_message # # Path: preimage/exceptions/shape.py # class InvalidShapeError(ValueError): # def __init__(self, parameter_name, parameter_shape, valid_shapes): # self.parameter_name = parameter_name # self.parameter_shape = parameter_shape # self.valid_shapes = [str(valid_shape) for valid_shape in valid_shapes] # # def __str__(self): # valid_shapes_string = ' or '.join(self.valid_shapes) # error_message = "{} wrong shape: Expected: {} Got: {}".format(self.parameter_name, valid_shapes_string, # str(self.parameter_shape)) # return error_message which might include code, classes, or functions. Output only the next line.
raise InvalidNGramLengthError(n, 1)
Using the snippet: <|code_start|> together when is_merging_path is True, and predict the longest path otherwise. Parameters ---------- n_gram_weights : array, shape=[len(alphabet)**n] Weight of each n-gram. y_length : int or None Length of the string to predict. None if thresholds are used. thresholds :array, shape=[len(alphabet)**n] or None Threshold value for each n-gram above which the n_gram_weights are rounded to one. None if y_length is given. Returns ------- y: string The predicted string. """ self._verify_weights_length_thresholds(n_gram_weights, y_length, thresholds) rounded_weights = self._round_weights(n_gram_weights, thresholds, y_length) n_gram_indexes = numpy.where(rounded_weights > 0)[0] n_grams = self._get_n_grams_in_selected_indexes(n_gram_indexes, rounded_weights) y = self._find_y_corresponding_to_n_grams(n_grams) if y_length is not None: y = y[0:y_length] return y def _verify_weights_length_thresholds(self, n_gram_weights, y_length, thresholds): if n_gram_weights.shape[0] != self._n_gram_count: raise InvalidShapeError('n_gram_weights', n_gram_weights.shape, [(self._n_gram_count,)]) if y_length is not None and y_length < self.n: <|code_end|> , determine the next line of code. You have imports: from copy import deepcopy from preimage.utils.alphabet import get_index_to_n_gram from preimage.exceptions.n_gram import InvalidNGramLengthError, InvalidYLengthError, NoThresholdsError from preimage.exceptions.shape import InvalidShapeError import numpy and context (class names, function names, or code) available: # Path: preimage/utils/alphabet.py # def get_index_to_n_gram(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # index_to_n_gram = dict(zip(indexes, n_grams)) # return index_to_n_gram # # Path: preimage/exceptions/n_gram.py # class InvalidNGramLengthError(ValueError): # def __init__(self, n, min_n=0): # self.n = n # self.min_n = min_n # # def __str__(self): # error_message = 'n must be greater than {:d}. Got: n={:d}'.format(self.min_n, self.n) # return error_message # # class InvalidYLengthError(ValueError): # def __init__(self, n, y_length): # self.n = n # self.y_length = y_length # # def __str__(self): # error_message = 'y_length must be >= n. Got: y_length={:d}, n={:d}'.format(self.y_length, self.n) # return error_message # # class NoThresholdsError(ValueError): # def __str__(self): # error_message = 'thresholds must be provided when y_length is None' # return error_message # # Path: preimage/exceptions/shape.py # class InvalidShapeError(ValueError): # def __init__(self, parameter_name, parameter_shape, valid_shapes): # self.parameter_name = parameter_name # self.parameter_shape = parameter_shape # self.valid_shapes = [str(valid_shape) for valid_shape in valid_shapes] # # def __str__(self): # valid_shapes_string = ' or '.join(self.valid_shapes) # error_message = "{} wrong shape: Expected: {} Got: {}".format(self.parameter_name, valid_shapes_string, # str(self.parameter_shape)) # return error_message . Output only the next line.
raise InvalidYLengthError(self.n, y_length)
Continue the code snippet: <|code_start|> n_gram_weights : array, shape=[len(alphabet)**n] Weight of each n-gram. y_length : int or None Length of the string to predict. None if thresholds are used. thresholds :array, shape=[len(alphabet)**n] or None Threshold value for each n-gram above which the n_gram_weights are rounded to one. None if y_length is given. Returns ------- y: string The predicted string. """ self._verify_weights_length_thresholds(n_gram_weights, y_length, thresholds) rounded_weights = self._round_weights(n_gram_weights, thresholds, y_length) n_gram_indexes = numpy.where(rounded_weights > 0)[0] n_grams = self._get_n_grams_in_selected_indexes(n_gram_indexes, rounded_weights) y = self._find_y_corresponding_to_n_grams(n_grams) if y_length is not None: y = y[0:y_length] return y def _verify_weights_length_thresholds(self, n_gram_weights, y_length, thresholds): if n_gram_weights.shape[0] != self._n_gram_count: raise InvalidShapeError('n_gram_weights', n_gram_weights.shape, [(self._n_gram_count,)]) if y_length is not None and y_length < self.n: raise InvalidYLengthError(self.n, y_length) if thresholds is not None and thresholds.shape[0] != self._n_gram_count: raise InvalidShapeError('thresholds', thresholds.shape, [(self._n_gram_count,)]) if thresholds is None and y_length is None: <|code_end|> . Use current file imports: from copy import deepcopy from preimage.utils.alphabet import get_index_to_n_gram from preimage.exceptions.n_gram import InvalidNGramLengthError, InvalidYLengthError, NoThresholdsError from preimage.exceptions.shape import InvalidShapeError import numpy and context (classes, functions, or code) from other files: # Path: preimage/utils/alphabet.py # def get_index_to_n_gram(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # index_to_n_gram = dict(zip(indexes, n_grams)) # return index_to_n_gram # # Path: preimage/exceptions/n_gram.py # class InvalidNGramLengthError(ValueError): # def __init__(self, n, min_n=0): # self.n = n # self.min_n = min_n # # def __str__(self): # error_message = 'n must be greater than {:d}. Got: n={:d}'.format(self.min_n, self.n) # return error_message # # class InvalidYLengthError(ValueError): # def __init__(self, n, y_length): # self.n = n # self.y_length = y_length # # def __str__(self): # error_message = 'y_length must be >= n. Got: y_length={:d}, n={:d}'.format(self.y_length, self.n) # return error_message # # class NoThresholdsError(ValueError): # def __str__(self): # error_message = 'thresholds must be provided when y_length is None' # return error_message # # Path: preimage/exceptions/shape.py # class InvalidShapeError(ValueError): # def __init__(self, parameter_name, parameter_shape, valid_shapes): # self.parameter_name = parameter_name # self.parameter_shape = parameter_shape # self.valid_shapes = [str(valid_shape) for valid_shape in valid_shapes] # # def __str__(self): # valid_shapes_string = ' or '.join(self.valid_shapes) # error_message = "{} wrong shape: Expected: {} Got: {}".format(self.parameter_name, valid_shapes_string, # str(self.parameter_shape)) # return error_message . Output only the next line.
raise NoThresholdsError()
Predict the next line for this snippet: <|code_start|> Rounds the n_gram_weights to integer values, creates a graph with the predicted n-grams, and predicts the output string by finding an eulerian path in this graph. If the graph is not connected, it will merge multiple paths together when is_merging_path is True, and predict the longest path otherwise. Parameters ---------- n_gram_weights : array, shape=[len(alphabet)**n] Weight of each n-gram. y_length : int or None Length of the string to predict. None if thresholds are used. thresholds :array, shape=[len(alphabet)**n] or None Threshold value for each n-gram above which the n_gram_weights are rounded to one. None if y_length is given. Returns ------- y: string The predicted string. """ self._verify_weights_length_thresholds(n_gram_weights, y_length, thresholds) rounded_weights = self._round_weights(n_gram_weights, thresholds, y_length) n_gram_indexes = numpy.where(rounded_weights > 0)[0] n_grams = self._get_n_grams_in_selected_indexes(n_gram_indexes, rounded_weights) y = self._find_y_corresponding_to_n_grams(n_grams) if y_length is not None: y = y[0:y_length] return y def _verify_weights_length_thresholds(self, n_gram_weights, y_length, thresholds): if n_gram_weights.shape[0] != self._n_gram_count: <|code_end|> with the help of current file imports: from copy import deepcopy from preimage.utils.alphabet import get_index_to_n_gram from preimage.exceptions.n_gram import InvalidNGramLengthError, InvalidYLengthError, NoThresholdsError from preimage.exceptions.shape import InvalidShapeError import numpy and context from other files: # Path: preimage/utils/alphabet.py # def get_index_to_n_gram(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # index_to_n_gram = dict(zip(indexes, n_grams)) # return index_to_n_gram # # Path: preimage/exceptions/n_gram.py # class InvalidNGramLengthError(ValueError): # def __init__(self, n, min_n=0): # self.n = n # self.min_n = min_n # # def __str__(self): # error_message = 'n must be greater than {:d}. Got: n={:d}'.format(self.min_n, self.n) # return error_message # # class InvalidYLengthError(ValueError): # def __init__(self, n, y_length): # self.n = n # self.y_length = y_length # # def __str__(self): # error_message = 'y_length must be >= n. Got: y_length={:d}, n={:d}'.format(self.y_length, self.n) # return error_message # # class NoThresholdsError(ValueError): # def __str__(self): # error_message = 'thresholds must be provided when y_length is None' # return error_message # # Path: preimage/exceptions/shape.py # class InvalidShapeError(ValueError): # def __init__(self, parameter_name, parameter_shape, valid_shapes): # self.parameter_name = parameter_name # self.parameter_shape = parameter_shape # self.valid_shapes = [str(valid_shape) for valid_shape in valid_shapes] # # def __str__(self): # valid_shapes_string = ' or '.join(self.valid_shapes) # error_message = "{} wrong shape: Expected: {} Got: {}".format(self.parameter_name, valid_shapes_string, # str(self.parameter_shape)) # return error_message , which may contain function names, class names, or code. Output only the next line.
raise InvalidShapeError('n_gram_weights', n_gram_weights.shape, [(self._n_gram_count,)])
Next line prediction: <|code_start|>__author__ = 'amelie' class TestStringMaximizationModel(unittest2.TestCase): def setUp(self): self.setup_feature_space() self.setup_graph_builder() self.setup_branch_and_bound() self.alphabet = ['a', 'b', 'c'] <|code_end|> . Use current file imports: (import unittest2 import numpy import numpy.testing from mock import patch, Mock from preimage.models.string_max_model import StringMaximizationModel) and context including class names, function names, or small code snippets from other files: # Path: preimage/models/string_max_model.py # class StringMaximizationModel(BaseEstimator): # def __init__(self, alphabet, n, gs_kernel, max_time): # self._n = int(n) # self._alphabet = alphabet # self._graph_builder = GraphBuilder(self._alphabet, self._n) # self._gs_kernel = gs_kernel # self._max_time = max_time # self._is_normalized = True # self._node_creator_ = None # self._y_length_ = None # # def fit(self, X, learned_weights, y_length): # feature_space = GenericStringSimilarityFeatureSpace(self._alphabet, self._n, X, self._is_normalized, # self._gs_kernel) # gs_weights = feature_space.compute_weights(learned_weights, y_length) # graph = self._graph_builder.build_graph(gs_weights, y_length) # self._node_creator_ = get_gs_similarity_node_creator(self._alphabet, self._n, graph, gs_weights, y_length, # self._gs_kernel) # self._y_length_ = y_length # # def predict(self, n_predictions): # strings, bounds = branch_and_bound_multiple_solutions(self._node_creator_, self._y_length_, n_predictions, # self._alphabet, self._max_time) # return strings, bounds . Output only the next line.
self.model_with_length = StringMaximizationModel(self.alphabet, n=1, gs_kernel=Mock(), max_time=30)
Predict the next line after this snippet: <|code_start|> self.setup_gs_weights() self.setup_gs_kernel_mock() def setup_parameters(self): self.alphabet = ['a', 'b'] self.abb = ['abb'] self.abaaa = ['abaaa'] self.abb_abaaa = self.abb + self.abaaa def setup_gs_weights(self): self.gs_weights_length_two_small_sigma_p_abb = numpy.array([[1., 0.5], [0.5, 1.]]) self.gs_weights_length_two_small_sigma_p_abb_abaaa = numpy.array([[1.5, 0.75], [0.75, 1.5]]) self.gs_weights_normalized_abb_abaaa = numpy.array( [[1. / sqrt(3) + 0.5 / sqrt(5), 0.5 / sqrt(3) + 0.25 / sqrt(5)], [0.5 / sqrt(3) + 0.25 / sqrt(5), 1. / sqrt(3) + 0.5 / sqrt(5)]]) self.gs_weights_length_four_small_sigma_p_abb = numpy.array([[1., 0.5], [0.5, 1.], [0.5, 1.], [0, 0]]) self.gs_weights_length_two_large_sigma_p_abb = numpy.array([[2., 2.5], [2, 2.5]]) self.gs_weights_two_gram_length_two_small_sigma_p_abb = numpy.array([[2., 3, 1.25, 2]]) self.gs_weights_two_gram_length_three_small_sigma_p_abb = numpy.array([[1.5, 2, 0.75, 1], [1.25, 2, 2, 3]]) def setup_gs_kernel_mock(self): self.positions_small_sigma = numpy.eye(5, dtype=numpy.float64) self.positions_large_sigma = numpy.ones((5, 5), dtype=numpy.float64) self.similarity_matrix = numpy.array([[1, 0.5], [0.5, 1]]) self.gs_kernel_mock = Mock() self.gs_kernel_mock.get_position_matrix.return_value = self.positions_small_sigma self.gs_kernel_mock.get_alphabet_similarity_matrix.return_value = self.similarity_matrix self.gs_kernel_mock.element_wise_kernel.return_value = [3, 5] def test_small_length_small_sigma_p_compute_one_gram_weights_returns_expected_weights(self): <|code_end|> using the current file's imports: from math import sqrt from mock import Mock from preimage.features.gs_similarity_feature_space import GenericStringSimilarityFeatureSpace import unittest2 import numpy.testing and any relevant context from other files: # Path: preimage/features/gs_similarity_feature_space.py # class GenericStringSimilarityFeatureSpace: # """Output space for the Generic String kernel with position and n-gram similarity. # # Doesn't use a sparse matrix representation because it takes in account the similarity between the n-grams. # This is used to compute the weights of the graph during the inference phase. # # Attributes # ---------- # n : int # N-gram length. # is_normalized : bool # True if the feature space should be normalized, False otherwise. # max_train_length : int # Length of the longest string in the training dataset. # gs_kernel : GenericStringKernel # Generic string kernel. # """ # # def __init__(self, alphabet, n, Y, is_normalized, gs_kernel): # self.n = int(n) # self.is_normalized = is_normalized # self._y_lengths = numpy.array([len(y) for y in Y]) # self.max_train_length = numpy.max(self._y_lengths) # self.gs_kernel = gs_kernel # self._Y_int = transform_strings_to_integer_lists(Y, alphabet) # self._n_grams_int = transform_strings_to_integer_lists(get_n_grams(alphabet, n), alphabet) # self._n_gram_similarity_matrix = gs_kernel.get_alphabet_similarity_matrix() # if is_normalized: # self._normalization = numpy.sqrt(gs_kernel.element_wise_kernel(Y)) # # def compute_weights(self, y_weights, y_length): # """Compute the inference graph weights # # Parameters # ---------- # y_weights : array, [n_samples] # Weight of each training example. # y_length : int # Length of the string to predict. # # Returns # ------- # gs_weights : [len(alphabet)**n, y_n_gram_count * len(alphabet)**n] # Weight of each n-gram at each position, where y_n_gram_count is the number of n-gram in y_length. # """ # normalized_weights = numpy.copy(y_weights) # max_length = max(y_length, self.max_train_length) # if self.is_normalized: # normalized_weights *= 1. / self._normalization # n_partitions = y_length - self.n + 1 # position_matrix = self.gs_kernel.get_position_matrix(max_length) # gs_weights = compute_gs_similarity_weights(n_partitions, self._n_grams_int, self._Y_int, normalized_weights, # self._y_lengths, position_matrix, self._n_gram_similarity_matrix) # return numpy.array(gs_weights) . Output only the next line.
feature_space = GenericStringSimilarityFeatureSpace(self.alphabet, n=1, Y=self.abb, is_normalized=False,
Here is a snippet: <|code_start|>"""Builder of string feature space represented as sparse matrix""" __author__ = 'amelie' def build_feature_space_without_positions(alphabet, n, Y): """Create the feature space without considering the position of the n-gram in the strings Parameters ---------- alphabet : list List of letters. n : int N-gram length. Y : array, [n_samples, ] Training strings. Returns ------- feature_space : sparse matrix, shape = [n_samples, len(alphabet)**n] Sparse matrix representation of the n-grams in each training string, where n_samples is the number of samples in Y. """ n = int(n) n_examples = numpy.array(Y).shape[0] <|code_end|> . Write the next line using the current file imports: from collections import Counter from scipy.sparse import csr_matrix from preimage.utils.alphabet import get_n_gram_to_index from preimage.exceptions.n_gram import InvalidNGramError import numpy and context from other files: # Path: preimage/utils/alphabet.py # def get_n_gram_to_index(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # n_gram_to_index = dict(zip(n_grams, indexes)) # return n_gram_to_index # # Path: preimage/exceptions/n_gram.py # class InvalidNGramError(ValueError): # def __init__(self, n, n_gram): # self.n = n # self.n_gram = n_gram # # def __str__(self): # error_message = "{} is not a possible {:d}_gram for this alphabet".format(self.n_gram, self.n) # return error_message , which may include functions, classes, or code. Output only the next line.
n_gram_to_index = get_n_gram_to_index(alphabet, n)
Using the snippet: <|code_start|> return feature_space def __initialize_pointers_indexes_data(n_examples): index_pointers = numpy.empty(n_examples + 1, dtype=numpy.int) index_pointers[0] = 0 indexes = [] data = [] return index_pointers, indexes, data def __build_y_pointers_indexes_data(index_pointers, indexes, data, n, n_gram_to_index, Y): for y_index, y in enumerate(Y): y_column_indexes = __get_y_indexes(y, n, n_gram_to_index) y_unique_column_indexes = list(numpy.unique(y_column_indexes)) index_pointers[y_index + 1] = __get_y_index_pointer(y_index, index_pointers, y_unique_column_indexes) indexes += y_unique_column_indexes data += __get_y_data(y_column_indexes, y_unique_column_indexes) def __get_y_index_pointer(y_index, index_pointers, y_unique_column_indexes): index_pointer = index_pointers[y_index] + len(y_unique_column_indexes) return index_pointer def __get_y_indexes(y, n, n_gram_to_index): y_n_gram_count = len(y) - n + 1 try: column_indexes = [n_gram_to_index[y[i:i + n]] for i in range(y_n_gram_count)] except KeyError as key_error: <|code_end|> , determine the next line of code. You have imports: from collections import Counter from scipy.sparse import csr_matrix from preimage.utils.alphabet import get_n_gram_to_index from preimage.exceptions.n_gram import InvalidNGramError import numpy and context (class names, function names, or code) available: # Path: preimage/utils/alphabet.py # def get_n_gram_to_index(alphabet, n): # n_grams = get_n_grams(alphabet, n) # indexes = numpy.arange(len(n_grams)) # n_gram_to_index = dict(zip(n_grams, indexes)) # return n_gram_to_index # # Path: preimage/exceptions/n_gram.py # class InvalidNGramError(ValueError): # def __init__(self, n, n_gram): # self.n = n # self.n_gram = n_gram # # def __str__(self): # error_message = "{} is not a possible {:d}_gram for this alphabet".format(self.n_gram, self.n) # return error_message . Output only the next line.
raise InvalidNGramError(n, key_error.args[0])
Continue the code snippet: <|code_start|>__author__ = 'amelie' # This is just to ensure the pickle files were made correctly # (not real unit testing since we use the real .pickle files) class TestLoader(unittest2.TestCase): def setUp(self): self.ocr_n_examples_in_fold = [626, 704, 684, 698, 693, 651, 739, 717, 690, 675] self.ocr_n_examples_not_in_fold = [6251, 6173, 6193, 6179, 6184, 6226, 6138, 6160, 6187, 6202] self.camps_n_examples = 101 self.bpps_n_examples = 31 self.amino_acids = ['A', 'B', 'C'] self.amino_acid_descriptors = [[4, -1, -2], [-1, 5, 0], [-2, 0, 6]] self.amino_acid_file = 'AA.example.dat' def test_load_ocr_letters_has_correct_number_of_x_in_fold(self): for fold_id in range(10): with self.subTest(fold_id=fold_id): <|code_end|> . Use current file imports: import numpy import unittest2 from preimage.datasets import loader and context (classes, functions, or code) from other files: # Path: preimage/datasets/loader.py # class StructuredOutputDataset: # class StandardDataset: # def __init__(self, X, Y): # def __init__(self, X, y): # def load_ocr_letters(fold_id=0): # def __load_gz_pickle_file(file_name): # def load_camps_dataset(): # def load_bpps_dataset(): # def __load_peptide_dataset(file_name): # def __load_pickle_file(file_name): # def load_amino_acids_and_descriptors(file_name=AminoAcidFile.blosum62_natural): # X = numpy.array(data['X'], dtype=numpy.str) . Output only the next line.
train_dataset, test_dataset = loader.load_ocr_letters(fold_id)
Given the following code snippet before the placeholder: <|code_start|> self.setup_patch() def setup_alphabet(self): self.alphabet = ['a', 'b'] self.abb = ['abb'] self.abaaa = ['abaaa'] self.abb_abaaa = self.abb + self.abaaa def setup_feature_space(self): self.feature_space_one_gram_abb = csr_matrix([[1., 2.]]) self.feature_space_two_gram_abb = csr_matrix([[0, 1., 0, 1.]]) self.feature_space_two_gram_abb_abaaa = csr_matrix([[0, 1., 0, 1.], [2., 1., 1., 0]]) self.feature_space_one_gram_abb_abaaa = csr_matrix([[1., 2.], [4., 1.]]) self.feature_space_normalized_one_gram_abb = [[1. / sqrt(5), 2. / sqrt(5)]] self.feature_space_normalized_two_gram_abb = [[0, 1. / sqrt(2), 0, 1. / sqrt(2)]] self.feature_space_normalized_one_gram_abb_abaaa = [[1. / sqrt(5), 2. / sqrt(5)], [4. / sqrt(17), 1. / sqrt(17)]] def setup_weights(self): self.one_gram_weights_one_half_abb = [0.5, 1] self.two_gram_weights_one_half_abb = [0, 0.5, 0, 0.5] self.two_gram_weights_one_half_abb_one_abaaa = [2, 1.5, 1, 0.5] def setup_patch(self): self.feature_space_builder_patch = patch('preimage.features.n_gram_feature_space.' 'build_feature_space_without_positions') def test_one_gram_one_y_normalized_feature_space_is_normalized(self): self.feature_space_builder_patch.start().return_value = self.feature_space_one_gram_abb <|code_end|> , predict the next line using imports from the current file: from math import sqrt from mock import patch from scipy.sparse import csr_matrix from preimage.features.n_gram_feature_space import NGramFeatureSpace import unittest2 import numpy.testing and context including class names, function names, and sometimes code from other files: # Path: preimage/features/n_gram_feature_space.py # class NGramFeatureSpace: # """Output feature space for the N-Gram Kernel # # Creates a sparse matrix representation of the n-grams in each training string. This is used to compute the weights # of the graph during the inference phase. # # Attributes # ---------- # feature_space : sparse matrix, shape = [n_samples, len(alphabet)**n] # Sparse matrix representation of the n-grams in each training string, where n_samples is the number of training # samples. # """ # # def __init__(self, alphabet, n, Y, is_normalized): # """Create the output feature space for the N-Gram Kernel # # Parameters # ---------- # alphabet : list # list of letters # n : int # N-gram length. # Y : array, [n_samples, ] # The training strings. # is_normalized : bool # True if the feature space should be normalized, False otherwise. # """ # self.feature_space = build_feature_space_without_positions(alphabet, n, Y) # self._normalize(is_normalized, self.feature_space) # # def _normalize(self, is_normalized, feature_space): # if is_normalized: # y_normalization = self._get_y_normalization(feature_space) # data_normalization = y_normalization.repeat(numpy.diff(feature_space.indptr)) # feature_space.data *= data_normalization # # def _get_y_normalization(self, feature_space): # y_normalization = (feature_space.multiply(feature_space)).sum(axis=1) # y_normalization = 1. / numpy.sqrt(numpy.array((y_normalization.reshape(1, -1))[0])) # return y_normalization # # def compute_weights(self, y_weights): # """Compute the inference graph weights # # Parameters # ---------- # y_weights : array, [n_samples] # Weight of each training example. # # Returns # ------- # n_gram_weights : [len(alphabet)**n] # Weight of each n-gram. # """ # data_copy = numpy.copy(self.feature_space.data) # self.feature_space.data *= self._repeat_each_y_weight_by_y_column_count(y_weights) # n_gram_weights = numpy.array(self.feature_space.sum(axis=0))[0] # self.feature_space.data = data_copy # return n_gram_weights # # def _repeat_each_y_weight_by_y_column_count(self, y_weights): # return y_weights.repeat(numpy.diff(self.feature_space.indptr)) . Output only the next line.
feature_space = NGramFeatureSpace(self.alphabet, n=1, Y=self.abb, is_normalized=True)
Based on the snippet: <|code_start|> info = "" tag = tag.strip() info = info.strip() ret.append({ "severity": flag, "component": component, "tag": tag, "info": info }) return ret def lint(path, pedantic=False, info=False, experimental=False): args = ["lintian", "--show-overrides"] if pedantic: args.append("--pedantic") if info: args.append("-I") if experimental: args.append("-E") args.append(path) try: output = subprocess.check_output(args) except subprocess.CalledProcessError as e: output = e.output except OSError as e: <|code_end|> , predict the immediate next line with the help of imports: import subprocess from dput.core import logger from dput.exceptions import HookException, DputConfigurationError from dput.interface import BUTTON_NO and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
logger.warning("Failed to execute lintian: %s" % (e))
Given the following code snippet before the placeholder: <|code_start|> tag = tag.strip() info = info.strip() ret.append({ "severity": flag, "component": component, "tag": tag, "info": info }) return ret def lint(path, pedantic=False, info=False, experimental=False): args = ["lintian", "--show-overrides"] if pedantic: args.append("--pedantic") if info: args.append("-I") if experimental: args.append("-E") args.append(path) try: output = subprocess.check_output(args) except subprocess.CalledProcessError as e: output = e.output except OSError as e: logger.warning("Failed to execute lintian: %s" % (e)) <|code_end|> , predict the next line using imports from the current file: import subprocess from dput.core import logger from dput.exceptions import HookException, DputConfigurationError from dput.interface import BUTTON_NO and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
raise DputConfigurationError("lintian: %s" % (e))
Continue the code snippet: <|code_start|> "Please configure the lintian checker instead.") if not profile['run_lintian']: # XXX: Broken. Fixme. logger.info("skipping lintian checking, enable with " "run_lintian = 1 in your dput.cf") return tags = lint( changes._absfile, pedantic=True, info=True, experimental=True ) sorted_tags = {} for tag in tags: if not tag['severity'] in sorted_tags: sorted_tags[tag['severity']] = {} if tag['tag'] not in sorted_tags[tag['severity']]: sorted_tags[tag['severity']][tag['tag']] = tag tags = sorted_tags # XXX: Make this configurable if not "E" in tags: return for tag in set(tags["E"]): print(" - %s: %s" % (tags["E"][tag]['severity'], tag)) inp = interface.boolean('Lintian Checker', 'Upload despite of Lintian finding issues?', <|code_end|> . Use current file imports: import subprocess from dput.core import logger from dput.exceptions import HookException, DputConfigurationError from dput.interface import BUTTON_NO and context (classes, functions, or code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
default=BUTTON_NO)
Given the following code snippet before the placeholder: <|code_start|> class HashValidationError(HookException): """ Subclass of the :class:`dput.exceptions.HookException`. Thrown if the ``checksum`` checker encounters an issue. """ pass def validate_checksums(changes, profile, interface): """ The ``checksum`` checker is a stock dput checker that checks packages intended for upload for correct checksums. This is actually the most simple checker that exists. Profile key: none. Example profile:: { ... "hash": "md5" ... } The hash may be one of md5, sha1, sha256. """ try: changes.validate_checksums(check_hash=profile["hash"]) <|code_end|> , predict the next line using imports from the current file: from dput.core import logger from dput.exceptions import (ChangesFileException, HookException) and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr # # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass . Output only the next line.
except ChangesFileException as e:
Continue the code snippet: <|code_start|> for index in range(0, len(str_button) + 1): buttons = [count for count in ALL_BUTTONS if count.startswith(str_button[0:index])] if len(buttons) == 0: break elif len(buttons) == 1: return buttons[0] return None def boolean(self, title, message, question_type=BUTTON_YES_NO, default=None): """ See :meth:`dput.interface.AbstractInterface.boolean` """ super(CLInterface, self).boolean(title, message, question_type) choices = "" question_len = len(question_type) for question in question_type: button_name = self.button_to_str(question) if question == default: button_name = button_name.upper() choices += button_name question_len -= 1 if question_len: choices += ", " user_input = None while not user_input: user_input = self.question(title, "%s [%s]" % (message, choices)) user_input = self.str_to_button(user_input, default) <|code_end|> . Use current file imports: import sys import getpass from dput.core import logger from dput.interface import (AbstractInterface, ALL_BUTTONS, BUTTON_YES_NO, BUTTON_OK, BUTTON_YES) and context (classes, functions, or code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/interface.py # class AbstractInterface(object): # """ # Abstract base class for Concrete implementations of user interfaces. # # The invoking process will instantiate the process, call initialize, # query (any number of times), and shutdown. # """ # # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Set up the interface state. # """ # pass # # def boolean(self, title, message, question_type=BUTTON_YES_NO, # default=None): # """ # Display a question returning a boolean value. This is evaluated # by checking the button return code either to be BUTTON_YES or # BUTTON_OK # """ # self.widget_type = WIDGET_BOOLEAN # self.message = message # self.question_type = question_type # self.default = default # # def message(self, title, message, question_type=BUTTON_OK): # """ # Display a message and a confirmation button when required by the # interface to make sure the user noticed the message Some interfaces, # e.g. the CLI may ignore the button. # """ # self.widget_type = WIDGET_MESSAGE # self.message = message # self.question_type = question_type # # def list(self, title, message, selections=[]): # """ # Display a list of alternatives the user can choose from, returns a # list of selections. # """ # self.widget_type = WIDGET_LIST # self.message = message # self.selection = selections # # def question(self, title, message, echo_input=True): # """ # Query for user input. The input is returned literally # """ # self.widget_type = WIDGET_QUESTION # self.message = message # self.echo_input = True # # def password(self, title, message): # """ # Query for user input. The input is returned literally but not printed # back. This is a shortcut to # :meth:`dput.interface.AbstractInterface.question` with echo_input # defaulting to False # """ # self.question(title, message, echo_input=False) # # @abc.abstractmethod # def shutdown(self): # """ # Get rid of everything, close out. # """ # pass # # ALL_BUTTONS = [BUTTON_YES, BUTTON_NO, BUTTON_CANCEL, BUTTON_OK] # # BUTTON_YES_NO = [BUTTON_YES, BUTTON_NO] # # BUTTON_OK = "ok" # # BUTTON_YES = "yes" . Output only the next line.
logger.trace("translated user input '%s'" % (user_input))
Predict the next line for this snippet: <|code_start|># WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ CLI User Interface Implementation """ class CLInterface(AbstractInterface): """ Concrete implementation of the command line user interface. """ def initialize(self, **kwargs): """ See :meth:`dput.interface.AbstractInterface.initialize` """ pass # nothing here. def button_to_str(self, button): """ Translate a button name to it's label value. """ <|code_end|> with the help of current file imports: import sys import getpass from dput.core import logger from dput.interface import (AbstractInterface, ALL_BUTTONS, BUTTON_YES_NO, BUTTON_OK, BUTTON_YES) and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/interface.py # class AbstractInterface(object): # """ # Abstract base class for Concrete implementations of user interfaces. # # The invoking process will instantiate the process, call initialize, # query (any number of times), and shutdown. # """ # # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Set up the interface state. # """ # pass # # def boolean(self, title, message, question_type=BUTTON_YES_NO, # default=None): # """ # Display a question returning a boolean value. This is evaluated # by checking the button return code either to be BUTTON_YES or # BUTTON_OK # """ # self.widget_type = WIDGET_BOOLEAN # self.message = message # self.question_type = question_type # self.default = default # # def message(self, title, message, question_type=BUTTON_OK): # """ # Display a message and a confirmation button when required by the # interface to make sure the user noticed the message Some interfaces, # e.g. the CLI may ignore the button. # """ # self.widget_type = WIDGET_MESSAGE # self.message = message # self.question_type = question_type # # def list(self, title, message, selections=[]): # """ # Display a list of alternatives the user can choose from, returns a # list of selections. # """ # self.widget_type = WIDGET_LIST # self.message = message # self.selection = selections # # def question(self, title, message, echo_input=True): # """ # Query for user input. The input is returned literally # """ # self.widget_type = WIDGET_QUESTION # self.message = message # self.echo_input = True # # def password(self, title, message): # """ # Query for user input. The input is returned literally but not printed # back. This is a shortcut to # :meth:`dput.interface.AbstractInterface.question` with echo_input # defaulting to False # """ # self.question(title, message, echo_input=False) # # @abc.abstractmethod # def shutdown(self): # """ # Get rid of everything, close out. # """ # pass # # ALL_BUTTONS = [BUTTON_YES, BUTTON_NO, BUTTON_CANCEL, BUTTON_OK] # # BUTTON_YES_NO = [BUTTON_YES, BUTTON_NO] # # BUTTON_OK = "ok" # # BUTTON_YES = "yes" , which may contain function names, class names, or code. Output only the next line.
for item in ALL_BUTTONS:
Given the code snippet: <|code_start|> assert(False) def str_to_button(self, str_button, default): """ Translate a string input to a button known to the interface. In case of the CLI interface there is no straight notion of a button, so this is abstracted by expected data input treated as button. This method guesses based on the supplied argument and the supplied default value, which button the user meant in 'Do you wanna foo [y/N]?' situations. """ str_button = str_button.lower() # return default when no input was supplied if default and not str_button: return default # compare literally if str_button in ALL_BUTTONS: return str_button # guess input button until only one choice is left or the outcome is # known to be ambiguous for index in range(0, len(str_button) + 1): buttons = [count for count in ALL_BUTTONS if count.startswith(str_button[0:index])] if len(buttons) == 0: break elif len(buttons) == 1: return buttons[0] return None <|code_end|> , generate the next line using the imports in this file: import sys import getpass from dput.core import logger from dput.interface import (AbstractInterface, ALL_BUTTONS, BUTTON_YES_NO, BUTTON_OK, BUTTON_YES) and context (functions, classes, or occasionally code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/interface.py # class AbstractInterface(object): # """ # Abstract base class for Concrete implementations of user interfaces. # # The invoking process will instantiate the process, call initialize, # query (any number of times), and shutdown. # """ # # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Set up the interface state. # """ # pass # # def boolean(self, title, message, question_type=BUTTON_YES_NO, # default=None): # """ # Display a question returning a boolean value. This is evaluated # by checking the button return code either to be BUTTON_YES or # BUTTON_OK # """ # self.widget_type = WIDGET_BOOLEAN # self.message = message # self.question_type = question_type # self.default = default # # def message(self, title, message, question_type=BUTTON_OK): # """ # Display a message and a confirmation button when required by the # interface to make sure the user noticed the message Some interfaces, # e.g. the CLI may ignore the button. # """ # self.widget_type = WIDGET_MESSAGE # self.message = message # self.question_type = question_type # # def list(self, title, message, selections=[]): # """ # Display a list of alternatives the user can choose from, returns a # list of selections. # """ # self.widget_type = WIDGET_LIST # self.message = message # self.selection = selections # # def question(self, title, message, echo_input=True): # """ # Query for user input. The input is returned literally # """ # self.widget_type = WIDGET_QUESTION # self.message = message # self.echo_input = True # # def password(self, title, message): # """ # Query for user input. The input is returned literally but not printed # back. This is a shortcut to # :meth:`dput.interface.AbstractInterface.question` with echo_input # defaulting to False # """ # self.question(title, message, echo_input=False) # # @abc.abstractmethod # def shutdown(self): # """ # Get rid of everything, close out. # """ # pass # # ALL_BUTTONS = [BUTTON_YES, BUTTON_NO, BUTTON_CANCEL, BUTTON_OK] # # BUTTON_YES_NO = [BUTTON_YES, BUTTON_NO] # # BUTTON_OK = "ok" # # BUTTON_YES = "yes" . Output only the next line.
def boolean(self, title, message, question_type=BUTTON_YES_NO,
Next line prediction: <|code_start|> buttons = [count for count in ALL_BUTTONS if count.startswith(str_button[0:index])] if len(buttons) == 0: break elif len(buttons) == 1: return buttons[0] return None def boolean(self, title, message, question_type=BUTTON_YES_NO, default=None): """ See :meth:`dput.interface.AbstractInterface.boolean` """ super(CLInterface, self).boolean(title, message, question_type) choices = "" question_len = len(question_type) for question in question_type: button_name = self.button_to_str(question) if question == default: button_name = button_name.upper() choices += button_name question_len -= 1 if question_len: choices += ", " user_input = None while not user_input: user_input = self.question(title, "%s [%s]" % (message, choices)) user_input = self.str_to_button(user_input, default) logger.trace("translated user input '%s'" % (user_input)) <|code_end|> . Use current file imports: (import sys import getpass from dput.core import logger from dput.interface import (AbstractInterface, ALL_BUTTONS, BUTTON_YES_NO, BUTTON_OK, BUTTON_YES)) and context including class names, function names, or small code snippets from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/interface.py # class AbstractInterface(object): # """ # Abstract base class for Concrete implementations of user interfaces. # # The invoking process will instantiate the process, call initialize, # query (any number of times), and shutdown. # """ # # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Set up the interface state. # """ # pass # # def boolean(self, title, message, question_type=BUTTON_YES_NO, # default=None): # """ # Display a question returning a boolean value. This is evaluated # by checking the button return code either to be BUTTON_YES or # BUTTON_OK # """ # self.widget_type = WIDGET_BOOLEAN # self.message = message # self.question_type = question_type # self.default = default # # def message(self, title, message, question_type=BUTTON_OK): # """ # Display a message and a confirmation button when required by the # interface to make sure the user noticed the message Some interfaces, # e.g. the CLI may ignore the button. # """ # self.widget_type = WIDGET_MESSAGE # self.message = message # self.question_type = question_type # # def list(self, title, message, selections=[]): # """ # Display a list of alternatives the user can choose from, returns a # list of selections. # """ # self.widget_type = WIDGET_LIST # self.message = message # self.selection = selections # # def question(self, title, message, echo_input=True): # """ # Query for user input. The input is returned literally # """ # self.widget_type = WIDGET_QUESTION # self.message = message # self.echo_input = True # # def password(self, title, message): # """ # Query for user input. The input is returned literally but not printed # back. This is a shortcut to # :meth:`dput.interface.AbstractInterface.question` with echo_input # defaulting to False # """ # self.question(title, message, echo_input=False) # # @abc.abstractmethod # def shutdown(self): # """ # Get rid of everything, close out. # """ # pass # # ALL_BUTTONS = [BUTTON_YES, BUTTON_NO, BUTTON_CANCEL, BUTTON_OK] # # BUTTON_YES_NO = [BUTTON_YES, BUTTON_NO] # # BUTTON_OK = "ok" # # BUTTON_YES = "yes" . Output only the next line.
if user_input in (BUTTON_OK, BUTTON_YES):
Continue the code snippet: <|code_start|> buttons = [count for count in ALL_BUTTONS if count.startswith(str_button[0:index])] if len(buttons) == 0: break elif len(buttons) == 1: return buttons[0] return None def boolean(self, title, message, question_type=BUTTON_YES_NO, default=None): """ See :meth:`dput.interface.AbstractInterface.boolean` """ super(CLInterface, self).boolean(title, message, question_type) choices = "" question_len = len(question_type) for question in question_type: button_name = self.button_to_str(question) if question == default: button_name = button_name.upper() choices += button_name question_len -= 1 if question_len: choices += ", " user_input = None while not user_input: user_input = self.question(title, "%s [%s]" % (message, choices)) user_input = self.str_to_button(user_input, default) logger.trace("translated user input '%s'" % (user_input)) <|code_end|> . Use current file imports: import sys import getpass from dput.core import logger from dput.interface import (AbstractInterface, ALL_BUTTONS, BUTTON_YES_NO, BUTTON_OK, BUTTON_YES) and context (classes, functions, or code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/interface.py # class AbstractInterface(object): # """ # Abstract base class for Concrete implementations of user interfaces. # # The invoking process will instantiate the process, call initialize, # query (any number of times), and shutdown. # """ # # __metaclass__ = abc.ABCMeta # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Set up the interface state. # """ # pass # # def boolean(self, title, message, question_type=BUTTON_YES_NO, # default=None): # """ # Display a question returning a boolean value. This is evaluated # by checking the button return code either to be BUTTON_YES or # BUTTON_OK # """ # self.widget_type = WIDGET_BOOLEAN # self.message = message # self.question_type = question_type # self.default = default # # def message(self, title, message, question_type=BUTTON_OK): # """ # Display a message and a confirmation button when required by the # interface to make sure the user noticed the message Some interfaces, # e.g. the CLI may ignore the button. # """ # self.widget_type = WIDGET_MESSAGE # self.message = message # self.question_type = question_type # # def list(self, title, message, selections=[]): # """ # Display a list of alternatives the user can choose from, returns a # list of selections. # """ # self.widget_type = WIDGET_LIST # self.message = message # self.selection = selections # # def question(self, title, message, echo_input=True): # """ # Query for user input. The input is returned literally # """ # self.widget_type = WIDGET_QUESTION # self.message = message # self.echo_input = True # # def password(self, title, message): # """ # Query for user input. The input is returned literally but not printed # back. This is a shortcut to # :meth:`dput.interface.AbstractInterface.question` with echo_input # defaulting to False # """ # self.question(title, message, echo_input=False) # # @abc.abstractmethod # def shutdown(self): # """ # Get rid of everything, close out. # """ # pass # # ALL_BUTTONS = [BUTTON_YES, BUTTON_NO, BUTTON_CANCEL, BUTTON_OK] # # BUTTON_YES_NO = [BUTTON_YES, BUTTON_NO] # # BUTTON_OK = "ok" # # BUTTON_YES = "yes" . Output only the next line.
if user_input in (BUTTON_OK, BUTTON_YES):
Continue the code snippet: <|code_start|># Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class RescheduleCommandError(DcutError): pass class RescheduleCommand(AbstractCommand): def __init__(self, interface): super(RescheduleCommand, self).__init__(interface) self.cmd_name = "reschedule" self.cmd_purpose = "reschedule a deferred upload" def generate_commands_name(self, profile): <|code_end|> . Use current file imports: from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.commands.cancel import generate_debianqueued_commands_name and context (classes, functions, or code) from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/commands/cancel.py # def generate_debianqueued_commands_name(profile): # # for debianqueued: $login-$timestamp.commands # # for dak: $login-$timestamp.dak-commands # the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) # logger.trace("Commands file will be named %s" % (the_file)) # return the_file . Output only the next line.
return generate_debianqueued_commands_name(profile)
Predict the next line for this snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class CancelCommandError(DcutError): pass def generate_debianqueued_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) logger.trace("Commands file will be named %s" % (the_file)) return the_file <|code_end|> with the help of current file imports: import time from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username and context from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): , which may contain function names, class names, or code. Output only the next line.
class CancelCommand(AbstractCommand):
Predict the next line after this snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class CancelCommandError(DcutError): pass def generate_debianqueued_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) <|code_end|> using the current file's imports: import time from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username and any relevant context from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): . Output only the next line.
logger.trace("Commands file will be named %s" % (the_file))
Given snippet: <|code_start|># -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class CancelCommandError(DcutError): pass def generate_debianqueued_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands <|code_end|> , continue by predicting the next line. Consider current file imports: import time from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username and context: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): which might include code, classes, or functions. Output only the next line.
the_file = "%s-%s.commands" % (get_local_username(), int(time.time()))
Based on the snippet: <|code_start|> def check_debs_in_upload(changes, profile, interface): """ The ``check-debs`` checker is a stock dput checker that checks packages intended for upload for .deb packages. Profile key: ``foo`` Example profile:: { "skip": false, "enforce": "debs" } ``skip`` controls if the checker should drop out without checking for anything at all. ``enforce`` This controls what we check for. Valid values are "debs" or "source". Nonsense values will cause an abort. """ debs = {} if 'check-debs' in profile: debs = profile['check-debs'] section = changes.get_section() BYHAND = (section == "byhand") <|code_end|> , predict the immediate next line with the help of imports: from dput.core import logger from dput.exceptions import HookException and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass . Output only the next line.
logger.debug("Is BYHAND: %s" % (BYHAND))
Next line prediction: <|code_start|># the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # XXX: document. def make_delayed_upload(conf, delayed_days): """ DELAYED uploads to ftp-master eventually means to use another incoming directory instead of the default. This is easy enough to be implemented Mangles the supplied configuration object """ incoming_directory = os.path.join( conf['incoming'], "DELAYED", "%d-day" % (delayed_days) ) <|code_end|> . Use current file imports: (import os from dput.core import logger) and context including class names, function names, or small code snippets from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): . Output only the next line.
logger.debug("overriding upload directory to %s" % (incoming_directory))
Continue the code snippet: <|code_start|> # Copyright (c) 2013 Luca Falavigna <dktrkranz@debian.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class DebomaticCommandError(DcutError): pass class BinNMUCommand(AbstractCommand): def __init__(self, interface): super(BinNMUCommand, self).__init__(interface) self.cmd_name = "debomatic-binnmu" self.cmd_purpose = ("generate a binNMU upload with Deb-o-Matic") def generate_commands_name(self, profile): <|code_end|> . Use current file imports: from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.commands.cancel import generate_debianqueued_commands_name from dput.profile import load_profile and context (classes, functions, or code) from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/commands/cancel.py # def generate_debianqueued_commands_name(profile): # # for debianqueued: $login-$timestamp.commands # # for dak: $login-$timestamp.dak-commands # the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) # logger.trace("Commands file will be named %s" % (the_file)) # return the_file # # Path: dput/profile.py # def load_profile(host): # """ # Load a profile, for a given host ``host``. In the case where # ``host`` has a ":", that'll be treated as an expansion for # config strings. For instance: # # ``ppa:paultag/fluxbox`` will expand any ``%(ppa)s`` strings to # ``paultag/fluxbox``. Comes in super handy. # """ # global _multi_config # # repls = {} # if host and ":" in host: # host, arg = host.split(":", 1) # repls[host] = arg # # if _multi_config is None: # _multi_config = MultiConfig() # config = _multi_config # config.set_replacements(repls) # configs = config.get_config_blocks() # # if host in configs: # return config.get_config(host) # # if host is not None: # raise DputConfigurationError("Error, was given host, " # "but we don't know about it.") # # for block in configs: # try: # obj = config.get_config(block) # except DputConfigurationError: # continue # We don't have fully converted blocks. # # host_main = obj.get('default_host_main') # if host_main: # If we have a default_host_main, let's return that. # return config.get_config(host_main) # return config.get_config("ftp-master") . Output only the next line.
return generate_debianqueued_commands_name(profile)
Next line prediction: <|code_start|> def register(self, parser, **kwargs): parser.add_argument('-s', '--source', metavar="SOURCE", action='store', default=None, help="source package to rebuild. ", required=True) parser.add_argument('-v', '--version', metavar="VERSION", action='store', default=None, help="version of " "the source package to rebuild. ", required=True) parser.add_argument('-d', '--distribution', metavar="DISTRIBUTION", action='store', default=None, help="distribution " "which rebuild the package for. ", required=True) parser.add_argument('-b', '--binnmu-version', metavar="VERSION", action='store', default=None, help="binNMU version", required=True) parser.add_argument('-c', '--changelog', metavar="CHANGELOG", action='store', default=None, help="binNMU changelog entry", required=True) parser.add_argument('-m', '--maintainer', metavar="MAINTAINER", action='store', default=None, help="contact to be " "listed in the Maintainer field. ", required=True) def produce(self, fh, args): fh.write("Commands:\n") fh.write(" binnmu %s_%s %s %s \"%s\" %s\n" % (args.source, args.version, args.distribution, args.binnmu_version, args.changelog, args.maintainer)) def validate(self, args): <|code_end|> . Use current file imports: (from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.commands.cancel import generate_debianqueued_commands_name from dput.profile import load_profile) and context including class names, function names, or small code snippets from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/commands/cancel.py # def generate_debianqueued_commands_name(profile): # # for debianqueued: $login-$timestamp.commands # # for dak: $login-$timestamp.dak-commands # the_file = "%s-%s.commands" % (get_local_username(), int(time.time())) # logger.trace("Commands file will be named %s" % (the_file)) # return the_file # # Path: dput/profile.py # def load_profile(host): # """ # Load a profile, for a given host ``host``. In the case where # ``host`` has a ":", that'll be treated as an expansion for # config strings. For instance: # # ``ppa:paultag/fluxbox`` will expand any ``%(ppa)s`` strings to # ``paultag/fluxbox``. Comes in super handy. # """ # global _multi_config # # repls = {} # if host and ":" in host: # host, arg = host.split(":", 1) # repls[host] = arg # # if _multi_config is None: # _multi_config = MultiConfig() # config = _multi_config # config.set_replacements(repls) # configs = config.get_config_blocks() # # if host in configs: # return config.get_config(host) # # if host is not None: # raise DputConfigurationError("Error, was given host, " # "but we don't know about it.") # # for block in configs: # try: # obj = config.get_config(block) # except DputConfigurationError: # continue # We don't have fully converted blocks. # # host_main = obj.get('default_host_main') # if host_main: # If we have a default_host_main, let's return that. # return config.get_config(host_main) # return config.get_config("ftp-master") . Output only the next line.
profile = load_profile(args.host)
Here is a snippet: <|code_start|> if not isinstance(a, Sftp.STATUS): raise SftpUnexpectedAnswerException(a, a.forr) elif a.status != a.Status.OK: raise SftpUploadException("Error writing to %s: %s: %s" % ( filename, a.forr, a)) class SFTPUploader(AbstractUploader): """ Provides an interface to upload files through SFTP. This is a subclass of :class:`dput.uploader.AbstractUploader` """ def initialize(self, **kwargs): """ See :meth:`dput.uploader.AbstractUploader.initialize` """ fqdn = self._config['fqdn'] incoming = self._config['incoming'] ssh_options = [] if "ssh_options" in self._config: ssh_options.extend(self._config['ssh_options']) if 'port' in self._config: ssh_options.append("-oPort=%d" % self._config['port']) username = None if 'login' in self._config and self._config['login'] != "*": username = self._config['login'] if incoming.startswith('~/'): <|code_end|> . Write the next line using the current file imports: import os.path import subprocess import select from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass , which may include functions, classes, or code. Output only the next line.
logger.warning("SFTP does not support ~/path, continuing with"
Next line prediction: <|code_start|> else: raise SftpUploadException("Failed to create %s: %s" % (filename, a)) if not isinstance(a, Sftp.HANDLE): raise SftpUnexpectedAnswerException(a, a.forr) h = a.handle a.forr.done() ranges = list(range(0, size, 32600)) if ranges: requests = [Sftp.WRITE(h, r, filepart(localf, r, 32600)) for r in ranges[:-1]] requests.append(Sftp.WRITE(h, ranges[-1], filepart(localf, ranges[-1], size - ranges[-1]))) a = yield requests while requests: a.forr.done() if not isinstance(a, Sftp.STATUS): raise SftpUnexpectedAnswerException(a, a.forr) elif a.status != a.Status.OK: raise SftpUploadException("Error writing to %s: %s: %s" % ( filename, a.forr, a)) requests.remove(a.forr) a = yield [] a = yield [Sftp.CLOSE(h)] a.forr.done() if not isinstance(a, Sftp.STATUS): raise SftpUnexpectedAnswerException(a, a.forr) elif a.status != a.Status.OK: raise SftpUploadException("Error writing to %s: %s: %s" % ( filename, a.forr, a)) <|code_end|> . Use current file imports: (import os.path import subprocess import select from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException) and context including class names, function names, or small code snippets from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass . Output only the next line.
class SFTPUploader(AbstractUploader):
Here is a snippet: <|code_start|> (e.value, str(l), type(self).__name__)) def __int__(self): v = 0 for i in self: v = v | int(i) return v def __str__(self): return "|".join([str(i) for i in self]) @classmethod def create(cls, name, values): class bitmask(Bitmask): __name__ = "Bitmask of " + name class Values(Enum): __name__ = name byvalue = dict() byname = dict() bitmask.__name__ = "Bitmask of " + name for (k, v) in values.items(): if isinstance(v, int): e = bitmask.Values(k, v) e.mask = v else: e = bitmask.Values(k, v[0]) e.mask = v[1] return bitmask <|code_end|> . Write the next line using the current file imports: import os.path import subprocess import select from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass , which may include functions, classes, or code. Output only the next line.
class SftpUploadException(UploadException):
Predict the next line for this snippet: <|code_start|> Sections with a prefix, separated with a forward-slash also show the component. It returns a list of strings in the form [component, section]. For example, `non-free/python` has component `non-free` and section `python`. ``section`` Section name to parse. """ if '/' in section: return section.split('/') else: return ['main', section] def set_directory(self, directory): if directory: self._directory = directory else: self._directory = "" def validate(self, check_hash="sha1", check_signature=True): """ See :meth:`validate_checksums` for ``check_hash``, and :meth:`validate_signature` if ``check_signature`` is True. """ self.validate_checksums(check_hash) if check_signature: self.validate_signature(check_signature) else: <|code_end|> with the help of current file imports: import sys import os.path import hashlib from debian import deb822 from dput.core import logger from dput.util import run_command from dput.exceptions import ChangesFileException and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr , which may contain function names, class names, or code. Output only the next line.
logger.info("Not checking signature")
Based on the snippet: <|code_start|> return section.split('/') else: return ['main', section] def set_directory(self, directory): if directory: self._directory = directory else: self._directory = "" def validate(self, check_hash="sha1", check_signature=True): """ See :meth:`validate_checksums` for ``check_hash``, and :meth:`validate_signature` if ``check_signature`` is True. """ self.validate_checksums(check_hash) if check_signature: self.validate_signature(check_signature) else: logger.info("Not checking signature") def validate_signature(self, check_signature=True): """ Validate the GPG signature of a .changes file. Throws a :class:`dput.exceptions.ChangesFileException` if there's an issue with the GPG signature. Returns the GPG key ID. """ gpg_path = "gpg" <|code_end|> , predict the immediate next line with the help of imports: import sys import os.path import hashlib from debian import deb822 from dput.core import logger from dput.util import run_command from dput.exceptions import ChangesFileException and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr . Output only the next line.
(gpg_output, gpg_output_stderr, exit_status) = run_command([
Based on the snippet: <|code_start|> """ def __init__(self, filename=None, string=None): """ Object constructor. The object allows the user to specify **either**: #. a path to a *changes* file to parse #. a string with the *changes* file contents. :: a = Changes(filename='/tmp/packagename_version.changes') b = Changes(string='Source: packagename\\nMaintainer: ...') ``filename`` Path to *changes* file to parse. ``string`` *changes* file in a string to parse. """ if (filename and string) or (not filename and not string): raise TypeError if filename: self._absfile = os.path.abspath(filename) self._data = deb822.Changes(open(filename)) else: self._data = deb822.Changes(string) if len(self._data) == 0: <|code_end|> , predict the immediate next line with the help of imports: import sys import os.path import hashlib from debian import deb822 from dput.core import logger from dput.util import run_command from dput.exceptions import ChangesFileException and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr . Output only the next line.
raise ChangesFileException('Changes file could not be parsed.')
Here is a snippet: <|code_start|># 02110-1301, USA. def test_parse_overrides(): test_cases = [ ({'foo': [['bar']]}, ['foo=bar']), ({'foo': [None]}, ['-foo']), ({'+foo': [['bar']]}, ['+foo=bar']), ({'foo': [None, ['1']]}, ['-foo', 'foo=1']), ({'foo': {'bar': {'baz': [['paultag.is.a.god']]}}}, ['foo.bar.baz=paultag.is.a.god']), ({'foo': {'bar': [['1'], ['2'], ['3']]}, 'foo2': [['4']]}, ['foo.bar=1', 'foo.bar=2', 'foo.bar=3', 'foo2=4']), ({'foo': {'bar': [['True=True'], ['foo=False', 'obj2']]}, 'foo2': [['bar']]}, ['foo.bar = "True=True"', "foo.bar='foo'=False 'obj2'", 'foo2=bar']) ] bad_test_cases = [ (None, ['invalid']), (None, ['foo=bar', 'foo=bar', 'foo.bar=bar']), (None, ['foo.bar=1', 'foo.bar.baz=1']) ] for (expectation, case) in test_cases: <|code_end|> . Write the next line using the current file imports: from dput.profile import parse_overrides from dput.exceptions import DputConfigurationError and context from other files: # Path: dput/profile.py # def parse_overrides(overrides): # """ # Translate a complex string structure into a JSON like object. For example # this function would translate foo.bar=baz like strings into objects # overriding the JSON profile. # # Basically this function function will take any object separated by a dot on # the left side as a dict object, whereas the terminal value on the right # side is taken literally. # """ # # This function involves lots of black magic. # # Generally we expect a foo.bar=value format, with foo.bar being a profile # # key and value being $anything. # # However, people might provide that in weird combinations such as # # 'foo.bar = "value value"' # override_obj = {} # for override in overrides: # parent_obj = override_obj # if override.find("=") > 0 or override.startswith("-") > 0: # (profile_key, profile_value) = (None, None) # if override.startswith("-"): # profile_key = override[1:] # profile_value = None # else: # (profile_key, profile_value) = override.split("=", 1) # profile_value = shlex.split(profile_value) # profile_key = re.sub(r'\s', '', profile_key) # profile_key = profile_key.split(".") # last_item = profile_key.pop() # # for key in profile_key: # if not key in parent_obj: # parent_obj[key] = {} # parent_obj = parent_obj[key] # # if isinstance(parent_obj, list): # raise DputConfigurationError("Ambiguous override: object %s " # "can either be a composite type or a terminal, not both" % # (last_item)) # # if not last_item in parent_obj: # parent_obj[last_item] = [] # if last_item in parent_obj and not ( # isinstance(parent_obj[last_item], list)): # raise DputConfigurationError("Ambiguous override: object %s " # "can either be a composite type or a terminal, not both" % # (last_item)) # parent_obj[last_item].append(profile_value) # else: # raise DputConfigurationError( # "Profile override %s does not seem to match the " # "expected format" % override) # return override_obj # # Path: dput/exceptions.py # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass , which may include functions, classes, or code. Output only the next line.
print(parse_overrides(case))
Predict the next line for this snippet: <|code_start|> ({'foo': [None]}, ['-foo']), ({'+foo': [['bar']]}, ['+foo=bar']), ({'foo': [None, ['1']]}, ['-foo', 'foo=1']), ({'foo': {'bar': {'baz': [['paultag.is.a.god']]}}}, ['foo.bar.baz=paultag.is.a.god']), ({'foo': {'bar': [['1'], ['2'], ['3']]}, 'foo2': [['4']]}, ['foo.bar=1', 'foo.bar=2', 'foo.bar=3', 'foo2=4']), ({'foo': {'bar': [['True=True'], ['foo=False', 'obj2']]}, 'foo2': [['bar']]}, ['foo.bar = "True=True"', "foo.bar='foo'=False 'obj2'", 'foo2=bar']) ] bad_test_cases = [ (None, ['invalid']), (None, ['foo=bar', 'foo=bar', 'foo.bar=bar']), (None, ['foo.bar=1', 'foo.bar.baz=1']) ] for (expectation, case) in test_cases: print(parse_overrides(case)) assert(expectation == parse_overrides(case)) for (expectation, case) in bad_test_cases: try: parse_overrides(case) raise Exception("Bad test case: %s" % (case)) <|code_end|> with the help of current file imports: from dput.profile import parse_overrides from dput.exceptions import DputConfigurationError and context from other files: # Path: dput/profile.py # def parse_overrides(overrides): # """ # Translate a complex string structure into a JSON like object. For example # this function would translate foo.bar=baz like strings into objects # overriding the JSON profile. # # Basically this function function will take any object separated by a dot on # the left side as a dict object, whereas the terminal value on the right # side is taken literally. # """ # # This function involves lots of black magic. # # Generally we expect a foo.bar=value format, with foo.bar being a profile # # key and value being $anything. # # However, people might provide that in weird combinations such as # # 'foo.bar = "value value"' # override_obj = {} # for override in overrides: # parent_obj = override_obj # if override.find("=") > 0 or override.startswith("-") > 0: # (profile_key, profile_value) = (None, None) # if override.startswith("-"): # profile_key = override[1:] # profile_value = None # else: # (profile_key, profile_value) = override.split("=", 1) # profile_value = shlex.split(profile_value) # profile_key = re.sub(r'\s', '', profile_key) # profile_key = profile_key.split(".") # last_item = profile_key.pop() # # for key in profile_key: # if not key in parent_obj: # parent_obj[key] = {} # parent_obj = parent_obj[key] # # if isinstance(parent_obj, list): # raise DputConfigurationError("Ambiguous override: object %s " # "can either be a composite type or a terminal, not both" % # (last_item)) # # if not last_item in parent_obj: # parent_obj[last_item] = [] # if last_item in parent_obj and not ( # isinstance(parent_obj[last_item], list)): # raise DputConfigurationError("Ambiguous override: object %s " # "can either be a composite type or a terminal, not both" % # (last_item)) # parent_obj[last_item].append(profile_value) # else: # raise DputConfigurationError( # "Profile override %s does not seem to match the " # "expected format" % override) # return override_obj # # Path: dput/exceptions.py # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass , which may contain function names, class names, or code. Output only the next line.
except DputConfigurationError:
Given the following code snippet before the placeholder: <|code_start|># Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ FTP Uploader implementation. """ class FtpUploadException(UploadException): """ Thrown in the event of a problem connecting, uploading to or terminating the connection with the remote server. This is a subclass of :class:`dput.exceptions.UploadException`. """ pass class FtpUploader(AbstractUploader): """ Provides an interface to upload files through FTP. Supports anonymous uploads only for the time being. This is a subclass of :class:`dput.uploader.AbstractUploader` """ def initialize(self, **kwargs): """ See :meth:`dput.uploader.AbstractUploader.initialize` """ <|code_end|> , predict the next line using imports from the current file: import ftplib import os.path from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass . Output only the next line.
logger.debug("Logging into %s as %s" % (
Continue the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ FTP Uploader implementation. """ class FtpUploadException(UploadException): """ Thrown in the event of a problem connecting, uploading to or terminating the connection with the remote server. This is a subclass of :class:`dput.exceptions.UploadException`. """ pass <|code_end|> . Use current file imports: import ftplib import os.path from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context (classes, functions, or code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass . Output only the next line.
class FtpUploader(AbstractUploader):
Continue the code snippet: <|code_start|># # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. KEYRINGS = [ "/usr/share/keyrings/debian-maintainers.gpg", "/usr/share/keyrings/debian-nonupload.gpg" ] class DmCommandError(DcutError): pass def generate_dak_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time())) # XXX: override w/ DEBEMAIL (if DEBEMAIL is @debian.org?) logger.trace("Commands file will be named %s" % (the_file)) return the_file <|code_end|> . Use current file imports: import time import os.path from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username from dput.util import run_command and context (classes, functions, or code) from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) . Output only the next line.
class DmCommand(AbstractCommand):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. KEYRINGS = [ "/usr/share/keyrings/debian-maintainers.gpg", "/usr/share/keyrings/debian-nonupload.gpg" ] <|code_end|> with the help of current file imports: import time import os.path from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username from dput.util import run_command and context from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) , which may contain function names, class names, or code. Output only the next line.
class DmCommandError(DcutError):
Here is a snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. KEYRINGS = [ "/usr/share/keyrings/debian-maintainers.gpg", "/usr/share/keyrings/debian-nonupload.gpg" ] class DmCommandError(DcutError): pass def generate_dak_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time())) # XXX: override w/ DEBEMAIL (if DEBEMAIL is @debian.org?) <|code_end|> . Write the next line using the current file imports: import time import os.path from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username from dput.util import run_command and context from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) , which may include functions, classes, or code. Output only the next line.
logger.trace("Commands file will be named %s" % (the_file))
Given the code snippet: <|code_start|># Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. KEYRINGS = [ "/usr/share/keyrings/debian-maintainers.gpg", "/usr/share/keyrings/debian-nonupload.gpg" ] class DmCommandError(DcutError): pass def generate_dak_commands_name(profile): # for debianqueued: $login-$timestamp.commands # for dak: $login-$timestamp.dak-commands <|code_end|> , generate the next line using the imports in this file: import time import os.path from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username from dput.util import run_command and context (functions, classes, or occasionally code) from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) . Output only the next line.
the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time()))
Next line prediction: <|code_start|> def validate(self, args): if args.force: return if not all((os.path.exists(keyring) for keyring in KEYRINGS)): raise DmCommandError( "To manage DM permissions, the `debian-keyring' " "keyring package must be installed." ) # I HATE embedded functions. But OTOH this function is not usable # somewhere else, so... def pretty_print_list(tuples): fingerprints = "" for entry in tuples: fingerprints += "\n- %s (%s)" % entry return fingerprints # I don't mind embedded functions ;3 def flatten(it): return [ item for nested in it for item in nested ] # TODO: Validate input. Packages must exist (i.e. be not NEW) cmd =[ "gpg", "--no-options", "--no-auto-check-trustdb", "--no-default-keyring", "--list-key", "--with-colons", "--fingerprint" ] + flatten(([ "--keyring", keyring] for keyring in KEYRINGS)) + [ args.dm ] <|code_end|> . Use current file imports: (import time import os.path from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.core import logger, get_local_username from dput.util import run_command) and context including class names, function names, or small code snippets from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def run_command(command, env=None): # """ # Run a synchronized command. The argument must be a list of arguments. # Returns a triple (stdout, stderr, exit_status) # # If there was a problem to start the supplied command, (None, None, -1) is # returned # """ # if not isinstance(command, list): # command = shlex.split(command) # try: # pipe = subprocess.Popen(command, # env=env, # shell=False, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # except OSError as e: # logger.error("Could not execute %s: %s" % (" ".join(command), e)) # return (None, None, -1) # (output, stderr) = pipe.communicate() # output = output.decode('utf-8', errors='replace') # stderr = stderr.decode('utf-8', errors='replace') # #if pipe.returncode != 0: # # error("Command %s returned failure: %s" % (" ".join(command), stderr)) # return (output, stderr, pipe.returncode) . Output only the next line.
(out, err, exit_status) = run_command(cmd)
Next line prediction: <|code_start|> dput.core.CONFIG_LOCATIONS = { os.path.abspath("./tests/dputng"): 0 } # Isolate. def test_config_load(): """ Make sure we can cleanly load a config """ obj = load_config('profiles', 'test_profile') comp = { "incoming": "/dev/null", "method": "local", "meta": "ubuntu" } for key in comp: assert obj[key] == comp[key] def test_config_validate(): """ Make sure we can validate a good config """ obj = load_config('profiles', 'test_profile') <|code_end|> . Use current file imports: (from dput.util import validate_object, load_config from dput.exceptions import InvalidConfigError import dput.core import os) and context including class names, function names, or small code snippets from other files: # Path: dput/util.py # def validate_object(schema, obj, name): # sobj = None # for root in dput.core.SCHEMA_DIRS: # if sobj is not None: # logger.debug("Skipping %s" % (root)) # continue # # logger.debug("Loading schema %s from %s" % (schema, root)) # spath = "%s/%s.json" % ( # root, # schema # ) # try: # if os.path.exists(spath): # sobj = json.load(open(spath, 'r')) # else: # logger.debug("No such config: %s" % (spath)) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # spath, # e # )) # # if sobj is None: # logger.critical("Schema not found: %s" % (schema)) # raise DputConfigurationError("No such schema: %s" % (schema)) # # try: # import validictory # validictory.validate(obj, sobj) # except ImportError: # pass # except validictory.validator.ValidationError as e: # err = str(e) # error = "Error with config file %s - %s" % ( # name, # err # ) # ex = InvalidConfigError(error) # ex.obj = obj # ex.root = e # ex.config_name = name # ex.sdir = dput.core.SCHEMA_DIRS # ex.schema = schema # raise ex # # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
validate_object('config', obj, "profiles/test_profile")
Continue the code snippet: <|code_start|> dput.core.CONFIG_LOCATIONS = { os.path.abspath("./tests/dputng"): 0 } # Isolate. def test_config_load(): """ Make sure we can cleanly load a config """ <|code_end|> . Use current file imports: from dput.util import validate_object, load_config from dput.exceptions import InvalidConfigError import dput.core import os and context (classes, functions, or code) from other files: # Path: dput/util.py # def validate_object(schema, obj, name): # sobj = None # for root in dput.core.SCHEMA_DIRS: # if sobj is not None: # logger.debug("Skipping %s" % (root)) # continue # # logger.debug("Loading schema %s from %s" % (schema, root)) # spath = "%s/%s.json" % ( # root, # schema # ) # try: # if os.path.exists(spath): # sobj = json.load(open(spath, 'r')) # else: # logger.debug("No such config: %s" % (spath)) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # spath, # e # )) # # if sobj is None: # logger.critical("Schema not found: %s" % (schema)) # raise DputConfigurationError("No such schema: %s" % (schema)) # # try: # import validictory # validictory.validate(obj, sobj) # except ImportError: # pass # except validictory.validator.ValidationError as e: # err = str(e) # error = "Error with config file %s - %s" % ( # name, # err # ) # ex = InvalidConfigError(error) # ex.obj = obj # ex.root = e # ex.config_name = name # ex.sdir = dput.core.SCHEMA_DIRS # ex.schema = schema # raise ex # # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
obj = load_config('profiles', 'test_profile')
Continue the code snippet: <|code_start|> dput.core.CONFIG_LOCATIONS = { os.path.abspath("./tests/dputng"): 0 } # Isolate. def test_config_load(): """ Make sure we can cleanly load a config """ obj = load_config('profiles', 'test_profile') comp = { "incoming": "/dev/null", "method": "local", "meta": "ubuntu" } for key in comp: assert obj[key] == comp[key] def test_config_validate(): """ Make sure we can validate a good config """ obj = load_config('profiles', 'test_profile') validate_object('config', obj, "profiles/test_profile") def test_config_invalidate(): """ Make sure a bad validation breaks """ obj = load_config('profiles', 'test_profile_bad') try: validate_object('config', obj, "profiles/test_profile_bad") assert True is False <|code_end|> . Use current file imports: from dput.util import validate_object, load_config from dput.exceptions import InvalidConfigError import dput.core import os and context (classes, functions, or code) from other files: # Path: dput/util.py # def validate_object(schema, obj, name): # sobj = None # for root in dput.core.SCHEMA_DIRS: # if sobj is not None: # logger.debug("Skipping %s" % (root)) # continue # # logger.debug("Loading schema %s from %s" % (schema, root)) # spath = "%s/%s.json" % ( # root, # schema # ) # try: # if os.path.exists(spath): # sobj = json.load(open(spath, 'r')) # else: # logger.debug("No such config: %s" % (spath)) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # spath, # e # )) # # if sobj is None: # logger.critical("Schema not found: %s" % (schema)) # raise DputConfigurationError("No such schema: %s" % (schema)) # # try: # import validictory # validictory.validate(obj, sobj) # except ImportError: # pass # except validictory.validator.ValidationError as e: # err = str(e) # error = "Error with config file %s - %s" % ( # name, # err # ) # ex = InvalidConfigError(error) # ex.obj = obj # ex.root = e # ex.config_name = name # ex.sdir = dput.core.SCHEMA_DIRS # ex.schema = schema # raise ex # # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
except InvalidConfigError as e:
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2013 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. try: except ImportError: logger.warning('Uploading to Ubuntu requires python3-distro-info to be ' 'installed') raise <|code_end|> , predict the next line using imports from the current file: from dput.core import logger from dput.exceptions import HookException from distro_info import (DebianDistroInfo, UbuntuDistroInfo, DistroDataOutdated) and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass . Output only the next line.
class UnknownDistribution(HookException):
Predict the next line after this snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ HTTP Uploader implementation """ class HttpUploadException(UploadException): """ Thrown in the event of a problem connecting, uploading to or terminating the connection with the remote server. This is a subclass of :class:`dput.exceptions.UploadException`. """ pass <|code_end|> using the current file's imports: from dput.exceptions import UploadException from dput.uploader import AbstractUploader from dput.core import logger import mmap import urllib.parse import urllib.request import os.path import mimetypes and any relevant context from other files: # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): . Output only the next line.
class HTTPUploader(AbstractUploader):
Given snippet: <|code_start|> _incoming = self._config['incoming'] if not _incoming.startswith("/"): _incoming = "/" + _incoming if not _incoming.endswith("/"): _incoming = _incoming + "/" _path = self._baseurl.path if not _path: _path = _incoming else: _path = _path + _incoming _params = self._baseurl.params _query = self._baseurl.query _fragment = self._baseurl.fragment self._username = self._baseurl.username self._password = self._baseurl.password # XXX: Timeout, please. self._baseurl = urllib.parse.urlunparse((self._baseurl.scheme, _netloc, _path, _params, _query, _fragment)) def upload_file(self, filename, upload_filename=None): """ See :meth:`dput.uploader.AbstractUploader.upload_file` """ upload_filename = self._baseurl + os.path.basename(filename) <|code_end|> , continue by predicting the next line. Consider current file imports: from dput.exceptions import UploadException from dput.uploader import AbstractUploader from dput.core import logger import mmap import urllib.parse import urllib.request import os.path import mimetypes and context: # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): which might include code, classes, or functions. Output only the next line.
logger.debug("Upload to %s" % (upload_filename))
Given the following code snippet before the placeholder: <|code_start|># (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ Misc & helper functions """ def load_obj(obj_path): """ Dynamically load an object (class, method, etc) by name (such as `dput.core.ClassName`), and return that object to work with. This is useful for loading modules on the fly, without them being all loaded at once, or even in the same package. Call this routine with at least one dot in it -- it attempts to load the module (such as dput.core) and use getattr to load the thing - similar to how `from` works. """ dput.core.mangle_sys() <|code_end|> , predict the next line using imports from the current file: import os import json import shlex import importlib import subprocess import dput.core import validictory from contextlib import contextmanager from dput.core import logger from dput.exceptions import (NoSuchConfigError, DputConfigurationError, InvalidConfigError) and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class NoSuchConfigError(DputError): # """ # Thrown when dput can not find a Configuration file or block that is # requested. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
logger.trace("Loading object: %s" % (obj_path))
Based on the snippet: <|code_start|>def load_obj(obj_path): """ Dynamically load an object (class, method, etc) by name (such as `dput.core.ClassName`), and return that object to work with. This is useful for loading modules on the fly, without them being all loaded at once, or even in the same package. Call this routine with at least one dot in it -- it attempts to load the module (such as dput.core) and use getattr to load the thing - similar to how `from` works. """ dput.core.mangle_sys() logger.trace("Loading object: %s" % (obj_path)) module, obj = obj_path.rsplit(".", 1) mod = importlib.import_module(module) fltr = getattr(mod, obj) return fltr def get_obj(cls, checker_method): # checker_method is a bad name. """ Get an object by plugin def (``checker_method``) in class ``cls`` (such as ``hooks``). """ logger.trace("Attempting to resolve %s %s" % (cls, checker_method)) try: config = load_config(cls, checker_method) validate_object('plugin', config, "%s/%s" % (cls, checker_method)) if config is None or config == {}: <|code_end|> , predict the immediate next line with the help of imports: import os import json import shlex import importlib import subprocess import dput.core import validictory from contextlib import contextmanager from dput.core import logger from dput.exceptions import (NoSuchConfigError, DputConfigurationError, InvalidConfigError) and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class NoSuchConfigError(DputError): # """ # Thrown when dput can not find a Configuration file or block that is # requested. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
raise NoSuchConfigError("No such config")
Given the following code snippet before the placeholder: <|code_start|> op = operators[operator] if kname in ret: ret[kname] = op(ret[key], ret[kname]) else: foo = op(ret[key], []) if foo != []: ret[kname] = foo ret.pop(key) return ret def validate_object(schema, obj, name): sobj = None for root in dput.core.SCHEMA_DIRS: if sobj is not None: logger.debug("Skipping %s" % (root)) continue logger.debug("Loading schema %s from %s" % (schema, root)) spath = "%s/%s.json" % ( root, schema ) try: if os.path.exists(spath): sobj = json.load(open(spath, 'r')) else: logger.debug("No such config: %s" % (spath)) except ValueError as e: <|code_end|> , predict the next line using imports from the current file: import os import json import shlex import importlib import subprocess import dput.core import validictory from contextlib import contextmanager from dput.core import logger from dput.exceptions import (NoSuchConfigError, DputConfigurationError, InvalidConfigError) and context including class names, function names, and sometimes code from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class NoSuchConfigError(DputError): # """ # Thrown when dput can not find a Configuration file or block that is # requested. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
raise DputConfigurationError("syntax error in %s: %s" % (
Predict the next line after this snippet: <|code_start|> logger.debug("Loading schema %s from %s" % (schema, root)) spath = "%s/%s.json" % ( root, schema ) try: if os.path.exists(spath): sobj = json.load(open(spath, 'r')) else: logger.debug("No such config: %s" % (spath)) except ValueError as e: raise DputConfigurationError("syntax error in %s: %s" % ( spath, e )) if sobj is None: logger.critical("Schema not found: %s" % (schema)) raise DputConfigurationError("No such schema: %s" % (schema)) try: validictory.validate(obj, sobj) except ImportError: pass except validictory.validator.ValidationError as e: err = str(e) error = "Error with config file %s - %s" % ( name, err ) <|code_end|> using the current file's imports: import os import json import shlex import importlib import subprocess import dput.core import validictory from contextlib import contextmanager from dput.core import logger from dput.exceptions import (NoSuchConfigError, DputConfigurationError, InvalidConfigError) and any relevant context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class NoSuchConfigError(DputError): # """ # Thrown when dput can not find a Configuration file or block that is # requested. # """ # pass # # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass # # class InvalidConfigError(DputError): # """ # Config file was loaded properly, but it was missing part of it's # required fields. # """ # pass . Output only the next line.
ex = InvalidConfigError(error)
Predict the next line for this snippet: <|code_start|> if accept: super(AskToAccept, self).missing_host_key(client, hostname, key) else: raise paramiko.SSHException('Unknown server %s' % hostname) class SFTPUploader(AbstractUploader): """ Provides an interface to upload files through SFTP. This is a subclass of :class:`dput.uploader.AbstractUploader` """ def initialize(self, **kwargs): """ See :meth:`dput.uploader.AbstractUploader.initialize` """ fqdn = self._config['fqdn'] incoming = self._config['incoming'] self.sftp_config = {} if "sftp" in self._config: self.sftp_config = self._config['sftp'] self.putargs = {'confirm': False} if "confirm_upload" in self.sftp_config: self.putargs['confirm'] = self.sftp_config['confirm_upload'] if incoming.startswith('~/'): <|code_end|> with the help of current file imports: import paramiko import socket import os import errno import pwd import os.path from binascii import hexlify from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass , which may contain function names, class names, or code. Output only the next line.
logger.warning("SFTP does not support ~/path, continuing with"
Using the snippet: <|code_start|> "No user to upload could be retrieved. " "Please set 'login' explicitly in your profile" ) return user class AskToAccept(paramiko.AutoAddPolicy): """ Paramiko policy to automatically add the hostname, but only after asking. """ def __init__(self, uploader): super(AskToAccept, self).__init__() self.uploader = uploader def missing_host_key(self, client, hostname, key): accept = self.uploader.interface.boolean( title='please login', message='To accept %s hostkey %s for %s type "yes":' % ( key.get_name(), hexlify(key.get_fingerprint()), hostname ) ) if accept: super(AskToAccept, self).missing_host_key(client, hostname, key) else: raise paramiko.SSHException('Unknown server %s' % hostname) <|code_end|> , determine the next line of code. You have imports: import paramiko import socket import os import errno import pwd import os.path from binascii import hexlify from dput.core import logger from dput.uploader import AbstractUploader from dput.exceptions import UploadException and context (class names, function names, or code) available: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/uploader.py # class AbstractUploader(object): # """ # Abstract base class for all concrete uploader implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, profile): # self._config = profile # interface = 'cli' # if 'interface' in profile: # interface = profile['interface'] # logger.trace("Using interface %s" % (interface)) # interface_obj = get_obj('interfaces', interface) # if interface_obj is None: # raise DputConfigurationError("No such interface: `%s'" % ( # interface # )) # self.interface = interface_obj() # self.interface.initialize() # # def _pre_hook(self): # self._run_hook("pre_upload_command") # # def _post_hook(self): # self._run_hook("post_upload_command") # # def _run_hook(self, hook): # if hook in self._config and self._config[hook] != "": # cmd = self._config[hook] # (output, stderr, ret) = run_command(cmd) # if ret == -1: # if not os.path.exists(cmd): # logger.warning( # "Error: You've set a hook (%s) to run (`%s`), " # "but it can't be found (and doesn't appear to exist)." # " Please verify the path and correct it." % ( # hook, # self._config[hook] # ) # ) # return # # sys.stdout.write(output) # XXX: Fixme # sys.stdout.flush() # if ret != 0: # raise DputError( # "Command `%s' returned an error: %s [err=%d]" % ( # self._config[hook], # stderr, # ret # ) # ) # # def __del__(self): # self.interface.shutdown() # # def upload_write_error(self, e): # """ # .. warning:: # don't call this. # # please don't call this # """ # # XXX: Refactor this, please god, refactor this. # logger.warning("""Upload permissions error # # You either don't have the rights to upload a file, or, if this is on # ftp-master, you may have tried to overwrite a file already on the server. # # Continuing anyway in case you want to recover from an incomplete upload. # No file was uploaded, however.""") # # @abc.abstractmethod # def initialize(self, **kwargs): # """ # Setup the things needed to upload a file. Usually this means creating # a network connection & authenticating. # """ # pass # # @abc.abstractmethod # def upload_file(self, filename, upload_filename=None): # """ # Upload a single file (``filename``) to the server. # """ # pass # # @abc.abstractmethod # def shutdown(self): # """ # Disconnect and shutdown. # """ # pass # # Path: dput/exceptions.py # class UploadException(DputError): # """ # Thrown when there's an error uploading, or creating an uploader. Usually # thrown by a subclass of the :class:`dput.uploader.AbstractUploader` # """ # pass . Output only the next line.
class SFTPUploader(AbstractUploader):
Here is a snippet: <|code_start|> Thrown if the ``suite-mismatch`` checker encounters an issue. """ pass def check_allowed_distribution(changes, profile, interface): """ The ``allowed-distribution`` checker is a stock dput checker that checks packages intended for upload for a valid upload distribution. Profile key: none Example profile:: { ... "allowed_distributions": "(?!UNRELEASED)", "distributions": ["unstable", "testing"], "disallowed_distributions": [] ... } The allowed_distributions key is in Python ``re`` syntax. """ allowed_block = profile.get('allowed-distribution', {}) suite = changes['Distribution'] if 'allowed_distributions' in profile: srgx = profile['allowed_distributions'] if re.match(srgx, suite) is None: <|code_end|> . Write the next line using the current file imports: import re from dput.core import logger from dput.util import load_config from dput.exceptions import HookException from dput.interface import BUTTON_NO and context from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" , which may include functions, classes, or code. Output only the next line.
logger.debug("Distribution does not %s match '%s'" % (
Based on the snippet: <|code_start|> allowed_block = profile.get('allowed-distribution', {}) suite = changes['Distribution'] if 'allowed_distributions' in profile: srgx = profile['allowed_distributions'] if re.match(srgx, suite) is None: logger.debug("Distribution does not %s match '%s'" % ( suite, profile['allowed_distributions'] )) raise BadDistributionError("'%s' doesn't match '%s'" % ( suite, srgx )) if'distributions' in profile: allowed_dists = profile['distributions'] if suite not in allowed_dists.split(","): raise BadDistributionError( "'%s' doesn't contain distribution '%s'" % ( suite, profile['distributions'] )) if 'disallowed_distributions' in profile: disallowed_dists = profile['disallowed_distributions'] if suite in disallowed_dists: raise BadDistributionError("'%s' is in '%s'" % ( suite, disallowed_dists)) if 'codenames' in profile and profile['codenames']: <|code_end|> , predict the immediate next line with the help of imports: import re from dput.core import logger from dput.util import load_config from dput.exceptions import HookException from dput.interface import BUTTON_NO and context (classes, functions, sometimes code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
codenames = load_config('codenames', profile['codenames'])
Continue the code snippet: <|code_start|> testing-proposed-updates, stable-security, etc.) did really follow the archive policies for that. Profile key: none """ # XXX: This check does not contain code names yet. We need a global way # to retrieve and share current code names. suite = changes['Distribution'] query_user = False release_team_suites = ["testing-proposed-updates", "proposed-updates", "oldstable", "stable", "testing"] if suite in release_team_suites: msg = "Are you sure to upload to %s? Did you coordinate with the " \ "Release Team before your upload?" % (suite) error_msg = "Aborting upload to Release Team managed suite upon " \ "request" query_user = True security_team_suites = ["stable-security", "oldstable-security", "testing-security"] if suite in security_team_suites: msg = "Are you sure to upload to %s? Did you coordinate with the " \ "Security Team before your upload?" % (suite) error_msg = "Aborting upload to Security Team managed suite upon " \ "request" query_user = True if query_user: logger.trace("Querying the user for input. The upload targets a " "protected distribution") <|code_end|> . Use current file imports: import re from dput.core import logger from dput.util import load_config from dput.exceptions import HookException from dput.interface import BUTTON_NO and context (classes, functions, or code) from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/util.py # def load_config(config_class, config_name, # default=None, configs=None, config_cleanup=True): # """ # Load any dput configuration given a ``config_class`` (such as # ``hooks``), and a ``config_name`` (such as # ``lintian`` or ``tweet``). # # Optional kwargs: # # ``default`` is a default to return, in case the config file # isn't found. If this isn't provided, this function will # raise a :class:`dput.exceptions.NoSuchConfigError`. # # ``configs`` is a list of config files to check. When this # isn't provided, we check dput.core.CONFIG_LOCATIONS. # """ # # logger.debug("Loading configuration: %s %s" % ( # config_class, # config_name # )) # roots = [] # ret = {} # found = False # template_path = "%s/%s/%s.json" # locations = configs or dput.core.CONFIG_LOCATIONS # for config in locations: # logger.trace("Checking for configuration: %s" % (config)) # path = template_path % ( # config, # config_class, # config_name # ) # logger.trace("Checking - %s" % (path)) # try: # if os.path.exists(path): # found = True # roots.append(path) # ret.update(json.load(open(path, 'r'))) # except ValueError as e: # raise DputConfigurationError("syntax error in %s: %s" % ( # path, e # )) # # if not found: # if default is not None: # return default # # raise NoSuchConfigError("No such config: %s/%s" % ( # config_class, # config_name # )) # # if 'meta' in ret and ( # config_class != 'metas' or # ret['meta'] != config_name # ): # metainfo = load_config( # "metas", # ret['meta'], # default={} # ) # configs=configs) # # Erm, is this right? For some reason, I don't think it is. Meta # # handling is a hemorrhoid in my ass. Fuck it, it works. Ship it. # # -- PRT # for key in metainfo: # if not key in ret: # ret[key] = metainfo[key] # else: # logger.trace("Ignoring key %s for %s (%s)" % ( # key, # ret['meta'], # metainfo[key] # )) # # obj = ret # if config_cleanup: # obj = _config_cleanup(ret) # # if obj != {}: # return obj # # if default is not None: # return default # # logger.debug("Failed to load configuration %s" % (config_name)) # # nsce = NoSuchConfigError("No such configuration: '%s' in class '%s'" % ( # config_name, # config_class # )) # # nsce.config_class = config_class # nsce.config_name = config_name # nsce.checked = dput.core.CONFIG_LOCATIONS # raise nsce # # Path: dput/exceptions.py # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
if not interface.boolean('Protected Checker', msg, default=BUTTON_NO):
Given snippet: <|code_start|> Thrown if the ``gpg`` checker encounters an issue. """ pass def check_gpg_signature(changes, profile, interface): """ The ``gpg`` checker is a stock dput checker that checks packages intended for upload for a GPG signature. Profile key: ``gpg`` Example profile:: { "allowed_keys": [ "8F049AD82C92066C7352D28A7B585B30807C2A87", "B7982329" ] } ``allowed_keys`` is an optional entry which contains all the keys that may upload to this host. This can come in handy if you use more then one key to upload to more then one host. Use any length of the last N chars of the fingerprint. """ if "allow_unsigned_uploads" in profile: if profile['allow_unsigned_uploads']: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import subprocess import dput.changes from dput.core import logger from dput.exceptions import (ChangesFileException, HookException) and context: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr # # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass which might include code, classes, or functions. Output only the next line.
logger.info("Not checking GPG signature due to "
Next line prediction: <|code_start|> Profile key: ``gpg`` Example profile:: { "allowed_keys": [ "8F049AD82C92066C7352D28A7B585B30807C2A87", "B7982329" ] } ``allowed_keys`` is an optional entry which contains all the keys that may upload to this host. This can come in handy if you use more then one key to upload to more then one host. Use any length of the last N chars of the fingerprint. """ if "allow_unsigned_uploads" in profile: if profile['allow_unsigned_uploads']: logger.info("Not checking GPG signature due to " "allow_unsigned_uploads being set.") return gpg = {} if 'gpg' in profile: gpg = profile['gpg'] try: key = changes.validate_signature() <|code_end|> . Use current file imports: (import os import subprocess import dput.changes from dput.core import logger from dput.exceptions import (ChangesFileException, HookException)) and context including class names, function names, or small code snippets from other files: # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class ChangesFileException(DputError): # """ # Thrown when there's an error processing / verifying a .changes file # (most often via the :class:`dput.changes.Changes` object) # """ # # def __init__(self, message, gpg_stderr=None): # super(ChangesFileException, self).__init__(message) # self.gpg_stderr = gpg_stderr # # class HookException(DputError): # """ # Thrown when there's an error checking, or creating a checker. Usually # thrown by a checker invoked by :class:`dput.checker.run_hooks`. # """ # pass . Output only the next line.
except ChangesFileException as e:
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ Old dput config file implementation """ if sys.version_info[0] >= 3: else: <|code_end|> with the help of current file imports: import os import sys import configparser import ConfigParser as configparser import dput.core from dput.config import AbstractConfig from dput.core import logger from dput.exceptions import DputConfigurationError and context from other files: # Path: dput/config.py # class AbstractConfig(object): # """ # Abstract Configuration Object. All concrete configuration implementations # must subclass this object. # # Basically, all subclasses are bootstrapped in the same-ish way: # # * preload # * get_defaults # * set defaults # """ # __metaclass__ = abc.ABCMeta # # def __init__(self, configs): # self.preload(configs) # self.path = ' '.join(configs) # # @abc.abstractmethod # def set_replacements(self, replacements): # """ # """ # pass # XXX: DOCUMENT ME. # # @abc.abstractmethod # def get_defaults(self): # """ # Get the defaults that concrete configs get overlaid on top of. In # theory, this is set during the bootstrapping process. # """ # pass # # @abc.abstractmethod # def get_config(self, name, ignore_errors=False): # """ # Get a configuration block. What this means is generally up to the # implementation. However, please keep things sane and only return # sensual upload target blocks. # """ # pass # # @abc.abstractmethod # def get_config_blocks(self): # """ # Get a list of all configuration blocks. Strings in a list. # """ # pass # # @abc.abstractmethod # def preload(self, replacements): # """ # Load all configuration blocks. # """ # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass , which may contain function names, class names, or code. Output only the next line.
class DputCfConfig(AbstractConfig):
Given the following code snippet before the placeholder: <|code_start|># You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ Old dput config file implementation """ if sys.version_info[0] >= 3: else: class DputCfConfig(AbstractConfig): """ dput-old config file implementation. Subclass of a :class:`dput.config.AbstractConfig`. """ def preload(self, configs): """ See :meth:`dput.config.AbstractConfig.preload` """ parser = configparser.ConfigParser() if configs is None: configs = dput.core.DPUT_CONFIG_LOCATIONS for config in configs: if not os.access(config, os.R_OK): <|code_end|> , predict the next line using imports from the current file: import os import sys import configparser import ConfigParser as configparser import dput.core from dput.config import AbstractConfig from dput.core import logger from dput.exceptions import DputConfigurationError and context including class names, function names, and sometimes code from other files: # Path: dput/config.py # class AbstractConfig(object): # """ # Abstract Configuration Object. All concrete configuration implementations # must subclass this object. # # Basically, all subclasses are bootstrapped in the same-ish way: # # * preload # * get_defaults # * set defaults # """ # __metaclass__ = abc.ABCMeta # # def __init__(self, configs): # self.preload(configs) # self.path = ' '.join(configs) # # @abc.abstractmethod # def set_replacements(self, replacements): # """ # """ # pass # XXX: DOCUMENT ME. # # @abc.abstractmethod # def get_defaults(self): # """ # Get the defaults that concrete configs get overlaid on top of. In # theory, this is set during the bootstrapping process. # """ # pass # # @abc.abstractmethod # def get_config(self, name, ignore_errors=False): # """ # Get a configuration block. What this means is generally up to the # implementation. However, please keep things sane and only return # sensual upload target blocks. # """ # pass # # @abc.abstractmethod # def get_config_blocks(self): # """ # Get a list of all configuration blocks. Strings in a list. # """ # pass # # @abc.abstractmethod # def preload(self, replacements): # """ # Load all configuration blocks. # """ # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass . Output only the next line.
logger.debug("Skipping file %s: Not accessible" % (
Predict the next line after this snippet: <|code_start|>class DputCfConfig(AbstractConfig): """ dput-old config file implementation. Subclass of a :class:`dput.config.AbstractConfig`. """ def preload(self, configs): """ See :meth:`dput.config.AbstractConfig.preload` """ parser = configparser.ConfigParser() if configs is None: configs = dput.core.DPUT_CONFIG_LOCATIONS for config in configs: if not os.access(config, os.R_OK): logger.debug("Skipping file %s: Not accessible" % ( config )) continue try: logger.trace("Parsing %s" % (config)) parser.readfp(open(config, 'r')) except IOError as e: logger.warning("Skipping file %s: %s" % ( config, e )) continue except configparser.ParsingError as e: <|code_end|> using the current file's imports: import os import sys import configparser import ConfigParser as configparser import dput.core from dput.config import AbstractConfig from dput.core import logger from dput.exceptions import DputConfigurationError and any relevant context from other files: # Path: dput/config.py # class AbstractConfig(object): # """ # Abstract Configuration Object. All concrete configuration implementations # must subclass this object. # # Basically, all subclasses are bootstrapped in the same-ish way: # # * preload # * get_defaults # * set defaults # """ # __metaclass__ = abc.ABCMeta # # def __init__(self, configs): # self.preload(configs) # self.path = ' '.join(configs) # # @abc.abstractmethod # def set_replacements(self, replacements): # """ # """ # pass # XXX: DOCUMENT ME. # # @abc.abstractmethod # def get_defaults(self): # """ # Get the defaults that concrete configs get overlaid on top of. In # theory, this is set during the bootstrapping process. # """ # pass # # @abc.abstractmethod # def get_config(self, name, ignore_errors=False): # """ # Get a configuration block. What this means is generally up to the # implementation. However, please keep things sane and only return # sensual upload target blocks. # """ # pass # # @abc.abstractmethod # def get_config_blocks(self): # """ # Get a list of all configuration blocks. Strings in a list. # """ # pass # # @abc.abstractmethod # def preload(self, replacements): # """ # Load all configuration blocks. # """ # pass # # Path: dput/core.py # CONFIG_LOCATIONS = { # "/usr/share/dput-ng/": 30, # "/etc/dput.d/": 20, # os.path.expanduser("~/.dput.d"): 10, # "skel/": 100 # } # DPUT_CONFIG_LOCATIONS = { # "/etc/dput.cf": 15, # os.path.expanduser("~/.dput.cf"): 5 # } # SCHEMA_DIRS = [ # "/usr/share/dput-ng/schemas", # "skel/schemas" # ] # def _write_upload_log(logfile, full_log): # def _enable_debugging(level): # def mangle_sys(): # def maybe_print_traceback(debug_level, stack): # def get_local_username(): # # Path: dput/exceptions.py # class DputConfigurationError(DputError): # """ # Errors in the parsing or retrieving of configuration files should raise # an instance of this, or a subclass thereof. # """ # pass . Output only the next line.
raise DputConfigurationError("Error parsing file %s: %s" % (
Based on the snippet: <|code_start|># Copyright (c) 2012 dput authors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. class BreakTheArchiveCommandCommandError(DcutError): pass class BreakTheArchiveCommand(AbstractCommand): def __init__(self, interface): super(BreakTheArchiveCommand, self).__init__(interface) self.cmd_name = "break-the-archive" self.cmd_purpose = "break the archive (no, really)" def generate_commands_name(self, profile): <|code_end|> , predict the immediate next line with the help of imports: from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.commands.dm import generate_dak_commands_name from dput.interface import BUTTON_NO and context (classes, functions, sometimes code) from other files: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/commands/dm.py # def generate_dak_commands_name(profile): # # for debianqueued: $login-$timestamp.commands # # for dak: $login-$timestamp.dak-commands # the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time())) # # XXX: override w/ DEBEMAIL (if DEBEMAIL is @debian.org?) # logger.trace("Commands file will be named %s" % (the_file)) # return the_file # # Path: dput/interface.py # BUTTON_NO = "no" . Output only the next line.
return generate_dak_commands_name(profile)
Given snippet: <|code_start|> class BreakTheArchiveCommand(AbstractCommand): def __init__(self, interface): super(BreakTheArchiveCommand, self).__init__(interface) self.cmd_name = "break-the-archive" self.cmd_purpose = "break the archive (no, really)" def generate_commands_name(self, profile): return generate_dak_commands_name(profile) def register(self, parser, **kwargs): pass def produce(self, fh, args): fh.write("\n") # yes, this newline matters fh.write("Action: %s\n" % (self.cmd_name)) def validate(self, args): if args.force: return self.interface.message( 'WARNING: Dangerous command', "Break the archive is totally dangerous! Make sure you know " "what you are doing before proceeding." ) if not self.interface.boolean( 'Break the Archive command', "Do you really want to break the archive?", <|code_end|> , continue by predicting the next line. Consider current file imports: from dput.command import AbstractCommand from dput.exceptions import DcutError from dput.commands.dm import generate_dak_commands_name from dput.interface import BUTTON_NO and context: # Path: dput/command.py # class AbstractCommand(object): # """ # Abstract base class for all concrete dcut command implementations. # """ # # __metaclass__ = abc.ABCMeta # # def __init__(self, interface): # self.cmd_name = None # self.cmd_purpose = None # self.interface = interface # # @abc.abstractmethod # def register(self, parser, **kwargs): # pass # # @abc.abstractmethod # def produce(self, fh, args): # pass # # @abc.abstractmethod # def validate(self, args): # pass # # @abc.abstractmethod # def name_and_purpose(self): # pass # # @abc.abstractmethod # def generate_commands_name(self, profile): # pass # # Path: dput/exceptions.py # class DcutError(Exception): # pass # # Path: dput/commands/dm.py # def generate_dak_commands_name(profile): # # for debianqueued: $login-$timestamp.commands # # for dak: $login-$timestamp.dak-commands # the_file = "%s-%s.dak-commands" % (get_local_username(), int(time.time())) # # XXX: override w/ DEBEMAIL (if DEBEMAIL is @debian.org?) # logger.trace("Commands file will be named %s" % (the_file)) # return the_file # # Path: dput/interface.py # BUTTON_NO = "no" which might include code, classes, or functions. Output only the next line.
default=BUTTON_NO
Given snippet: <|code_start|> """ def __init__(self, filename=None, string=None): """ Object constructor. The object allows the user to specify **either**: #. a path to a *changes* file to parse #. a string with the *changes* file contents. :: a = Dsc(filename='/tmp/packagename_version.changes') b = Dsc(string='Source: packagename\\nMaintainer: ...') ``filename`` Path to *changes* file to parse. ``string`` *dsc* file in a string to parse. """ if (filename and string) or (not filename and not string): raise TypeError if filename: self._absfile = os.path.abspath(filename) self._data = deb822.Dsc(file(filename)) else: self._data = deb822.Dsc(string) if len(self._data) == 0: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import os.path from debian import deb822 from dput.exceptions import DscFileException and context: # Path: dput/exceptions.py # class DscFileException(DputError): # """ # Thrown when there's an error processing / verifying a .dsc file # (most often via the :class:`dput.changes.Dsc` object) # """ # pass which might include code, classes, or functions. Output only the next line.
raise DscFileException('Changes file could not be parsed.')
Given the code snippet: <|code_start|> return getattr(self, name) return self._raw.get(name, *args) def set(self, name: str, value: str) -> None: """ Set the value of a metadata element """ self._raw[name.lower()] = value def unset(self, name: str) -> None: """ Unset the value of a metadata element, if it exists, otherwise does nothing """ self._raw.pop(name.lower(), None) def set_durations(self, durations: Dict[str, int]) -> None: """ Set the Total: header from the given computed durations """ if len(durations) == 1: self.set("total", format_duration(durations[""])) else: lines = [] for tag, duration in sorted(durations.items()): if not tag: tag = "*" lines.append("{}: {}".format(tag, format_duration(duration))) self.set("total", "\n".join(lines)) <|code_end|> , generate the next line using the imports in this file: from typing import Optional, TextIO, List, Dict from collections import OrderedDict from .parse import Lines from .utils import format_duration import re import sys import inspect import email and context (functions, classes, or occasionally code) from other files: # Path: egtlib/parse.py # class Lines: # """ # Access a text file line by line, with line numbers # """ # def __init__(self, pathname: str, fd: Optional[TextIO] = None): # # File name being parsed # self.fname = pathname # # Current line being parsed # self.lineno = 0 # # Read the file, split in trimmed lines # self.lines: List[str] # if fd is None: # with open(self.fname, "rt") as fd: # self.lines = [x.rstrip() for x in fd] # else: # self.lines = [x.rstrip() for x in fd] # # def peek(self) -> Optional[str]: # """ # Return the next line to be parsed, without advancing the cursor. # Return None if we are at the end. # """ # if self.lineno < len(self.lines): # return self.lines[self.lineno] # else: # return None # # def next(self) -> str: # """ # Return the next line to be parsed, advancing the cursor. # Raise RuntimeError if we are at the end. # """ # if self.lineno >= len(self.lines): # raise RuntimeError("Lines.next() called at the end of the input") # res = self.lines[self.lineno] # self.lineno += 1 # return res # # def rest(self) -> Generator[str, None, None]: # """ # Generate all remaining lines # """ # yield from self.lines[self.lineno:] # # def discard(self) -> None: # """ # Just advance the cursor to the next line # """ # if self.lineno < len(self.lines): # self.lineno += 1 # # def skip_empty_lines(self) -> None: # while True: # line = self.peek() # if line is None: # break # if line: # break # self.discard() # # Path: egtlib/utils.py # def format_duration(mins: int, tabular: bool = False): # h = mins / 60 # m = mins % 60 # if tabular: # return "%3dh %02dm" % (h, m) # else: # if m: # return "%dh %dm" % (h, m) # else: # return "%dh" % h . Output only the next line.
def parse(self, lines: Lines) -> None:
Given snippet: <|code_start|> """ return name.lower() in self._raw def get(self, name: str, *args) -> str: """ Get a metadata element by name, optionally with a default. """ name = name.lower() if hasattr(self, name): return getattr(self, name) return self._raw.get(name, *args) def set(self, name: str, value: str) -> None: """ Set the value of a metadata element """ self._raw[name.lower()] = value def unset(self, name: str) -> None: """ Unset the value of a metadata element, if it exists, otherwise does nothing """ self._raw.pop(name.lower(), None) def set_durations(self, durations: Dict[str, int]) -> None: """ Set the Total: header from the given computed durations """ if len(durations) == 1: <|code_end|> , continue by predicting the next line. Consider current file imports: from typing import Optional, TextIO, List, Dict from collections import OrderedDict from .parse import Lines from .utils import format_duration import re import sys import inspect import email and context: # Path: egtlib/parse.py # class Lines: # """ # Access a text file line by line, with line numbers # """ # def __init__(self, pathname: str, fd: Optional[TextIO] = None): # # File name being parsed # self.fname = pathname # # Current line being parsed # self.lineno = 0 # # Read the file, split in trimmed lines # self.lines: List[str] # if fd is None: # with open(self.fname, "rt") as fd: # self.lines = [x.rstrip() for x in fd] # else: # self.lines = [x.rstrip() for x in fd] # # def peek(self) -> Optional[str]: # """ # Return the next line to be parsed, without advancing the cursor. # Return None if we are at the end. # """ # if self.lineno < len(self.lines): # return self.lines[self.lineno] # else: # return None # # def next(self) -> str: # """ # Return the next line to be parsed, advancing the cursor. # Raise RuntimeError if we are at the end. # """ # if self.lineno >= len(self.lines): # raise RuntimeError("Lines.next() called at the end of the input") # res = self.lines[self.lineno] # self.lineno += 1 # return res # # def rest(self) -> Generator[str, None, None]: # """ # Generate all remaining lines # """ # yield from self.lines[self.lineno:] # # def discard(self) -> None: # """ # Just advance the cursor to the next line # """ # if self.lineno < len(self.lines): # self.lineno += 1 # # def skip_empty_lines(self) -> None: # while True: # line = self.peek() # if line is None: # break # if line: # break # self.discard() # # Path: egtlib/utils.py # def format_duration(mins: int, tabular: bool = False): # h = mins / 60 # m = mins % 60 # if tabular: # return "%3dh %02dm" % (h, m) # else: # if m: # return "%dh %dm" % (h, m) # else: # return "%dh" % h which might include code, classes, or functions. Output only the next line.
self.set("total", format_duration(durations[""]))
Next line prediction: <|code_start|># coding: utf8 body_p = """Name: test 2016 15 march: 9:00-9:30 - wrote unit tests Write more unit tests """ body_p1 = """Name: p1 tags: foo, bar """ body_p2 = """Name: p2 tags: blubb, foo """ <|code_end|> . Use current file imports: (import unittest import os import egtlib import tarfile from unittest.mock import Mock, patch from io import StringIO from .utils import ProjectTestMixin from configparser import ConfigParser from egtlib.state import State from egtlib.commands import Completion) and context including class names, function names, or small code snippets from other files: # Path: test/utils.py # class ProjectTestMixin: # def setUp(self): # self.workdir = tempfile.TemporaryDirectory() # self.taskrc = os.path.join(self.workdir.name, ".taskrc") # with open(self.taskrc, "wt") as fd: # print("data.location={}".format(os.path.join(self.workdir.name, "tasks")), file=fd) # # def tearDown(self): # self.workdir.cleanup() # # Path: egtlib/state.py # class State: # """ # Cached information about known projects. # """ # # def __init__(self): # # Map project names to ProjectInfo objects # self.projects = {} # # def load(self, statedir: str = None) -> None: # if statedir is None: # statedir = self.get_state_dir() # # statefile = os.path.join(statedir, "state.json") # if os.path.exists(statefile): # # Load state from JSON file # with open(statefile, "rt") as fd: # state = json.load(fd) # self.projects = state["projects"] # return # # # TODO: remove support for legacy format # statefile = os.path.join(statedir, "state") # if os.path.exists(statefile): # # Load state from legacy .ini file # from configparser import RawConfigParser # cp = RawConfigParser() # cp.read([statefile]) # for secname in cp.sections(): # if secname.startswith("proj "): # name = secname.split(None, 1)[1] # fname = cp.get(secname, "fname") # self.projects[name] = {"fname": fname} # return # # @classmethod # def rescan(cls, dirs: List[str], statedir: str = None) -> None: # """ # Rebuild the state looking for files in the given directories. # # If statedir is None, the state is saved in the default state # directory. If it is not None, it is the directory in which state is to # be saved. # """ # if statedir is None: # statedir = cls.get_state_dir() # # # Read and detect duplicates # projects: Dict[str, dict] = {} # for dirname in dirs: # for fname in scan(dirname): # try: # p = Project.from_file(fname) # except Exception as e: # log.exception("%s: failed to parse: %s", fname, str(e)) # continue # if p.name in projects: # log.warn("%s: project %s already exists in %s: skipping", fname, p.name, projects[p.name]["fname"]) # else: # projects[p.name] = {"fname": p.abspath} # # # Log the difference with the old info # # old_projects = set(self.projects.keys()) # # for name, p in new_projects.items(): # # old_projects.discard(name) # # op = self.projects.get(name, None) # # if op is None: # # log.info("add %s: %s", name, p["fname"]) # # elif op["fname"] != p["fname"]: # # log.info("mv %s: %s -> %s", name, p["fname"], p["fname"]) # # else: # # log.info("hit %s: %s", name, p["fname"]) # # for name in old_projects: # # log.info("rm %s", name) # # # Commit the new project set # statefile = os.path.join(statedir, "state.json") # with atomic_writer(statefile, "wt") as fd: # json.dump({ # "projects": projects # }, fd, indent=1) # # # Clean up old version of state file # old_statefile = os.path.join(statedir, "state") # if os.path.exists(old_statefile): # log.warn("%s: legacy state file removed", old_statefile) # os.unlink(old_statefile) # # # TODO: scan statedir removing project-$NAME.json files for all # # projects that disappeared. # # log.debug("%s: new state written", statefile) # # @classmethod # def get_state_dir(cls) -> str: # return BaseDirectory.save_data_path('egt') # # Path: egtlib/commands.py # class Completion(Command): # """ # Tab completion support # """ # def main(self): # if not self.args.subcommand: # raise CommandError("Usage: egt completion {commands|projects|tags}") # if self.args.subcommand == "commands": # for c in Command.COMMANDS: # print(c.get_name()) # elif self.args.subcommand == "projects": # e = self.make_egt() # names = e.project_names # for n in names: # print(n) # elif self.args.subcommand == "tags": # e = self.make_egt() # res = set() # for p in e.projects: # res |= p.tags # for n in sorted(res): # print(n) # else: # raise CommandError("Usage: egt completion {commands|projects|tags}") # # @classmethod # def add_args(cls, subparser): # super().add_args(subparser) # subparser.add_argument("subcommand", nargs="?", default=None, help="command for which to provide completion") . Output only the next line.
class TestCommands(ProjectTestMixin, unittest.TestCase):
Predict the next line for this snippet: <|code_start|> basedir = os.path.dirname(__file__) if not basedir: basedir = os.getcwd() basedir = os.path.abspath(os.path.join(basedir, "..")) testdir = os.path.join(basedir, "test") class TestScan(unittest.TestCase): """ Test scan results """ def test_scan(self): <|code_end|> with the help of current file imports: import unittest import os import os.path from egtlib import scan and context from other files: # Path: egtlib/scan.py # def scan(top: str) -> Generator[str, None, None]: # """ # Generate the pathnames of all project files inside the given directory # """ # # inodes already visited # seen: Set[int] = set() # for root, dirs, files in os.walk(top, followlinks=True): # # Since we follow links, prevent loops by remembering which inodes we # # visited # st = os.stat(root) # if st.st_ino in seen: # dirs[:] = [] # continue # else: # seen.add(st.st_ino) # # # # # Check files # # # # is_leaf = False # has_dot_egt = False # has_egt = False # for f in files: # if f.endswith(".egt"): # # All .egt files are good # yield os.path.join(top, root, f) # if f == ".egt": # has_dot_egt = True # elif f == "egt": # has_egt = True # elif f in LEAF_FILE_MARKERS: # is_leaf = True # # # If 'egt' exists, there is no '.egt' and egt isn't a script, it is # # good # if has_egt and not has_dot_egt: # fname = os.path.join(top, root, 'egt') # if not is_script(fname): # yield fname # else: # log.debug("scan: skipping script: %s", fname) # # # # # Perform pruning of subdirs # # # if is_leaf: # log.debug("scan: prune dir %s", root) # dirs[:] = [] # else: # # Skip hidden dirs # dirs[:] = [d for d in dirs if not d.startswith(".")] , which may contain function names, class names, or code. Output only the next line.
res = sorted([x[len(testdir) + 10:] for x in scan(os.path.join(testdir, "testdata"))])
Predict the next line after this snippet: <|code_start|> while True: line = cls.process.stdout.readline() if line.strip(): print(line.strip()) if "Remote interface" in str(line): success = True break if not success: raise RuntimeError("Database failed to boot.") # Reset the credentials requests.post("http://localhost:7474/user/neo4j/authorization_token", json={ "password": "neo4j", "new_authorization_token": TEST_TOKEN }) @classmethod def tearDownClass(cls): """Kill the database process.""" cls.process.kill() def setUp(self): """Log in using neo4j/cits3200 and clear all data.""" super(TestImporterLoad, self).setUp() run_query("CYPHER 1.9 START n=node(*) DETACH DELETE n") def test_create_article(self): """4.5.5.0 Can create article.""" <|code_end|> using the current file's imports: import errno import json import mock import os import socket import shutil import subprocess import sys import requests from importer import load from nose_parameterized import parameterized from six.moves import StringIO from testtools import (ExpectedException, TestCase) from testtools.matchers import Equals and any relevant context from other files: # Path: importer/load.py # def generate_command_for_record(record): # def open_or_default(path, default): # def commands_from_data(data): # def main(argv=None): . Output only the next line.
run_commands(load.commands_from_data([ENTRY_VALUES]))
Next line prediction: <|code_start|> EXPECTED_ENTRY_VALUES = { "Author": ["fore_name last_name"], "pubDate": { "date": "2011-11-11", "components": { "Year": True, "Month": True, "Day": True } }, "reviseDate": { "date": "2012-11-11", "components": { "Year": True, "Month": True, "Day": True } }, "ISSN": "0", "country": "Australia" } class TestFileToElementTree(TestCase): """Test conversion of a file to an element tree.""" def test_convert(self): """4.5.3.1 File can be converted to element tree.""" stream = StringIO("<html></html>") <|code_end|> . Use current file imports: (import sys from importer import parsexml from nose_parameterized import parameterized from six.moves import StringIO from testtools import (ExpectedException, TestCase) from testtools.matchers import (Contains, Equals, Is) from xml.etree import ElementTree) and context including class names, function names, or small code snippets from other files: # Path: importer/parsexml.py # def file_to_element_tree(path): # def parse_selected_sections(object, *args): # def _text_or_none(element): # def __init__(self, entry, valid_combinations): # def __str__(self): # def expect_section_combinations(entry, object, combinations): # def expect_valid_date_combinations(entry, object): # def sections_to_date_entry(sections): # def sanitise_string(string): # def sanitise_field_values(structure): # def warning(filename, msg): # def get_author_name(author_element): # def parse_element_tree(tree, filename=None): # def main(argv=None): # class InvalidCombinationExpection(Exception): . Output only the next line.
parsexml.file_to_element_tree(stream)
Next line prediction: <|code_start|> n_requested_samples, ln_prior=None, init_batch_size=None, growth_factor=128, n_linear_samples=1): n_total_samples = len(prior_samples_batch) # The "magic numbers" below control how fast the iterative batches grow # in size, and the maximum number of iterations maxiter = 128 # MAGIC NUMBER safety_factor = 1 # MAGIC NUMBER if init_batch_size is None: n_process = growth_factor * n_requested_samples # MAGIC NUMBER else: n_process = init_batch_size if n_process > n_total_samples: raise ValueError("Prior sample library not big enough! For " "iterative sampling, you have to have at least " "growth_factor * n_requested_samples = " f"{growth_factor * n_requested_samples} samples in " "the prior samples cache file. You have, or have " f"limited to, {n_total_samples} samples.") all_idx = np.arange(0, n_total_samples, 1) all_marg_lls = np.array([]) start_idx = 0 for i in range(maxiter): <|code_end|> . Use current file imports: (import numpy as np from .logging import logger from .samples import JokerSamples) and context including class names, function names, or small code snippets from other files: # Path: thejoker/logging.py # class JokerHandler(StreamHandler): # class JokerLogger(logging.getLoggerClass()): # def emit(self, record): # def _set_defaults(self): . Output only the next line.
logger.log(1, f"iteration {i}, computing {n_process} likelihoods")
Using the snippet: <|code_start|> "object's table datatype do not match. " f"{existing_header['datatype']} vs. {this_header['datatype']}") # If we got here, we can now try to append: current_size = len(output_group[name]) output_group[name].resize((current_size + len(table), )) output_group[name][current_size:] = table.as_array() def inferencedata_to_samples(joker_prior, inferencedata, data, prune_divergences=True): """ Create a ``JokerSamples`` instance from an arviz object. Parameters ---------- joker_prior : `thejoker.JokerPrior` inferencedata : `arviz.InferenceData` data : `thejoker.RVData` prune_divergences : bool (optional) """ if hasattr(inferencedata, 'posterior'): posterior = inferencedata.posterior else: posterior = inferencedata inferencedata = None <|code_end|> , determine the next line of code. You have imports: import os import warnings import h5py import exoplanet.units as xu import pymc3 as pm import exoplanet.units as xu from astropy.table.meta import get_header_from_yaml, get_yaml_from_table from astropy.io.misc.hdf5 import _encode_mixins, meta_path from astropy.utils.exceptions import AstropyUserWarning from astropy.utils import metadata from thejoker.thejoker import validate_prepare_data from astropy.table import meta from thejoker.samples import JokerSamples from thejoker.samples import JokerSamples and context (class names, function names, or code) available: # Path: thejoker/thejoker.py # class TheJoker: # def __init__(self, prior, pool=None, random_state=None, # tempfile_path=None): # def tempfile_path(self): # def _make_joker_helper(self, data): # def marginal_ln_likelihood(self, data, prior_samples, n_batches=None, # in_memory=False): # def rejection_sample(self, data, prior_samples, # n_prior_samples=None, # max_posterior_samples=None, # n_linear_samples=1, # return_logprobs=False, # return_all_logprobs=False, # n_batches=None, # randomize_prior_order=False, # in_memory=False): # def iterative_rejection_sample(self, data, prior_samples, # n_requested_samples, # max_prior_samples=None, # n_linear_samples=1, # return_logprobs=False, # n_batches=None, # randomize_prior_order=False, # init_batch_size=None, # growth_factor=128, # in_memory=False): # def setup_mcmc(self, data, joker_samples, model=None, custom_func=None): # def trace_to_samples(self, trace, data, names=None): # N = prior_samples # M = get_trend_design_matrix(data, ids, self.prior.poly_trend) . Output only the next line.
data, *_ = validate_prepare_data(data,
Using the snippet: <|code_start|> if self.rv_err.ndim == 1: self._has_cov = False elif self.rv_err.ndim == 2: self._has_cov = True if (self.rv_err.shape != (self.rv.size, self.rv.size) and self.rv_err.shape != (self.rv.size, )): raise ValueError(f"Invalid shape for input RV error " f"{self.rv_err.shape}. Should either be " f"({self.rv.size},) or " f"({self.rv.size}, {self.rv.size})") # make sure shapes are consistent if self._t_bmjd.shape != self.rv.shape: raise ValueError(f"Shape of input times and RVs must be consistent" f" ({self._t_bmjd.shape} vs {self.rv.shape})") if clean: # filter out NAN or INF data points idx = (np.isfinite(self._t_bmjd) & np.isfinite(self.rv)) if self._has_cov: idx &= np.isfinite(self.rv_err).all(axis=0) else: idx &= np.isfinite(self.rv_err) n_filter = len(self.rv) - idx.sum() if n_filter > 0: <|code_end|> , determine the next line of code. You have imports: import warnings import astropy.units as u import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.time import Time from astropy.utils.decorators import deprecated_renamed_argument from .logging import logger from .data_helpers import guess_time_format from .exceptions import TheJokerDeprecationWarning from fuzzywuzzy import process from astropy.timeseries import TimeSeries from astropy.timeseries import TimeSeries and context (class names, function names, or code) available: # Path: thejoker/logging.py # class JokerHandler(StreamHandler): # class JokerLogger(logging.getLoggerClass()): # def emit(self, record): # def _set_defaults(self): # # Path: thejoker/data_helpers.py # def guess_time_format(time_val): # """Guess the `astropy.time.Time` format from the input value(s). # # Parameters # ---------- # time_val : float, array_like # The value or values to guess the format from. # # Returns # ------- # format : str # The `astropy.time.Time` format string, guessed from the value. # # """ # arr = np.array(time_val) # # # Only support float or int times # if arr.dtype.char not in ['f', 'd', 'i', 'l']: # raise NotImplementedError("We can only try to guess " # "the time format with a numeric " # "time value. Sorry about that!") # # # HACK: magic number! # dt_thresh = 50*u.year # # jd_check = np.abs(arr - Time('2010-01-01').jd) * u.day < dt_thresh # jd_check = np.all(jd_check) # # mjd_check = np.abs(arr - Time('2010-01-01').mjd) * u.day < dt_thresh # mjd_check = np.all(mjd_check) # # err_msg = ("Unable to guess time format! Initialize with an " # "explicit astropy.time.Time() object instead.") # if jd_check and mjd_check: # raise ValueError(err_msg) # # elif jd_check: # return 'jd' # # elif mjd_check: # return 'mjd' # # else: # raise ValueError(err_msg) # # Path: thejoker/exceptions.py # class TheJokerDeprecationWarning(Warning): # """Because standard deprecation warnings are ignored!""" # pass . Output only the next line.
logger.info(f"Filtering {n_filter} NaN/Inf data points")
Using the snippet: <|code_start|> if time_kwargs is None: time_kwargs = dict() # First check for any of the valid astropy Time format names: # FUTURETODO: right now we only support jd and mjd (and b-preceding) for fmt in ['jd', 'mjd']: if fmt in lwr_cols: time_kwargs['format'] = time_kwargs.get('format', fmt) time_data = tbl[lwr_to_col[fmt]] break elif f'b{fmt}' in lwr_cols: time_kwargs['format'] = time_kwargs.get('format', fmt) time_kwargs['scale'] = time_kwargs.get('scale', 'tcb') time_data = tbl[lwr_to_col[f'b{fmt}']] _scale_specified = True break time_info_msg = ("Assuming time scale is '{}' because it was not " "specified. To change this, pass in: " "time_kwargs=dict(scale='...') with whatever time " "scale your data are in.") _fmt_specified = 'format' in time_kwargs _scale_specified = 'scale' in time_kwargs # check colnames for "t" or "time" for name in ['t', 'time']: if name in lwr_cols: time_data = tbl[lwr_to_col[name]] time_kwargs['format'] = time_kwargs.get( <|code_end|> , determine the next line of code. You have imports: import warnings import astropy.units as u import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.time import Time from astropy.utils.decorators import deprecated_renamed_argument from .logging import logger from .data_helpers import guess_time_format from .exceptions import TheJokerDeprecationWarning from fuzzywuzzy import process from astropy.timeseries import TimeSeries from astropy.timeseries import TimeSeries and context (class names, function names, or code) available: # Path: thejoker/logging.py # class JokerHandler(StreamHandler): # class JokerLogger(logging.getLoggerClass()): # def emit(self, record): # def _set_defaults(self): # # Path: thejoker/data_helpers.py # def guess_time_format(time_val): # """Guess the `astropy.time.Time` format from the input value(s). # # Parameters # ---------- # time_val : float, array_like # The value or values to guess the format from. # # Returns # ------- # format : str # The `astropy.time.Time` format string, guessed from the value. # # """ # arr = np.array(time_val) # # # Only support float or int times # if arr.dtype.char not in ['f', 'd', 'i', 'l']: # raise NotImplementedError("We can only try to guess " # "the time format with a numeric " # "time value. Sorry about that!") # # # HACK: magic number! # dt_thresh = 50*u.year # # jd_check = np.abs(arr - Time('2010-01-01').jd) * u.day < dt_thresh # jd_check = np.all(jd_check) # # mjd_check = np.abs(arr - Time('2010-01-01').mjd) * u.day < dt_thresh # mjd_check = np.all(mjd_check) # # err_msg = ("Unable to guess time format! Initialize with an " # "explicit astropy.time.Time() object instead.") # if jd_check and mjd_check: # raise ValueError(err_msg) # # elif jd_check: # return 'jd' # # elif mjd_check: # return 'mjd' # # else: # raise ValueError(err_msg) # # Path: thejoker/exceptions.py # class TheJokerDeprecationWarning(Warning): # """Because standard deprecation warnings are ignored!""" # pass . Output only the next line.
'format', guess_time_format(tbl[lwr_to_col[name]]))
Given the following code snippet before the placeholder: <|code_start|># Third-party # Project __all__ = ['RVData'] class RVData: """ Time-domain radial velocity measurements for a single target. Parameters ---------- t : `~astropy.time.Time`, array_like Array of measurement times. Either as an astropy `~astropy.time.Time` object, or as a numpy array of Barycentric MJD (BMJD) values. rv : `~astropy.units.Quantity` [speed] Radial velocity (RV) measurements. rv_err : `~astropy.units.Quantity` [speed] (optional) If 1D, assumed to be the standard deviation for each RV measurement. If this input is 2-dimensional, this is assumed to be a covariance matrix for all data points. t_ref : numeric (optional) [day] A reference time. Default is to use the minimum time in barycentric MJD (days). Set to ``False`` to disable subtracting the reference time. clean : bool (optional) Filter out any NaN or Inf data points. """ @deprecated_renamed_argument('t0', 't_ref', since='v1.2', <|code_end|> , predict the next line using imports from the current file: import warnings import astropy.units as u import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.time import Time from astropy.utils.decorators import deprecated_renamed_argument from .logging import logger from .data_helpers import guess_time_format from .exceptions import TheJokerDeprecationWarning from fuzzywuzzy import process from astropy.timeseries import TimeSeries from astropy.timeseries import TimeSeries and context including class names, function names, and sometimes code from other files: # Path: thejoker/logging.py # class JokerHandler(StreamHandler): # class JokerLogger(logging.getLoggerClass()): # def emit(self, record): # def _set_defaults(self): # # Path: thejoker/data_helpers.py # def guess_time_format(time_val): # """Guess the `astropy.time.Time` format from the input value(s). # # Parameters # ---------- # time_val : float, array_like # The value or values to guess the format from. # # Returns # ------- # format : str # The `astropy.time.Time` format string, guessed from the value. # # """ # arr = np.array(time_val) # # # Only support float or int times # if arr.dtype.char not in ['f', 'd', 'i', 'l']: # raise NotImplementedError("We can only try to guess " # "the time format with a numeric " # "time value. Sorry about that!") # # # HACK: magic number! # dt_thresh = 50*u.year # # jd_check = np.abs(arr - Time('2010-01-01').jd) * u.day < dt_thresh # jd_check = np.all(jd_check) # # mjd_check = np.abs(arr - Time('2010-01-01').mjd) * u.day < dt_thresh # mjd_check = np.all(mjd_check) # # err_msg = ("Unable to guess time format! Initialize with an " # "explicit astropy.time.Time() object instead.") # if jd_check and mjd_check: # raise ValueError(err_msg) # # elif jd_check: # return 'jd' # # elif mjd_check: # return 'mjd' # # else: # raise ValueError(err_msg) # # Path: thejoker/exceptions.py # class TheJokerDeprecationWarning(Warning): # """Because standard deprecation warnings are ignored!""" # pass . Output only the next line.
warning_type=TheJokerDeprecationWarning)
Based on the snippet: <|code_start|> err_msg = ("Unable to guess time format! Initialize with an " "explicit astropy.time.Time() object instead.") if jd_check and mjd_check: raise ValueError(err_msg) elif jd_check: return 'jd' elif mjd_check: return 'mjd' else: raise ValueError(err_msg) def validate_prepare_data(data, poly_trend, n_offsets): """Internal function. Used to take an input ``RVData`` instance, or a list/dict of ``RVData`` instances, and produce concatenated time, RV, and error arrays, along with a consistent t0. """ if isinstance(data, RVData): # single instance if n_offsets != 0: raise ValueError("If sampling over velocity offsets between data " "sources, you must pass in multiple data sources." " To do this, pass in a list of RVData instances " "or a dictionary with RVData instances as values." ) <|code_end|> , predict the immediate next line with the help of imports: from astropy.time import Time from .likelihood_helpers import get_trend_design_matrix from .data import RVData import astropy.units as u import numpy as np and context (classes, functions, sometimes code) from other files: # Path: thejoker/likelihood_helpers.py # def get_trend_design_matrix(data, ids, poly_trend): # """ # Construct the full design matrix for linear parameters, without the K column # """ # # Combine design matrix for constant term, which may contain columns for # # sampling over v0 offsets, with the rest of the long-term trend columns # const_M = get_constant_term_design_matrix(data, ids) # dt = data._t_bmjd - data._t_ref_bmjd # trend_M = np.vander(dt, N=poly_trend, increasing=True)[:, 1:] # return np.hstack((const_M, trend_M)) . Output only the next line.
trend_M = get_trend_design_matrix(data, None, poly_trend)
Using the snippet: <|code_start|> The number of conversations created in this interval. """ start_time = proto.Field( proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) conversation_count = proto.Field(proto.INT32, number=2,) interval_duration = proto.Field( proto.MESSAGE, number=1, message=duration_pb2.Duration, ) points = proto.RepeatedField( proto.MESSAGE, number=2, message="CalculateStatsResponse.TimeSeries.Interval", ) average_duration = proto.Field( proto.MESSAGE, number=1, message=duration_pb2.Duration, ) average_turn_count = proto.Field(proto.INT32, number=2,) conversation_count = proto.Field(proto.INT32, number=3,) smart_highlighter_matches = proto.MapField(proto.STRING, proto.INT32, number=4,) custom_highlighter_matches = proto.MapField(proto.STRING, proto.INT32, number=5,) issue_matches = proto.MapField(proto.STRING, proto.INT32, number=6,) issue_matches_stats = proto.MapField( proto.STRING, proto.MESSAGE, number=8, <|code_end|> , determine the next line of code. You have imports: import proto # type: ignore from google.cloud.contact_center_insights_v1.types import resources from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore and context (class names, function names, or code) available: # Path: google/cloud/contact_center_insights_v1/types/resources.py # class Conversation(proto.Message): # class Medium(proto.Enum): # class CallMetadata(proto.Message): # class Transcript(proto.Message): # class TranscriptSegment(proto.Message): # class WordInfo(proto.Message): # class DialogflowSegmentMetadata(proto.Message): # class Analysis(proto.Message): # class ConversationDataSource(proto.Message): # class GcsSource(proto.Message): # class DialogflowSource(proto.Message): # class AnalysisResult(proto.Message): # class CallAnalysisMetadata(proto.Message): # class IssueModelResult(proto.Message): # class ConversationLevelSentiment(proto.Message): # class IssueAssignment(proto.Message): # class CallAnnotation(proto.Message): # class AnnotationBoundary(proto.Message): # class Entity(proto.Message): # class Type(proto.Enum): # class Intent(proto.Message): # class PhraseMatchData(proto.Message): # class DialogflowIntent(proto.Message): # class InterruptionData(proto.Message): # class SilenceData(proto.Message): # class HoldData(proto.Message): # class EntityMentionData(proto.Message): # class MentionType(proto.Enum): # class IntentMatchData(proto.Message): # class SentimentData(proto.Message): # class IssueModel(proto.Message): # class State(proto.Enum): # class InputDataConfig(proto.Message): # class Issue(proto.Message): # class IssueModelLabelStats(proto.Message): # class IssueStats(proto.Message): # class PhraseMatcher(proto.Message): # class PhraseMatcherType(proto.Enum): # class PhraseMatchRuleGroup(proto.Message): # class PhraseMatchRuleGroupType(proto.Enum): # class PhraseMatchRule(proto.Message): # class PhraseMatchRuleConfig(proto.Message): # class ExactMatchConfig(proto.Message): # class Settings(proto.Message): # class AnalysisConfig(proto.Message): # class RuntimeAnnotation(proto.Message): # class AnswerFeedback(proto.Message): # class CorrectnessLevel(proto.Enum): # class ArticleSuggestionData(proto.Message): # class FaqAnswerData(proto.Message): # class SmartReplyData(proto.Message): # class SmartComposeSuggestionData(proto.Message): # class DialogflowInteractionData(proto.Message): # class ConversationParticipant(proto.Message): # class Role(proto.Enum): # class View(proto.Message): # MEDIUM_UNSPECIFIED = 0 # PHONE_CALL = 1 # CHAT = 2 # TYPE_UNSPECIFIED = 0 # PERSON = 1 # LOCATION = 2 # ORGANIZATION = 3 # EVENT = 4 # WORK_OF_ART = 5 # CONSUMER_GOOD = 6 # OTHER = 7 # PHONE_NUMBER = 9 # ADDRESS = 10 # DATE = 11 # NUMBER = 12 # PRICE = 13 # MENTION_TYPE_UNSPECIFIED = 0 # PROPER = 1 # COMMON = 2 # STATE_UNSPECIFIED = 0 # UNDEPLOYED = 1 # DEPLOYING = 2 # DEPLOYED = 3 # UNDEPLOYING = 4 # DELETING = 5 # PHRASE_MATCHER_TYPE_UNSPECIFIED = 0 # ALL_OF = 1 # ANY_OF = 2 # PHRASE_MATCH_RULE_GROUP_TYPE_UNSPECIFIED = 0 # ALL_OF = 1 # ANY_OF = 2 # CORRECTNESS_LEVEL_UNSPECIFIED = 0 # NOT_CORRECT = 1 # PARTIALLY_CORRECT = 2 # FULLY_CORRECT = 3 # ROLE_UNSPECIFIED = 0 # HUMAN_AGENT = 1 # AUTOMATED_AGENT = 2 # END_USER = 3 # ANY_AGENT = 4 . Output only the next line.
message=resources.IssueModelLabelStats.IssueStats,
Predict the next line after this snippet: <|code_start|> probs = scores_to_probs(scores) assert_less(abs(sum(probs) - 1), 1e-6) for prob in probs: assert_less_equal(0, prob) assert_less_equal(prob, 1) def test_multinomial_goodness_of_fit(): for dim in range(2, 20): yield _test_multinomial_goodness_of_fit, dim def _test_multinomial_goodness_of_fit(dim): seed_all(0) thresh = 1e-3 sample_count = int(1e5) probs = numpy.random.dirichlet([1] * dim) counts = numpy.random.multinomial(sample_count, probs) p_good = multinomial_goodness_of_fit(probs, counts, sample_count) assert_greater(p_good, thresh) unif_counts = numpy.random.multinomial(sample_count, [1. / dim] * dim) p_bad = multinomial_goodness_of_fit(probs, unif_counts, sample_count) assert_less(p_bad, thresh) def test_bin_samples(): samples = range(6) numpy.random.shuffle(samples) <|code_end|> using the current file's imports: import numpy from nose.tools import ( assert_less, assert_less_equal, assert_greater, assert_list_equal, ) from distributions.util import ( scores_to_probs, bin_samples, multinomial_goodness_of_fit, ) from distributions.tests.util import seed_all and any relevant context from other files: # Path: distributions/util.py # def scores_to_probs(scores): # scores = numpy.array(scores) # scores -= scores.max() # probs = numpy.exp(scores, out=scores) # probs /= probs.sum() # return probs # # def bin_samples(samples, k=10, support=[]): # """ # Bins a collection of univariate samples into k bins of equal # fill via the empirical cdf, to be used in goodness of fit testing. # # Returns # counts : array k x 1 # bin_ranges : arrary k x 2 # # each count is the number of samples in [bin_min, bin_max) # except for the last bin which is [bin_min, bin_max] # # list partitioning algorithm adapted from Mark Dickinson: # http://stackoverflow.com/questions/2659900 # """ # samples = sorted(samples) # # N = len(samples) # q, r = divmod(N, k) # #we need to distribute the remainder relatively evenly # #tests will be inaccurate if we have small bins at the end # indices = [i * q + min(r, i) for i in range(k + 1)] # bins = [samples[indices[i]: indices[i + 1]] for i in range(k)] # bin_ranges = [] # counts = [] # for i in range(k): # bin_min = bins[i][0] # try: # bin_max = bins[i + 1][0] # except IndexError: # bin_max = bins[i][-1] # bin_ranges.append([bin_min, bin_max]) # counts.append(len(bins[i])) # if support: # bin_ranges[0][0] = support[0] # bin_ranges[-1][1] = support[1] # return numpy.array(counts), numpy.array(bin_ranges) # # def multinomial_goodness_of_fit( # probs, # counts, # total_count, # truncated=False, # plot=False): # """ # Pearson's chi^2 test, on possibly truncated data. # http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test # # Returns: # p-value of truncated multinomial sample. # """ # assert len(probs) == len(counts) # assert truncated or total_count == sum(counts) # chi_squared = 0 # dof = 0 # if plot: # print_histogram(probs, counts) # for p, c in zip(probs, counts): # if p == 1: # return 1 if c == total_count else 0 # assert p < 1, 'bad probability: %g' % p # if p > 0: # mean = total_count * p # variance = total_count * p * (1 - p) # assert variance > 1,\ # 'WARNING goodness of fit is inaccurate; use more samples' # chi_squared += (c - mean) ** 2 / variance # dof += 1 # else: # print 'WARNING zero probability in goodness-of-fit test' # if c > 0: # return float('inf') # # if not truncated: # dof -= 1 # # survival = scipy.stats.chi2.sf(chi_squared, dof) # return survival # # Path: distributions/tests/util.py # def seed_all(s): # import distributions.dbg.random # distributions.dbg.random.seed(s) # try: # import distributions.hp.random # distributions.hp.random.seed(s) # except ImportError: # pass . Output only the next line.
counts, bounds = bin_samples(samples, 2)
Using the snippet: <|code_start|># INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def test_scores_to_probs(): scores = [-10000, 10000, 10001, 9999, 0, 5, 6, 6, 7] probs = scores_to_probs(scores) assert_less(abs(sum(probs) - 1), 1e-6) for prob in probs: assert_less_equal(0, prob) assert_less_equal(prob, 1) def test_multinomial_goodness_of_fit(): for dim in range(2, 20): yield _test_multinomial_goodness_of_fit, dim def _test_multinomial_goodness_of_fit(dim): seed_all(0) thresh = 1e-3 sample_count = int(1e5) probs = numpy.random.dirichlet([1] * dim) counts = numpy.random.multinomial(sample_count, probs) <|code_end|> , determine the next line of code. You have imports: import numpy from nose.tools import ( assert_less, assert_less_equal, assert_greater, assert_list_equal, ) from distributions.util import ( scores_to_probs, bin_samples, multinomial_goodness_of_fit, ) from distributions.tests.util import seed_all and context (class names, function names, or code) available: # Path: distributions/util.py # def scores_to_probs(scores): # scores = numpy.array(scores) # scores -= scores.max() # probs = numpy.exp(scores, out=scores) # probs /= probs.sum() # return probs # # def bin_samples(samples, k=10, support=[]): # """ # Bins a collection of univariate samples into k bins of equal # fill via the empirical cdf, to be used in goodness of fit testing. # # Returns # counts : array k x 1 # bin_ranges : arrary k x 2 # # each count is the number of samples in [bin_min, bin_max) # except for the last bin which is [bin_min, bin_max] # # list partitioning algorithm adapted from Mark Dickinson: # http://stackoverflow.com/questions/2659900 # """ # samples = sorted(samples) # # N = len(samples) # q, r = divmod(N, k) # #we need to distribute the remainder relatively evenly # #tests will be inaccurate if we have small bins at the end # indices = [i * q + min(r, i) for i in range(k + 1)] # bins = [samples[indices[i]: indices[i + 1]] for i in range(k)] # bin_ranges = [] # counts = [] # for i in range(k): # bin_min = bins[i][0] # try: # bin_max = bins[i + 1][0] # except IndexError: # bin_max = bins[i][-1] # bin_ranges.append([bin_min, bin_max]) # counts.append(len(bins[i])) # if support: # bin_ranges[0][0] = support[0] # bin_ranges[-1][1] = support[1] # return numpy.array(counts), numpy.array(bin_ranges) # # def multinomial_goodness_of_fit( # probs, # counts, # total_count, # truncated=False, # plot=False): # """ # Pearson's chi^2 test, on possibly truncated data. # http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test # # Returns: # p-value of truncated multinomial sample. # """ # assert len(probs) == len(counts) # assert truncated or total_count == sum(counts) # chi_squared = 0 # dof = 0 # if plot: # print_histogram(probs, counts) # for p, c in zip(probs, counts): # if p == 1: # return 1 if c == total_count else 0 # assert p < 1, 'bad probability: %g' % p # if p > 0: # mean = total_count * p # variance = total_count * p * (1 - p) # assert variance > 1,\ # 'WARNING goodness of fit is inaccurate; use more samples' # chi_squared += (c - mean) ** 2 / variance # dof += 1 # else: # print 'WARNING zero probability in goodness-of-fit test' # if c > 0: # return float('inf') # # if not truncated: # dof -= 1 # # survival = scipy.stats.chi2.sf(chi_squared, dof) # return survival # # Path: distributions/tests/util.py # def seed_all(s): # import distributions.dbg.random # distributions.dbg.random.seed(s) # try: # import distributions.hp.random # distributions.hp.random.seed(s) # except ImportError: # pass . Output only the next line.
p_good = multinomial_goodness_of_fit(probs, counts, sample_count)
Using the snippet: <|code_start|># # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def test_scores_to_probs(): scores = [-10000, 10000, 10001, 9999, 0, 5, 6, 6, 7] probs = scores_to_probs(scores) assert_less(abs(sum(probs) - 1), 1e-6) for prob in probs: assert_less_equal(0, prob) assert_less_equal(prob, 1) def test_multinomial_goodness_of_fit(): for dim in range(2, 20): yield _test_multinomial_goodness_of_fit, dim def _test_multinomial_goodness_of_fit(dim): <|code_end|> , determine the next line of code. You have imports: import numpy from nose.tools import ( assert_less, assert_less_equal, assert_greater, assert_list_equal, ) from distributions.util import ( scores_to_probs, bin_samples, multinomial_goodness_of_fit, ) from distributions.tests.util import seed_all and context (class names, function names, or code) available: # Path: distributions/util.py # def scores_to_probs(scores): # scores = numpy.array(scores) # scores -= scores.max() # probs = numpy.exp(scores, out=scores) # probs /= probs.sum() # return probs # # def bin_samples(samples, k=10, support=[]): # """ # Bins a collection of univariate samples into k bins of equal # fill via the empirical cdf, to be used in goodness of fit testing. # # Returns # counts : array k x 1 # bin_ranges : arrary k x 2 # # each count is the number of samples in [bin_min, bin_max) # except for the last bin which is [bin_min, bin_max] # # list partitioning algorithm adapted from Mark Dickinson: # http://stackoverflow.com/questions/2659900 # """ # samples = sorted(samples) # # N = len(samples) # q, r = divmod(N, k) # #we need to distribute the remainder relatively evenly # #tests will be inaccurate if we have small bins at the end # indices = [i * q + min(r, i) for i in range(k + 1)] # bins = [samples[indices[i]: indices[i + 1]] for i in range(k)] # bin_ranges = [] # counts = [] # for i in range(k): # bin_min = bins[i][0] # try: # bin_max = bins[i + 1][0] # except IndexError: # bin_max = bins[i][-1] # bin_ranges.append([bin_min, bin_max]) # counts.append(len(bins[i])) # if support: # bin_ranges[0][0] = support[0] # bin_ranges[-1][1] = support[1] # return numpy.array(counts), numpy.array(bin_ranges) # # def multinomial_goodness_of_fit( # probs, # counts, # total_count, # truncated=False, # plot=False): # """ # Pearson's chi^2 test, on possibly truncated data. # http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test # # Returns: # p-value of truncated multinomial sample. # """ # assert len(probs) == len(counts) # assert truncated or total_count == sum(counts) # chi_squared = 0 # dof = 0 # if plot: # print_histogram(probs, counts) # for p, c in zip(probs, counts): # if p == 1: # return 1 if c == total_count else 0 # assert p < 1, 'bad probability: %g' % p # if p > 0: # mean = total_count * p # variance = total_count * p * (1 - p) # assert variance > 1,\ # 'WARNING goodness of fit is inaccurate; use more samples' # chi_squared += (c - mean) ** 2 / variance # dof += 1 # else: # print 'WARNING zero probability in goodness-of-fit test' # if c > 0: # return float('inf') # # if not truncated: # dof -= 1 # # survival = scipy.stats.chi2.sf(chi_squared, dof) # return survival # # Path: distributions/tests/util.py # def seed_all(s): # import distributions.dbg.random # distributions.dbg.random.seed(s) # try: # import distributions.hp.random # distributions.hp.random.seed(s) # except ImportError: # pass . Output only the next line.
seed_all(0)
Given the code snippet: <|code_start|> score_empty = self.score_add_value(0, bogus, size) if len(counts) == 0 or counts[-1] != 0: counts.append(0) scores.append(score_empty) else: scores[-1] = score_empty assign = sample_discrete_log(scores) counts[assign] += 1 size += 1 scores[assign] = self.score_add_value(counts[assign], bogus, bogus) assignments.append(assign) return assignments #------------------------------------------------------------------------- # Scoring def score_counts(self, counts): ''' Return log probability of data, given sufficient statistics of a partial assignment vector [X_0,...,X_{n-1}] log P[ X_0=x_0, ..., X_{n-1}=x_{n-1} ] ''' score = 0.0 sample_size = 0 for count in counts: sample_size += count if count > 1: <|code_end|> , generate the next line using the imports in this file: from distributions.dbg.special import log from distributions.dbg.random import sample_discrete_log from distributions.mixins import SharedIoMixin and context (functions, classes, or occasionally code) from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_discrete_log(scores): # probs = scores_to_probs(scores) # return sample_discrete(probs, total=1.0) . Output only the next line.
score += count * log(count)
Predict the next line after this snippet: <|code_start|> #------------------------------------------------------------------------- # Sampling def sample_assignments(self, sample_size): ''' Sample partial assignment vector [X_0, ..., X_{n-1}] where n = sample_size <= N = dataset_size. ''' assert sample_size <= self.dataset_size assignments = [] counts = [] scores = [] bogus = 0 for size in xrange(sample_size): score_empty = self.score_add_value(0, bogus, size) if len(counts) == 0 or counts[-1] != 0: counts.append(0) scores.append(score_empty) else: scores[-1] = score_empty <|code_end|> using the current file's imports: from distributions.dbg.special import log from distributions.dbg.random import sample_discrete_log from distributions.mixins import SharedIoMixin and any relevant context from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_discrete_log(scores): # probs = scores_to_probs(scores) # return sample_discrete(probs, total=1.0) . Output only the next line.
assign = sample_discrete_log(scores)
Here is a snippet: <|code_start|> self.count_times_variance = float(raw['count_times_variance']) def dump(self): return { 'count': self.count, 'mean': self.mean, 'count_times_variance': self.count_times_variance, } def protobuf_load(self, message): self.count = int(message.count) self.mean = float(message.mean) self.count_times_variance = float(message.count_times_variance) def protobuf_dump(self, message): message.count = self.count message.mean = self.mean message.count_times_variance = self.count_times_variance class Sampler(object): def init(self, shared, group=None): """ Draw samples from the marginal posteriors of mu and sigmasq \cite{murphy2007conjugate}, Eqs. 156 & 167 """ post = shared if group is None else shared.plus_group(group) # Sample from the inverse-chi^2 using the transform from the chi^2 sigmasq_star = post.nu * post.sigmasq / sample_chi2(post.nu) <|code_end|> . Write the next line using the current file imports: from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) , which may include functions, classes, or code. Output only the next line.
self.sigma = sqrt(sigmasq_star)
Using the snippet: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ A conjugate model on normally-distributied univariate data in which the prior on the mean is normally distributed, and the prior on the variance is Inverse-Chi-Square distributed. The equations used here are from \cite{murphy2007conjugate}. Murphy, K. "Conjugate Bayesian analysis of the Gaussian distribution" (2007) Equation numbers referenced below are from this paper. """ # scalar score_student_t, see distributions.dbg.random.score_student_t # for the multivariate generalization def score_student_t(x, nu, mu, sigmasq): """ \cite{murphy2007conjugate}, Eq. 304 """ score = gammaln(.5 * (nu + 1.)) - gammaln(.5 * nu) <|code_end|> , determine the next line of code. You have imports: from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context (class names, function names, or code) available: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) . Output only the next line.
score -= .5 * log(nu * pi * sigmasq)
Given the following code snippet before the placeholder: <|code_start|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ A conjugate model on normally-distributied univariate data in which the prior on the mean is normally distributed, and the prior on the variance is Inverse-Chi-Square distributed. The equations used here are from \cite{murphy2007conjugate}. Murphy, K. "Conjugate Bayesian analysis of the Gaussian distribution" (2007) Equation numbers referenced below are from this paper. """ # scalar score_student_t, see distributions.dbg.random.score_student_t # for the multivariate generalization def score_student_t(x, nu, mu, sigmasq): """ \cite{murphy2007conjugate}, Eq. 304 """ score = gammaln(.5 * (nu + 1.)) - gammaln(.5 * nu) <|code_end|> , predict the next line using imports from the current file: from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context including class names, function names, and sometimes code from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) . Output only the next line.
score -= .5 * log(nu * pi * sigmasq)
Using the snippet: <|code_start|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ A conjugate model on normally-distributied univariate data in which the prior on the mean is normally distributed, and the prior on the variance is Inverse-Chi-Square distributed. The equations used here are from \cite{murphy2007conjugate}. Murphy, K. "Conjugate Bayesian analysis of the Gaussian distribution" (2007) Equation numbers referenced below are from this paper. """ # scalar score_student_t, see distributions.dbg.random.score_student_t # for the multivariate generalization def score_student_t(x, nu, mu, sigmasq): """ \cite{murphy2007conjugate}, Eq. 304 """ <|code_end|> , determine the next line of code. You have imports: from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context (class names, function names, or code) available: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) . Output only the next line.
score = gammaln(.5 * (nu + 1.)) - gammaln(.5 * nu)
Predict the next line for this snippet: <|code_start|> self.mean = float(raw['mean']) self.count_times_variance = float(raw['count_times_variance']) def dump(self): return { 'count': self.count, 'mean': self.mean, 'count_times_variance': self.count_times_variance, } def protobuf_load(self, message): self.count = int(message.count) self.mean = float(message.mean) self.count_times_variance = float(message.count_times_variance) def protobuf_dump(self, message): message.count = self.count message.mean = self.mean message.count_times_variance = self.count_times_variance class Sampler(object): def init(self, shared, group=None): """ Draw samples from the marginal posteriors of mu and sigmasq \cite{murphy2007conjugate}, Eqs. 156 & 167 """ post = shared if group is None else shared.plus_group(group) # Sample from the inverse-chi^2 using the transform from the chi^2 <|code_end|> with the help of current file imports: from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) , which may contain function names, class names, or code. Output only the next line.
sigmasq_star = post.nu * post.sigmasq / sample_chi2(post.nu)
Next line prediction: <|code_start|> def dump(self): return { 'count': self.count, 'mean': self.mean, 'count_times_variance': self.count_times_variance, } def protobuf_load(self, message): self.count = int(message.count) self.mean = float(message.mean) self.count_times_variance = float(message.count_times_variance) def protobuf_dump(self, message): message.count = self.count message.mean = self.mean message.count_times_variance = self.count_times_variance class Sampler(object): def init(self, shared, group=None): """ Draw samples from the marginal posteriors of mu and sigmasq \cite{murphy2007conjugate}, Eqs. 156 & 167 """ post = shared if group is None else shared.plus_group(group) # Sample from the inverse-chi^2 using the transform from the chi^2 sigmasq_star = post.nu * post.sigmasq / sample_chi2(post.nu) self.sigma = sqrt(sigmasq_star) <|code_end|> . Use current file imports: (from distributions.dbg.special import sqrt, log, pi, gammaln from distributions.dbg.random import sample_chi2, sample_normal from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin) and context including class names, function names, or small code snippets from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # def sample_chi2(nu): # return chi2.rvs(nu) # # def sample_normal(mu, sigmasq): # return norm.rvs(mu, sigmasq) . Output only the next line.
self.mu = sample_normal(post.mu, sqrt(sigmasq_star / post.kappa))
Here is a snippet: <|code_start|> def test_log_stirling1_row(): require_cython() MAX_N = 128 rows = [[1]] for n in range(1, MAX_N + 1): prev = rows[-1] middle = [(n - 1) * prev[k] + prev[k - 1] for k in range(1, n)] row = [0] + middle + [1] rows.append(row) for n in range(1, MAX_N + 1): print 'Row {}:'.format(n), row_py = numpy.log(numpy.array(rows[n][1:], dtype=numpy.double)) row_cpp = log_stirling1_row(n)[1:] assert_equal(len(row_py), len(row_cpp)) # only the slopes need to be accurate #print 0, #assert_close(row_py[0], row_cpp[0]) #print len(row_py) #assert_close(row_py[-1], row_cpp[-1]) diff_py = numpy.diff(row_py) diff_cpp = numpy.diff(row_cpp) for k_minus_1, (dx_py, dx_cpp) in enumerate(zip(diff_py, diff_cpp)): k = k_minus_1 + 1 print '%d-%d' % (k, k + 1), <|code_end|> . Write the next line using the current file imports: import numpy from nose.tools import assert_equal from distributions.tests.util import require_cython, assert_close from distributions.lp.special import log_stirling1_row and context from other files: # Path: distributions/tests/util.py # def require_cython(): # if not distributions.has_cython: # raise SkipTest('no cython support') # # def assert_close(lhs, rhs, tol=TOL, err_msg=None): # try: # if isinstance(lhs, dict): # assert_true( # isinstance(rhs, dict), # 'type mismatch: {} vs {}'.format(type(lhs), type(rhs))) # assert_equal(set(lhs.keys()), set(rhs.keys())) # for key, val in lhs.iteritems(): # msg = '{}[{}]'.format(err_msg or '', key) # assert_close(val, rhs[key], tol, msg) # elif isinstance(lhs, float) or isinstance(lhs, numpy.float64): # assert_true( # isinstance(rhs, float) or isinstance(rhs, numpy.float64), # 'type mismatch: {} vs {}'.format(type(lhs), type(rhs))) # diff = abs(lhs - rhs) # norm = 1 + abs(lhs) + abs(rhs) # msg = '{} off by {}% = {}'.format( # err_msg or '', # 100 * diff / norm, # diff) # assert_less(diff, tol * norm, msg) # elif isinstance(lhs, numpy.ndarray) or isinstance(rhs, numpy.ndarray): # assert_true( # (isinstance(lhs, numpy.ndarray) or isinstance(lhs, list)) and # (isinstance(rhs, numpy.ndarray) or isinstance(rhs, list)), # 'type mismatch: {} vs {}'.format(type(lhs), type(rhs))) # decimal = int(round(-math.log10(tol))) # assert_array_almost_equal( # lhs, # rhs, # decimal=decimal, # err_msg=(err_msg or '')) # elif isinstance(lhs, list) or isinstance(lhs, tuple): # assert_true( # isinstance(rhs, list) or isinstance(rhs, tuple), # 'type mismatch: {} vs {}'.format(type(lhs), type(rhs))) # for pos, (x, y) in enumerate(izip(lhs, rhs)): # msg = '{}[{}]'.format(err_msg or '', pos) # assert_close(x, y, tol, msg) # else: # assert_equal(lhs, rhs, err_msg) # except Exception: # print err_msg or '' # print 'actual = {}'.format(print_short(lhs)) # print 'expected = {}'.format(print_short(rhs)) # raise , which may include functions, classes, or code. Output only the next line.
assert_close(dx_py, dx_cpp, tol=0.5)
Next line prediction: <|code_start|> for alpha in self.alphas: message.alphas.append(alpha) class Group(GroupIoMixin): def __init__(self): self.counts = None def init(self, shared): self.counts = numpy.zeros(shared.dim, dtype=numpy.int) def add_value(self, shared, value): self.counts[value] += 1 def add_repeated_value(self, shared, value, count): self.counts[value] += count def remove_value(self, shared, value): self.counts[value] -= 1 def merge(self, shared, source): self.counts += source.counts def score_value(self, shared, value): """ \cite{wallach2009rethinking} Eqn 4. McCallum, et. al, 'Rething LDA: Why Priors Matter' """ numer = self.counts[value] + shared.alphas[value] denom = self.counts.sum() + shared.alphas.sum() <|code_end|> . Use current file imports: (import numpy from distributions.dbg.special import log, gammaln from distributions.dbg.random import sample_discrete, sample_dirichlet from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin) and context including class names, function names, or small code snippets from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # LOG = logging.getLogger(__name__) # S = inner(inner(z, inv(sigma)), z) # X = multivariate_normal(mean=numpy.zeros(d), cov=Lambda, size=nu) # S = numpy.dot(X.T, X) # T = numpy.zeros((d, d)) # D, = mu0.shape # Z = 0. # def seed(x): # def sample_discrete_log(scores): # def sample_bernoulli(prob): # def sample_discrete(probs, total=None): # def sample_normal(mu, sigmasq): # def sample_chi2(nu): # def sample_student_t(dof, mu, Sigma): # def score_student_t(x, nu, mu, sigma): # def sample_wishart_naive(nu, Lambda): # def sample_wishart(nu, Lambda): # def sample_wishart_v2(nu, Lambda): # def sample_inverse_wishart(nu, S): # def sample_normal_inverse_wishart(mu0, lambda0, psi0, nu0): # def sample_partition_from_counts(items, counts): # def sample_stick(gamma, tol=1e-3): # def sample_negative_binomial(p, r): . Output only the next line.
return log(numer / denom)
Here is a snippet: <|code_start|> def add_repeated_value(self, shared, value, count): self.counts[value] += count def remove_value(self, shared, value): self.counts[value] -= 1 def merge(self, shared, source): self.counts += source.counts def score_value(self, shared, value): """ \cite{wallach2009rethinking} Eqn 4. McCallum, et. al, 'Rething LDA: Why Priors Matter' """ numer = self.counts[value] + shared.alphas[value] denom = self.counts.sum() + shared.alphas.sum() return log(numer / denom) def score_data(self, shared): """ \cite{jordan2001more} Eqn 22. Michael Jordan's CS281B/Stat241B Advanced Topics in Learning and Decision Making course, 'More on Marginal Likelihood' """ dim = shared.dim a = shared.alphas m = self.counts <|code_end|> . Write the next line using the current file imports: import numpy from distributions.dbg.special import log, gammaln from distributions.dbg.random import sample_discrete, sample_dirichlet from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context from other files: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # LOG = logging.getLogger(__name__) # S = inner(inner(z, inv(sigma)), z) # X = multivariate_normal(mean=numpy.zeros(d), cov=Lambda, size=nu) # S = numpy.dot(X.T, X) # T = numpy.zeros((d, d)) # D, = mu0.shape # Z = 0. # def seed(x): # def sample_discrete_log(scores): # def sample_bernoulli(prob): # def sample_discrete(probs, total=None): # def sample_normal(mu, sigmasq): # def sample_chi2(nu): # def sample_student_t(dof, mu, Sigma): # def score_student_t(x, nu, mu, sigma): # def sample_wishart_naive(nu, Lambda): # def sample_wishart(nu, Lambda): # def sample_wishart_v2(nu, Lambda): # def sample_inverse_wishart(nu, S): # def sample_normal_inverse_wishart(mu0, lambda0, psi0, nu0): # def sample_partition_from_counts(items, counts): # def sample_stick(gamma, tol=1e-3): # def sample_negative_binomial(p, r): , which may include functions, classes, or code. Output only the next line.
score = sum(gammaln(a[k] + m[k]) - gammaln(a[k]) for k in xrange(dim))
Using the snippet: <|code_start|> return score def sample_value(self, shared): sampler = Sampler() sampler.init(shared, self) return sampler.eval(shared) def load(self, raw): self.counts = numpy.array(raw['counts'], dtype=numpy.int) def dump(self): return {'counts': self.counts.tolist()} def protobuf_load(self, message): self.counts = numpy.array(message.counts, dtype=numpy.int) def protobuf_dump(self, message): message.Clear() for count in self.counts: message.counts.append(count) class Sampler(object): def init(self, shared, group=None): if group is None: self.ps = sample_dirichlet(shared.alphas) else: self.ps = sample_dirichlet(group.counts + shared.alphas) def eval(self, shared): <|code_end|> , determine the next line of code. You have imports: import numpy from distributions.dbg.special import log, gammaln from distributions.dbg.random import sample_discrete, sample_dirichlet from distributions.mixins import SharedMixin, GroupIoMixin, SharedIoMixin and context (class names, function names, or code) available: # Path: distributions/dbg/special.py # # Path: distributions/dbg/random.py # LOG = logging.getLogger(__name__) # S = inner(inner(z, inv(sigma)), z) # X = multivariate_normal(mean=numpy.zeros(d), cov=Lambda, size=nu) # S = numpy.dot(X.T, X) # T = numpy.zeros((d, d)) # D, = mu0.shape # Z = 0. # def seed(x): # def sample_discrete_log(scores): # def sample_bernoulli(prob): # def sample_discrete(probs, total=None): # def sample_normal(mu, sigmasq): # def sample_chi2(nu): # def sample_student_t(dof, mu, Sigma): # def score_student_t(x, nu, mu, sigma): # def sample_wishart_naive(nu, Lambda): # def sample_wishart(nu, Lambda): # def sample_wishart_v2(nu, Lambda): # def sample_inverse_wishart(nu, S): # def sample_normal_inverse_wishart(mu0, lambda0, psi0, nu0): # def sample_partition_from_counts(items, counts): # def sample_stick(gamma, tol=1e-3): # def sample_negative_binomial(p, r): . Output only the next line.
return sample_discrete(self.ps)