_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q254200
RfLint._load_rule_file
validation
def _load_rule_file(self, filename): """Import the given rule file""" if not (os.path.exists(filename)): sys.stderr.write("rflint: %s: No such file or directory\n" % filename)
python
{ "resource": "" }
q254201
RfLint.parse_and_process_args
validation
def parse_and_process_args(self, args): """Handle the parsing of command line arguments.""" parser = argparse.ArgumentParser( prog="python -m rflint", description="A style checker for robot framework plain text files.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog = ( "You can use 'all' in place of RULENAME to refer to all rules. \n" "\n" "For example: '--ignore all --warn DuplicateTestNames' will ignore all\n" "rules except DuplicateTestNames.\n" "\n" "FORMAT is a string that performs a substitution on the following \n" "patterns: {severity}, {linenumber}, {char}, {message}, and {rulename}.\n" "\n" "For example: --format 'line: {linenumber}: message: {message}'. \n" "\n" "ARGUMENTFILE is a filename with contents that match the format of \n" "standard robot framework argument files\n" "\n" "If you give a directory as an argument, all files in the directory\n" "with the suffix .txt, .robot or .tsv will be processed. With the \n" "--recursive option, subfolders within the directory will also be\n" "processed." ) ) parser.add_argument("--error", "-e", metavar="RULENAME", action=SetErrorAction, help="Assign a severity of ERROR to the given RULENAME") parser.add_argument("--ignore", "-i", metavar="RULENAME", action=SetIgnoreAction, help="Ignore the given RULENAME") parser.add_argument("--warning", "-w", metavar="RULENAME", action=SetWarningAction, help="Assign a severity of WARNING for the given RULENAME") parser.add_argument("--list", "-l", action="store_true", help="show a list of known rules and exit") parser.add_argument("--describe", "-d", action="store_true", help="describe the given rules") parser.add_argument("--no-filenames", action="store_false", dest="print_filenames", default=True, help="suppress the printing of filenames") parser.add_argument("--format", "-f",
python
{ "resource": "" }
q254202
Draft4ExtendedValidatorFactory.from_resolver
validation
def from_resolver(cls, spec_resolver): """Creates a customized Draft4ExtendedValidator. :param spec_resolver: resolver for the spec
python
{ "resource": "" }
q254203
ExtendedSafeConstructor.construct_mapping
validation
def construct_mapping(self, node, deep=False): """While yaml supports integer keys, these are not valid in json, and will break jsonschema. This method coerces all keys to strings. """ mapping = super(ExtendedSafeConstructor, self).construct_mapping(
python
{ "resource": "" }
q254204
read_yaml_file
validation
def read_yaml_file(path, loader=ExtendedSafeLoader): """Open a file, read it and return its contents."""
python
{ "resource": "" }
q254205
SpecValidatorsGeneratorFactory.from_spec_resolver
validation
def from_spec_resolver(cls, spec_resolver): """Creates validators generator for the spec resolver. :param spec_resolver: resolver for the spec :type instance_resolver: :class:`jsonschema.RefResolver` """
python
{ "resource": "" }
q254206
create_model_path
validation
def create_model_path(model_path): """ Creates a path to model files model_path - string """ if not model_path.startswith("/") and not model_path.startswith("models/"): model_path="/" + model_path if not model_path.startswith("models"):
python
{ "resource": "" }
q254207
sub_chars
validation
def sub_chars(string): """ Strips illegal characters from a string. Used to sanitize input essays. Removes all non-punctuation, digit, or letter characters. Returns sanitized string. string - string """ #Define replacement patterns sub_pat = r"[^A-Za-z\.\?!,';:]" char_pat = r"\." com_pat = r"," ques_pat = r"\?"
python
{ "resource": "" }
q254208
spell_correct
validation
def spell_correct(string): """ Uses aspell to spell correct an input string. Requires aspell to be installed and added to the path. Returns the spell corrected string if aspell is found, original string if not. string - string """ # Create a temp file so that aspell could be used # By default, tempfile will delete this file when the file handle is closed. f = tempfile.NamedTemporaryFile(mode='w') f.write(string) f.flush() f_path = os.path.abspath(f.name) try: p = os.popen(aspell_path + " -a < " + f_path + " --sug-mode=ultra") # Aspell returns a list of incorrect words with the above flags incorrect = p.readlines() p.close() except Exception: log.exception("aspell process failed; could not spell check") # Return original string if aspell fails return string,0, string finally: f.close() incorrect_words = list() correct_spelling = list() for i in range(1, len(incorrect)): if(len(incorrect[i]) > 10): #Reformat aspell output to make sense match = re.search(":", incorrect[i]) if hasattr(match, "start"): begstring = incorrect[i][2:match.start()] begmatch = re.search(" ", begstring)
python
{ "resource": "" }
q254209
f7
validation
def f7(seq): """ Makes a list unique """ seen = set() seen_add = seen.add
python
{ "resource": "" }
q254210
count_list
validation
def count_list(the_list): """ Generates a count of the number of times each unique item appears in a list """ count = the_list.count
python
{ "resource": "" }
q254211
regenerate_good_tokens
validation
def regenerate_good_tokens(string): """ Given an input string, part of speech tags the string, then generates a list of ngrams that appear in the string. Used to define grammatically correct part of speech tag sequences. Returns a list of part of speech tag sequences. """ toks = nltk.word_tokenize(string) pos_string =
python
{ "resource": "" }
q254212
edit_distance
validation
def edit_distance(s1, s2): """ Calculates string edit distance between string 1 and string 2. Deletion, insertion, substitution, and transposition all increase edit distance. """ d = {} lenstr1 = len(s1) lenstr2 = len(s2) for i in xrange(-1, lenstr1 + 1): d[(i, -1)] = i + 1 for j in xrange(-1, lenstr2 + 1): d[(-1, j)] = j + 1 for i in xrange(lenstr1): for j in xrange(lenstr2): if s1[i] == s2[j]: cost = 0 else: cost = 1 d[(i, j)] = min( d[(i - 1, j)] + 1, # deletion
python
{ "resource": "" }
q254213
gen_preds
validation
def gen_preds(clf, arr): """ Generates predictions on a novel data array using a fit classifier clf is a classifier that has already been fit arr is a data array identical in dimension to the array clf was trained on Returns the array of predictions.
python
{ "resource": "" }
q254214
calc_list_average
validation
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total =
python
{ "resource": "" }
q254215
quadratic_weighted_kappa
validation
def quadratic_weighted_kappa(rater_a, rater_b, min_rating=None, max_rating=None): """ Calculates kappa correlation between rater_a and rater_b. Kappa measures how well 2 quantities vary together. rater_a is a list of rater a scores rater_b is a list of rater b scores min_rating is an optional argument describing the minimum rating possible on the data set max_rating is an optional argument describing the maximum rating possible on the data set Returns a float corresponding to the kappa correlation """ assert(len(rater_a) == len(rater_b)) rater_a = [int(a) for a in rater_a] rater_b = [int(b) for b in rater_b] if min_rating is None: min_rating = min(rater_a + rater_b) if max_rating is None: max_rating = max(rater_a + rater_b) conf_mat = confusion_matrix(rater_a, rater_b, min_rating, max_rating) num_ratings = len(conf_mat) num_scored_items
python
{ "resource": "" }
q254216
confusion_matrix
validation
def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None): """ Generates a confusion matrix between rater_a and rater_b A confusion matrix shows how often 2 values agree and disagree See quadratic_weighted_kappa for argument descriptions """ assert(len(rater_a) == len(rater_b)) rater_a = [int(a) for a in rater_a]
python
{ "resource": "" }
q254217
histogram
validation
def histogram(ratings, min_rating=None, max_rating=None): """ Generates a frequency count of each rating on the scale ratings is a list of scores Returns a list of frequencies """ ratings = [int(r) for r in ratings] if min_rating is None: min_rating = min(ratings) if max_rating is None:
python
{ "resource": "" }
q254218
encode_plus
validation
def encode_plus(s): """ Literally encodes the plus sign input is a string returns the string with plus signs encoded """
python
{ "resource": "" }
q254219
FeatureExtractor.initialize_dictionaries
validation
def initialize_dictionaries(self, e_set, max_feats2 = 200): """ Initializes dictionaries from an essay set object Dictionaries must be initialized prior to using this to extract features e_set is an input essay set returns a confirmation of initialization """ if(hasattr(e_set, '_type')): if(e_set._type == "train"): #normal text (unstemmed) useful words/bigrams nvocab = util_functions.get_vocab(e_set._text, e_set._score, max_feats2 = max_feats2) #stemmed and spell corrected vocab useful words/ngrams svocab = util_functions.get_vocab(e_set._clean_stem_text, e_set._score, max_feats2 = max_feats2) #dictionary trained on proper vocab self._normal_dict = CountVectorizer(ngram_range=(1,2), vocabulary=nvocab) #dictionary trained on proper vocab self._stem_dict = CountVectorizer(ngram_range=(1,2), vocabulary=svocab) self.dict_initialized = True #Average spelling errors in set. needed later for spelling detection self._mean_spelling_errors=sum(e_set._spelling_errors)/float(len(e_set._spelling_errors)) self._spell_errors_per_character=sum(e_set._spelling_errors)/float(sum([len(t) for t in e_set._text])) #Gets the number and positions of grammar errors good_pos_tags,bad_pos_positions=self._get_grammar_errors(e_set._pos,e_set._text,e_set._tokens)
python
{ "resource": "" }
q254220
FeatureExtractor.get_good_pos_ngrams
validation
def get_good_pos_ngrams(self): """ Gets a set of gramatically correct part of speech sequences from an input file called essaycorpus.txt Returns the set and caches the file """ if(os.path.isfile(NGRAM_PATH)): good_pos_ngrams = pickle.load(open(NGRAM_PATH, 'rb')) elif os.path.isfile(ESSAY_CORPUS_PATH): essay_corpus = open(ESSAY_CORPUS_PATH).read() essay_corpus = util_functions.sub_chars(essay_corpus) good_pos_ngrams = util_functions.regenerate_good_tokens(essay_corpus) pickle.dump(good_pos_ngrams, open(NGRAM_PATH, 'wb')) else: #Hard coded list in case the needed files cannot be found
python
{ "resource": "" }
q254221
FeatureExtractor.gen_length_feats
validation
def gen_length_feats(self, e_set): """ Generates length based features from an essay set Generally an internal function called by gen_feats Returns an array of length features e_set - EssaySet object """ text = e_set._text lengths = [len(e) for e in text] word_counts = [max(len(t),1) for t in e_set._tokens] comma_count = [e.count(",") for e in text]
python
{ "resource": "" }
q254222
FeatureExtractor.gen_bag_feats
validation
def gen_bag_feats(self, e_set): """ Generates bag of words features from an input essay set and trained FeatureExtractor Generally called by gen_feats Returns an array of features e_set - EssaySet object """ if(hasattr(self, '_stem_dict')): sfeats = self._stem_dict.transform(e_set._clean_stem_text) nfeats = self._normal_dict.transform(e_set._text)
python
{ "resource": "" }
q254223
FeatureExtractor.gen_feats
validation
def gen_feats(self, e_set): """ Generates bag of words, length, and prompt features from an essay set object returns an array of features e_set - EssaySet object """ bag_feats = self.gen_bag_feats(e_set) length_feats = self.gen_length_feats(e_set) prompt_feats = self.gen_prompt_feats(e_set)
python
{ "resource": "" }
q254224
FeatureExtractor.gen_prompt_feats
validation
def gen_prompt_feats(self, e_set): """ Generates prompt based features from an essay set object and internal prompt variable. Generally called internally by gen_feats Returns an array of prompt features e_set - EssaySet object """ prompt_toks = nltk.word_tokenize(e_set._prompt) expand_syns = [] for word in prompt_toks: synonyms = util_functions.get_wordnet_syns(word) expand_syns.append(synonyms) expand_syns = list(chain.from_iterable(expand_syns)) prompt_overlap = []
python
{ "resource": "" }
q254225
EssaySet.update_prompt
validation
def update_prompt(self, prompt_text): """ Update the default prompt string, which is "". prompt_text should be a string. Returns the prompt as a confirmation. """ if(isinstance(prompt_text, basestring)): self._prompt = util_functions.sub_chars(prompt_text)
python
{ "resource": "" }
q254226
get_algorithms
validation
def get_algorithms(algorithm): """ Gets two classifiers for each type of algorithm, and returns them. First for predicting, second for cv error. type - one of util_functions.AlgorithmTypes """ if algorithm == util_functions.AlgorithmTypes.classification: clf = sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05, max_depth=4, random_state=1,min_samples_leaf=3) clf2=sklearn.ensemble.GradientBoostingClassifier(n_estimators=100, learn_rate=.05,
python
{ "resource": "" }
q254227
extract_features_and_generate_model_predictors
validation
def extract_features_and_generate_model_predictors(predictor_set, algorithm=util_functions.AlgorithmTypes.regression): """ Extracts features and generates predictors based on a given predictor set predictor_set - a PredictorSet object that has been initialized with data type - one of util_functions.AlgorithmType """ if(algorithm not in [util_functions.AlgorithmTypes.regression, util_functions.AlgorithmTypes.classification]): algorithm = util_functions.AlgorithmTypes.regression f = predictor_extractor.PredictorExtractor() f.initialize_dictionaries(predictor_set) train_feats = f.gen_feats(predictor_set) clf,clf2 = get_algorithms(algorithm)
python
{ "resource": "" }
q254228
extract_features_and_generate_model
validation
def extract_features_and_generate_model(essays, algorithm=util_functions.AlgorithmTypes.regression): """ Feed in an essay set to get feature vector and classifier essays must be an essay set object additional array is an optional argument that can specify a numpy array of values to add in returns a trained FeatureExtractor object and a trained classifier """ f = feature_extractor.FeatureExtractor() f.initialize_dictionaries(essays) train_feats = f.gen_feats(essays) set_score = numpy.asarray(essays._score, dtype=numpy.int) if len(util_functions.f7(list(set_score)))>5: algorithm = util_functions.AlgorithmTypes.regression
python
{ "resource": "" }
q254229
dump_model_to_file
validation
def dump_model_to_file(prompt_string, feature_ext, classifier, text, score, model_path): """ Writes out a model to a file. prompt string is a string containing the prompt feature_ext is a trained FeatureExtractor object classifier is a trained classifier model_path is the path of write out the model file to """ model_file
python
{ "resource": "" }
q254230
create_essay_set_and_dump_model
validation
def create_essay_set_and_dump_model(text,score,prompt,model_path,additional_array=None): """ Function that creates essay set, extracts features, and writes out model See above functions for argument descriptions """
python
{ "resource": "" }
q254231
PredictorExtractor.initialize_dictionaries
validation
def initialize_dictionaries(self, p_set): """ Initialize dictionaries with the textual inputs in the PredictorSet object p_set - PredictorSet object that has had data fed in """ success = False if not (hasattr(p_set, '_type')): error_message = "needs to be an essay set of the train type." log.exception(error_message) raise util_functions.InputError(p_set, error_message) if not (p_set._type == "train"): error_message = "needs to be an essay set of the train type." log.exception(error_message) raise util_functions.InputError(p_set, error_message) div_length=len(p_set._essay_sets) if div_length==0:
python
{ "resource": "" }
q254232
PredictorExtractor.gen_feats
validation
def gen_feats(self, p_set): """ Generates features based on an iput p_set p_set - PredictorSet """ if self._initialized!=True: error_message = "Dictionaries have not been initialized." log.exception(error_message) raise util_functions.InputError(p_set, error_message) textual_features = [] for i in xrange(0,len(p_set._essay_sets)):
python
{ "resource": "" }
q254233
Parser.order_error
validation
def order_error(self, first_tag, second_tag, line): """Reports an OrderError. Error message will state that first_tag came before second_tag. """ self.error = True msg =
python
{ "resource": "" }
q254234
write_creation_info
validation
def write_creation_info(creation_info, out): """ Write the creation info to out. """ out.write('# Creation Info\n\n') # Write sorted creators for creator in sorted(creation_info.creators): write_value('Creator', creator, out) # write
python
{ "resource": "" }
q254235
write_review
validation
def write_review(review, out): """ Write the fields of a single review to out. """ out.write('# Review\n\n') write_value('Reviewer',
python
{ "resource": "" }
q254236
write_annotation
validation
def write_annotation(annotation, out): """ Write the fields of a single annotation to out. """ out.write('# Annotation\n\n') write_value('Annotator', annotation.annotator, out) write_value('AnnotationDate', annotation.annotation_date_iso_format, out) if annotation.has_comment:
python
{ "resource": "" }
q254237
write_file
validation
def write_file(spdx_file, out): """ Write a file fields to out. """ out.write('# File\n\n') write_value('FileName', spdx_file.name, out) write_value('SPDXID', spdx_file.spdx_id, out) if spdx_file.has_optional_field('type'): write_file_type(spdx_file.type, out) write_value('FileChecksum', spdx_file.chk_sum.to_tv(), out) if isinstance(spdx_file.conc_lics, (document.LicenseConjunction, document.LicenseDisjunction)): write_value('LicenseConcluded', u'({0})'.format(spdx_file.conc_lics), out) else: write_value('LicenseConcluded', spdx_file.conc_lics, out) # write sorted list for lics in sorted(spdx_file.licenses_in_file): write_value('LicenseInfoInFile', lics, out) if isinstance(spdx_file.copyright, six.string_types): write_text_value('FileCopyrightText', spdx_file.copyright, out) else: write_value('FileCopyrightText', spdx_file.copyright, out) if spdx_file.has_optional_field('license_comment'): write_text_value('LicenseComments', spdx_file.license_comment, out) if spdx_file.has_optional_field('comment'): write_text_value('FileComment', spdx_file.comment, out) if spdx_file.has_optional_field('notice'):
python
{ "resource": "" }
q254238
write_package
validation
def write_package(package, out): """ Write a package fields to out. """ out.write('# Package\n\n') write_value('PackageName', package.name, out) if package.has_optional_field('version'): write_value('PackageVersion', package.version, out) write_value('PackageDownloadLocation', package.download_location, out) if package.has_optional_field('summary'): write_text_value('PackageSummary', package.summary, out) if package.has_optional_field('source_info'): write_text_value('PackageSourceInfo', package.source_info, out) if package.has_optional_field('file_name'): write_value('PackageFileName', package.file_name, out) if package.has_optional_field('supplier'): write_value('PackageSupplier', package.supplier, out) if package.has_optional_field('originator'): write_value('PackageOriginator', package.originator, out) if package.has_optional_field('check_sum'): write_value('PackageChecksum', package.check_sum.to_tv(), out) write_value('PackageVerificationCode', format_verif_code(package), out) if package.has_optional_field('description'): write_text_value('PackageDescription', package.description, out) if isinstance(package.license_declared, (document.LicenseConjunction, document.LicenseDisjunction)): write_value('PackageLicenseDeclared', u'({0})'.format(package.license_declared), out) else: write_value('PackageLicenseDeclared', package.license_declared, out) if isinstance(package.conc_lics, (document.LicenseConjunction,
python
{ "resource": "" }
q254239
write_extracted_licenses
validation
def write_extracted_licenses(lics, out): """ Write extracted licenses fields to out. """ write_value('LicenseID', lics.identifier, out) if lics.full_name is not None: write_value('LicenseName', lics.full_name, out) if lics.comment is not None:
python
{ "resource": "" }
q254240
write_document
validation
def write_document(document, out, validate=True): """ Write an SPDX tag value document. - document - spdx.document instance. - out - file like object that will be written to. Optionally `validate` the document before writing and raise InvalidDocumentError if document.validate returns False. """ messages = [] messages = document.validate(messages) if validate and messages: raise InvalidDocumentError(messages) # Write out document information out.write('# Document Information\n\n') write_value('SPDXVersion', str(document.version), out) write_value('DataLicense', document.data_license.identifier, out) write_value('DocumentName', document.name, out) write_value('SPDXID', 'SPDXRef-DOCUMENT', out) write_value('DocumentNamespace', document.namespace, out) if document.has_comment: write_text_value('DocumentComment', document.comment, out) for doc_ref in document.ext_document_references: doc_ref_str = ' '.join([doc_ref.external_document_id, doc_ref.spdx_document_uri, doc_ref.check_sum.identifier + ':' + doc_ref.check_sum.value])
python
{ "resource": "" }
q254241
checksum_from_sha1
validation
def checksum_from_sha1(value): """ Return an spdx.checksum.Algorithm instance representing the SHA1 checksum or None if does not match CHECKSUM_RE. """ # More constrained regex at lexer level CHECKSUM_RE = re.compile('SHA1:\s*([\S]+)', re.UNICODE)
python
{ "resource": "" }
q254242
str_from_text
validation
def str_from_text(text): """ Return content of a free form text block as a string. """ REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE) match =
python
{ "resource": "" }
q254243
DocBuilder.set_doc_version
validation
def set_doc_version(self, doc, value): """ Set the document version. Raise SPDXValueError if malformed value, CardinalityError if already defined """ if not self.doc_version_set: self.doc_version_set = True m = self.VERS_STR_REGEX.match(value) if m is None: raise SPDXValueError('Document::Version') else:
python
{ "resource": "" }
q254244
DocBuilder.set_doc_data_lics
validation
def set_doc_data_lics(self, doc, lics): """Sets the document data license. Raises value error if malformed value, CardinalityError if already defined. """ if not self.doc_data_lics_set: self.doc_data_lics_set = True if validations.validate_data_lics(lics):
python
{ "resource": "" }
q254245
DocBuilder.set_doc_name
validation
def set_doc_name(self, doc, name): """Sets the document name. Raises CardinalityError if already defined. """ if not self.doc_name_set: doc.name = name
python
{ "resource": "" }
q254246
DocBuilder.set_doc_spdx_id
validation
def set_doc_spdx_id(self, doc, doc_spdx_id_line): """Sets the document SPDX Identifier. Raises value error if malformed value, CardinalityError if already defined. """ if not self.doc_spdx_id_set: if doc_spdx_id_line == 'SPDXRef-DOCUMENT': doc.spdx_id = doc_spdx_id_line
python
{ "resource": "" }
q254247
DocBuilder.set_doc_comment
validation
def set_doc_comment(self, doc, comment): """Sets document comment, Raises CardinalityError if comment already set. Raises SPDXValueError if comment is not free form text. """ if not self.doc_comment_set: self.doc_comment_set = True if validations.validate_doc_comment(comment):
python
{ "resource": "" }
q254248
DocBuilder.set_doc_namespace
validation
def set_doc_namespace(self, doc, namespace): """Sets the document namespace. Raise SPDXValueError if malformed value, CardinalityError if already defined. """ if not self.doc_namespace_set: self.doc_namespace_set = True if validations.validate_doc_namespace(namespace):
python
{ "resource": "" }
q254249
DocBuilder.reset_document
validation
def reset_document(self): """Resets the state to allow building new documents""" # FIXME: this state does not make sense self.doc_version_set = False self.doc_comment_set = False
python
{ "resource": "" }
q254250
ExternalDocumentRefBuilder.set_spdx_doc_uri
validation
def set_spdx_doc_uri(self, doc, spdx_doc_uri): """ Sets the `spdx_document_uri` attribute of the `ExternalDocumentRef` object. """ if validations.validate_doc_namespace(spdx_doc_uri):
python
{ "resource": "" }
q254251
EntityBuilder.build_tool
validation
def build_tool(self, doc, entity): """Builds a tool object out of a string representation. Returns built tool. Raises SPDXValueError if failed to extract tool name or name is malformed """ match = self.tool_re.match(entity) if match and validations.validate_tool_name(match.group(self.TOOL_NAME_GROUP)):
python
{ "resource": "" }
q254252
CreationInfoBuilder.add_creator
validation
def add_creator(self, doc, creator): """Adds a creator to the document's creation info. Returns true if creator is valid. Creator must be built by an EntityBuilder. Raises SPDXValueError if not a creator type. """ if validations.validate_creator(creator):
python
{ "resource": "" }
q254253
CreationInfoBuilder.set_created_date
validation
def set_created_date(self, doc, created): """Sets created date, Raises CardinalityError if created date already set. Raises SPDXValueError if created is not a date. """ if not self.created_date_set:
python
{ "resource": "" }
q254254
CreationInfoBuilder.set_lics_list_ver
validation
def set_lics_list_ver(self, doc, value): """Sets the license list version, Raises CardinalityError if already set, SPDXValueError if incorrect value. """ if not self.lics_list_ver_set: self.lics_list_ver_set = True
python
{ "resource": "" }
q254255
CreationInfoBuilder.reset_creation_info
validation
def reset_creation_info(self): """ Resets builder state to allow building new creation info.""" # FIXME: this state does not make sense
python
{ "resource": "" }
q254256
ReviewBuilder.add_reviewer
validation
def add_reviewer(self, doc, reviewer): """Adds a reviewer to the SPDX Document. Reviwer is an entity created by an EntityBuilder. Raises SPDXValueError if not a valid reviewer type. """ # Each reviewer marks the start of a new review object. # FIXME: this state does not make sense
python
{ "resource": "" }
q254257
ReviewBuilder.add_review_date
validation
def add_review_date(self, doc, reviewed): """Sets the review date. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if invalid reviewed value. """ if len(doc.reviews) != 0: if not self.review_date_set: self.review_date_set = True date = utils.datetime_from_iso_format(reviewed) if date is not None:
python
{ "resource": "" }
q254258
ReviewBuilder.add_review_comment
validation
def add_review_comment(self, doc, comment): """Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. """ if len(doc.reviews) != 0: if not self.review_comment_set: self.review_comment_set = True if validations.validate_review_comment(comment): doc.reviews[-1].comment = str_from_text(comment)
python
{ "resource": "" }
q254259
AnnotationBuilder.reset_annotations
validation
def reset_annotations(self): """Resets the builder's state to allow building new annotations.""" # FIXME: this state does not make sense self.annotation_date_set = False
python
{ "resource": "" }
q254260
AnnotationBuilder.add_annotator
validation
def add_annotator(self, doc, annotator): """Adds an annotator to the SPDX Document. Annotator is an entity created by an EntityBuilder. Raises SPDXValueError if not a valid annotator type. """ # Each annotator marks the start of a new annotation object. # FIXME: this state does not make sense self.reset_annotations()
python
{ "resource": "" }
q254261
AnnotationBuilder.add_annotation_date
validation
def add_annotation_date(self, doc, annotation_date): """Sets the annotation date. Raises CardinalityError if already set. OrderError if no annotator defined before. Raises SPDXValueError if invalid value. """ if len(doc.annotations) != 0: if not self.annotation_date_set: self.annotation_date_set = True date = utils.datetime_from_iso_format(annotation_date) if date is not None: doc.annotations[-1].annotation_date
python
{ "resource": "" }
q254262
AnnotationBuilder.add_annotation_comment
validation
def add_annotation_comment(self, doc, comment): """Sets the annotation comment. Raises CardinalityError if already set. OrderError if no annotator defined before. Raises SPDXValueError if comment is not free form text. """ if len(doc.annotations) != 0: if not self.annotation_comment_set: self.annotation_comment_set = True if validations.validate_annotation_comment(comment): doc.annotations[-1].comment = str_from_text(comment)
python
{ "resource": "" }
q254263
AnnotationBuilder.add_annotation_type
validation
def add_annotation_type(self, doc, annotation_type): """Sets the annotation type. Raises CardinalityError if already set. OrderError if no annotator defined before. Raises SPDXValueError if invalid value. """ if len(doc.annotations) != 0: if not self.annotation_type_set: self.annotation_type_set = True if validations.validate_annotation_type(annotation_type): doc.annotations[-1].annotation_type = annotation_type
python
{ "resource": "" }
q254264
AnnotationBuilder.set_annotation_spdx_id
validation
def set_annotation_spdx_id(self, doc, spdx_id): """Sets the annotation SPDX Identifier. Raises CardinalityError if already set. OrderError if no annotator defined before. """ if len(doc.annotations) != 0: if not self.annotation_spdx_id_set: self.annotation_spdx_id_set = True
python
{ "resource": "" }
q254265
PackageBuilder.reset_package
validation
def reset_package(self): """Resets the builder's state in order to build new packages.""" # FIXME: this state does not make sense self.package_set = False self.package_vers_set = False self.package_file_name_set = False self.package_supplier_set = False self.package_originator_set = False
python
{ "resource": "" }
q254266
PackageBuilder.create_package
validation
def create_package(self, doc, name): """Creates a package for the SPDX Document. name - any string. Raises CardinalityError if package already defined. """ if not self.package_set: self.package_set = True
python
{ "resource": "" }
q254267
PackageBuilder.set_pkg_vers
validation
def set_pkg_vers(self, doc, version): """Sets package version, if not already set. version - Any string. Raises CardinalityError if already has a version. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_vers_set:
python
{ "resource": "" }
q254268
PackageBuilder.set_pkg_file_name
validation
def set_pkg_file_name(self, doc, name): """Sets the package file name, if not already set. name - Any string. Raises CardinalityError if already has a file_name. Raises OrderError if no pacakge previously defined. """ self.assert_package_exists() if not self.package_file_name_set:
python
{ "resource": "" }
q254269
PackageBuilder.set_pkg_supplier
validation
def set_pkg_supplier(self, doc, entity): """Sets the package supplier, if not already set. entity - Organization, Person or NoAssert. Raises CardinalityError if already has a supplier. Raises OrderError if no package previously defined.
python
{ "resource": "" }
q254270
PackageBuilder.set_pkg_originator
validation
def set_pkg_originator(self, doc, entity): """Sets the package originator, if not already set. entity - Organization, Person or NoAssert. Raises CardinalityError if already has an originator. Raises OrderError if no package previously defined. """
python
{ "resource": "" }
q254271
PackageBuilder.set_pkg_down_location
validation
def set_pkg_down_location(self, doc, location): """Sets the package download location, if not already set. location - A string Raises CardinalityError if already defined. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_down_location_set:
python
{ "resource": "" }
q254272
PackageBuilder.set_pkg_home
validation
def set_pkg_home(self, doc, location): """Sets the package homepage location if not already set. location - A string or None or NoAssert. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. Raises SPDXValueError if location has incorrect
python
{ "resource": "" }
q254273
PackageBuilder.set_pkg_verif_code
validation
def set_pkg_verif_code(self, doc, code): """Sets the package verification code, if not already set. code - A string. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. Raises Value error if doesn't match verifcode form """ self.assert_package_exists() if not self.package_verif_set: self.package_verif_set = True match = self.VERIF_CODE_REGEX.match(code) if match: doc.package.verif_code = match.group(self.VERIF_CODE_CODE_GRP)
python
{ "resource": "" }
q254274
PackageBuilder.set_pkg_source_info
validation
def set_pkg_source_info(self, doc, text): """Sets the package's source information, if not already set. text - Free form text. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. SPDXValueError if text is not free form text. """ self.assert_package_exists() if not self.package_source_info_set: self.package_source_info_set = True if validations.validate_pkg_src_info(text):
python
{ "resource": "" }
q254275
PackageBuilder.set_pkg_licenses_concluded
validation
def set_pkg_licenses_concluded(self, doc, licenses): """Sets the package's concluded licenses. licenses - License info. Raises CardinalityError if already defined. Raises OrderError if no package previously defined. Raises SPDXValueError if data malformed. """ self.assert_package_exists() if not self.package_conc_lics_set: self.package_conc_lics_set = True if validations.validate_lics_conc(licenses):
python
{ "resource": "" }
q254276
PackageBuilder.set_pkg_license_from_file
validation
def set_pkg_license_from_file(self, doc, lic): """Adds a license from a file to the package. Raises SPDXValueError if data malformed. Raises OrderError if no package previously defined. """ self.assert_package_exists() if validations.validate_lics_from_file(lic):
python
{ "resource": "" }
q254277
PackageBuilder.set_pkg_license_declared
validation
def set_pkg_license_declared(self, doc, lic): """Sets the package's declared license. Raises SPDXValueError if data malformed. Raises OrderError if no package previously defined. Raises CardinalityError if already set. """ self.assert_package_exists() if not self.package_license_declared_set: self.package_license_declared_set = True
python
{ "resource": "" }
q254278
PackageBuilder.set_pkg_license_comment
validation
def set_pkg_license_comment(self, doc, text): """Sets the package's license comment. Raises OrderError if no package previously defined. Raises CardinalityError if already set. Raises SPDXValueError if text is not free form text. """ self.assert_package_exists() if not self.package_license_comment_set: self.package_license_comment_set = True
python
{ "resource": "" }
q254279
PackageBuilder.set_pkg_summary
validation
def set_pkg_summary(self, doc, text): """Set's the package summary. Raises SPDXValueError if text is not free form text. Raises CardinalityError if summary already set. Raises OrderError if no package previously defined. """ self.assert_package_exists() if not self.package_summary_set:
python
{ "resource": "" }
q254280
PackageBuilder.set_pkg_desc
validation
def set_pkg_desc(self, doc, text): """Set's the package's description. Raises SPDXValueError if text is not free form text. Raises CardinalityError if description already set. Raises OrderError if no package previously defined.
python
{ "resource": "" }
q254281
FileBuilder.set_file_name
validation
def set_file_name(self, doc, name): """Raises OrderError if no package defined. """ if self.has_package(doc): doc.package.files.append(file.File(name)) # A file name marks the start of a new file instance.
python
{ "resource": "" }
q254282
FileBuilder.set_file_spdx_id
validation
def set_file_spdx_id(self, doc, spdx_id): """ Sets the file SPDX Identifier. Raises OrderError if no package or no file defined. Raises SPDXValueError if malformed value. Raises CardinalityError if more than one spdx_id set. """ if self.has_package(doc) and self.has_file(doc): if not self.file_spdx_id_set: self.file_spdx_id_set = True if validations.validate_file_spdx_id(spdx_id):
python
{ "resource": "" }
q254283
FileBuilder.set_file_comment
validation
def set_file_comment(self, doc, text): """ Raises OrderError if no package or no file defined. Raises CardinalityError if more than one comment set. Raises SPDXValueError if text is not free form text. """ if self.has_package(doc) and self.has_file(doc): if not self.file_comment_set: self.file_comment_set = True if validations.validate_file_comment(text): self.file(doc).comment = str_from_text(text)
python
{ "resource": "" }
q254284
FileBuilder.set_file_type
validation
def set_file_type(self, doc, type_value): """ Raises OrderError if no package or file defined. Raises CardinalityError if more than one type set. Raises SPDXValueError if type is unknown. """ type_dict = { 'SOURCE': file.FileType.SOURCE, 'BINARY': file.FileType.BINARY, 'ARCHIVE': file.FileType.ARCHIVE, 'OTHER': file.FileType.OTHER } if self.has_package(doc) and self.has_file(doc): if not self.file_type_set: self.file_type_set = True
python
{ "resource": "" }
q254285
FileBuilder.set_file_chksum
validation
def set_file_chksum(self, doc, chksum): """ Raises OrderError if no package or file defined. Raises CardinalityError if more than one chksum set. """ if self.has_package(doc) and self.has_file(doc): if not self.file_chksum_set: self.file_chksum_set = True
python
{ "resource": "" }
q254286
FileBuilder.set_concluded_license
validation
def set_concluded_license(self, doc, lic): """ Raises OrderError if no package or file defined. Raises CardinalityError if already set. Raises SPDXValueError if malformed. """ if self.has_package(doc) and self.has_file(doc): if not self.file_conc_lics_set: self.file_conc_lics_set = True if validations.validate_lics_conc(lic): self.file(doc).conc_lics = lic
python
{ "resource": "" }
q254287
FileBuilder.set_file_license_in_file
validation
def set_file_license_in_file(self, doc, lic): """ Raises OrderError if no package or file defined. Raises SPDXValueError if malformed value. """ if self.has_package(doc) and self.has_file(doc): if validations.validate_file_lics_in_file(lic): self.file(doc).add_lics(lic)
python
{ "resource": "" }
q254288
FileBuilder.set_file_license_comment
validation
def set_file_license_comment(self, doc, text): """ Raises OrderError if no package or file defined. Raises SPDXValueError if text is not free form text. Raises CardinalityError if more than one per file. """ if self.has_package(doc) and self.has_file(doc):
python
{ "resource": "" }
q254289
FileBuilder.set_file_copyright
validation
def set_file_copyright(self, doc, text): """Raises OrderError if no package or file defined. Raises SPDXValueError if not free form text or NONE or NO_ASSERT. Raises CardinalityError if more than one. """ if self.has_package(doc) and self.has_file(doc): if not self.file_copytext_set: self.file_copytext_set = True if validations.validate_file_cpyright(text): if isinstance(text, string_types): self.file(doc).copyright = str_from_text(text)
python
{ "resource": "" }
q254290
FileBuilder.set_file_notice
validation
def set_file_notice(self, doc, text): """Raises OrderError if no package or file defined. Raises SPDXValueError if not free form text. Raises CardinalityError if more than one. """ if self.has_package(doc) and self.has_file(doc): if not self.file_notice_set: self.file_notice_set = True if validations.validate_file_notice(text): self.file(doc).notice = str_from_text(text)
python
{ "resource": "" }
q254291
FileBuilder.set_file_atrificat_of_project
validation
def set_file_atrificat_of_project(self, doc, symbol, value): """Sets a file name, uri or home artificat. Raises OrderError if no package or
python
{ "resource": "" }
q254292
FileBuilder.reset_file_stat
validation
def reset_file_stat(self): """Resets the builder's state to enable building new files.""" # FIXME: this state does not make sense self.file_spdx_id_set = False self.file_comment_set = False self.file_type_set = False self.file_chksum_set = False
python
{ "resource": "" }
q254293
LicenseBuilder.set_lic_id
validation
def set_lic_id(self, doc, lic_id): """Adds a new extracted license to the document. Raises SPDXValueError if data format is incorrect. """ # FIXME: this state does not make sense self.reset_extr_lics() if validations.validate_extracted_lic_id(lic_id):
python
{ "resource": "" }
q254294
LicenseBuilder.set_lic_text
validation
def set_lic_text(self, doc, text): """Sets license extracted text. Raises SPDXValueError if text is not free form text. Raises OrderError if no license ID defined. """ if self.has_extr_lic(doc): if not self.extr_text_set: self.extr_text_set = True if validations.validate_is_free_form_text(text): self.extr_lic(doc).text = str_from_text(text) return True
python
{ "resource": "" }
q254295
LicenseBuilder.set_lic_name
validation
def set_lic_name(self, doc, name): """Sets license name. Raises SPDXValueError if name is not str or utils.NoAssert Raises OrderError if no license id defined. """ if self.has_extr_lic(doc): if not self.extr_lic_name_set: self.extr_lic_name_set = True if validations.validate_extr_lic_name(name): self.extr_lic(doc).full_name = name return True
python
{ "resource": "" }
q254296
LicenseBuilder.set_lic_comment
validation
def set_lic_comment(self, doc, comment): """Sets license comment. Raises SPDXValueError if comment is not free form text. Raises OrderError if no license ID defined. """ if self.has_extr_lic(doc): if not self.extr_lic_comment_set: self.extr_lic_comment_set = True if validations.validate_is_free_form_text(comment): self.extr_lic(doc).comment = str_from_text(comment) return True
python
{ "resource": "" }
q254297
LicenseBuilder.add_lic_xref
validation
def add_lic_xref(self, doc, ref): """Adds a license cross reference. Raises OrderError if no License ID defined.
python
{ "resource": "" }
q254298
Builder.reset
validation
def reset(self): """Resets builder's state for building new documents. Must be called between usage with different documents. """ # FIXME: this state
python
{ "resource": "" }
q254299
datetime_iso_format
validation
def datetime_iso_format(date): """ Return an ISO-8601 representation of a datetime object. """ return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format(
python
{ "resource": "" }