def test_simple_type(): """ Test if it can validate a simple type """ lexems = [ "_", "_a", "a1", "int_", "int", "int ", "real", "boolean", "bolean" ] validator = Validator() assert validator.validate_lexems(lexems) == [ {"_": "<IDENTIFIER>"}, {"_a": "<IDENTIFIER>"}, {"a1": "<IDENTIFIER>"}, {"int_": "<IDENTIFIER>"}, {"int": "<SIMPLE_TYPE>"}, {"int ": None}, {"real": "<SIMPLE_TYPE>"}, {"boolean": "<SIMPLE_TYPE>"}, {"bolean": "<IDENTIFIER>"}, ]
def test_number_lexem(): """ Test if it can validate a number """ lexems = [ "197", "1", "10", "37", "58", "5", "1a2", ".", "1.", ] validator = Validator() assert validator.validate_lexems(lexems) == [ {"197": "<NUMBER>"}, {"1": "<NUMBER>"}, {"10": "<NUMBER>"}, {"37": "<NUMBER>"}, {"58": "<NUMBER>"}, {"5": "<NUMBER>"}, {"1a2": None}, {".": None}, {"1.": None}, ]
def test_relation(): """ Test if it can validate a relation """ lexems = [ "=", "<>", "<", "<=", ">=", ">", "#", "a", "&%4$", "1" ] validator = Validator() assert validator.validate_lexems(lexems) == [ {"=": "<RELATION>"}, {"<>": "<RELATION>"}, {"<": "<RELATION>"}, {"<=": "<RELATION>"}, {">=": "<RELATION>"}, {">": "<RELATION>"}, {"#": None}, {"a": "<IDENTIFIER>"}, {"&%4$": None}, {"1": "<NUMBER>"}, ]
def getChain(self): Validator.checkChainValidity(self.chain) Validator.consensus(self.chain) data = [] for block in self.chain: data.append(block.__dict__) return dumps({'length': len(data), 'chain': data})
def checkInputDir(inputdir: str, validator: val.Validator) -> (int, int): readFiles = 0 failed = 0 for inputFileName in os.listdir(inputdir): inputFile = os.path.join(inputdir, inputFileName) content = None with open(inputFile, "r") as f: content = f.read() readFiles += 1 if not validator.checkLength(content): log.warn(str.format("Odd input length: {}", inputFileName)) failed += 1 continue valid, invalidopcode = validator.checkInput(content) if not valid: log.warn(str.format("Invalid opcode {}: {}", invalidopcode, inputFileName)) failed += 1 global VALIDATED_SEQUENCES # inc validates sequences counter VALIDATED_SEQUENCES += 1 addSequenceLength(validator.getByteCount(content)) return readFiles, failed
def main(args): input_file = None output_file = None logger = create_logger(LOG_FILE, LOG_LEVEL) logger.info("Geofencing validator logger was created.") try: opts, args = getopt.getopt(sys.argv[1:], "i:o:", ["input=", "output="]) except getopt.GetoptError as exc: logger.error( "Got an error: \"{}\", while trying to get options".format(exc)) sys.exit(2) for opt, arg in opts: if opt in ("-i", "--input"): input_file = arg elif opt in ("-o", "--output"): output_file = arg else: logger.error("Incorrect parameter was set") sys.exit(usage) if input_file and output_file: validator = Validator(input_file, output_file) validator.process() else: logger.error("No input csv file or output file path in parameter") sys.exit(usage)
def test_identifier(): """ Test if it can validate a identifier """ lexems = [ "_", "_a", "a1", "1", "a111*", " ", "a_1", "#$&", ] validator = Validator() assert validator.validate_lexems(lexems) == [ {"_": "<IDENTIFIER>"}, {"_a": "<IDENTIFIER>"}, {"a1": "<IDENTIFIER>"}, {"1": "<NUMBER>"}, {"a111*": None}, {" ": None}, {"a_1": "<IDENTIFIER>"}, {"#$&": None}, ]
def checkInputDir(inputdir: str, validator: val.Validator) -> (int, int): readFiles = 0 failed = 0 for inputFileName in os.listdir(inputdir): inputFile = os.path.join(inputdir, inputFileName) content = None with open(inputFile, "r") as f: content = f.read() readFiles += 1 if not validator.checkLength(content): log.warn(str.format("Odd input length: {}", inputFileName)) failed += 1 continue valid, invalidopcode = validator.checkInput(content) if not valid: log.warn( str.format("Invalid opcode {}: {}", invalidopcode, inputFileName)) failed += 1 global VALIDATED_SEQUENCES # inc validates sequences counter VALIDATED_SEQUENCES += 1 addSequenceLength(validator.getByteCount(content)) return readFiles, failed
def test_keyword(): """ Test if it can validate a keyword """ lexems = [ "program", "progra", "procedure", "procedur", "var", "va", "read", "rea", "write", "writ", "begin", "begi", "end", "en", "if", "i", "then", "the", "else", "els", "while", "whil", "do", "d" ] validator = Validator() assert validator.validate_lexems(lexems) == [ {"program": "<KEYWORD_PROGRAM>"}, {"progra": "<IDENTIFIER>"}, {"procedure": "<KEYWORD_PROCEDURE>"}, {"procedur": "<IDENTIFIER>"}, {"var": "<KEYWORD_VAR>"}, {"va": "<IDENTIFIER>"}, {"read": "<KEYWORD_READ>"}, {"rea": "<IDENTIFIER>"}, {"write": "<KEYWORD_WRITE>"}, {"writ": "<IDENTIFIER>"}, {"begin": "<KEYWORD_BEGIN>"}, {"begi": "<IDENTIFIER>"}, {"end": "<KEYWORD_END>"}, {"en": "<IDENTIFIER>"}, {"if": "<KEYWORD_IF>"}, {"i": "<IDENTIFIER>"}, {"then": "<KEYWORD_THEN>"}, {"the": "<IDENTIFIER>"}, {"else": "<KEYWORD_ELSE>"}, {"els": "<IDENTIFIER>"}, {"while": "<KEYWORD_WHILE>"}, {"whil": "<IDENTIFIER>"}, {"do": "<KEYWORD_DO>"}, {"d": "<IDENTIFIER>"}, ]
def test_validatorStr(self): validator = Validator() valid = validator.validate('') self.assertFalse(valid) valid = validator.validate(' ') self.assertFalse(valid) valid = validator.validate('auqywsdsad') self.assertFalse(valid)
def test_validator(self): validator = Validator() with open(self.abs_file_path) as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') index = 0 for row in reader: index = index + 1 # skip title row and only check in use postcodes if index > 1 and row[1] == "Yes": valid = validator.validate(row[0]) self.assertTrue(valid)
def quiz(): """ Gets requested Quiz :param id: Quiz id :return: A json representation of a Quiz class :rtype: str :exception QuizNotFoundException: Thrown when getting a quiz that does not exist in the database """ if request.method == 'GET': try: id = request.args.get('_id') mquiz = db.get_quiz(id) if mquiz is None: e = QuizNotFoundException() app.logger.error(str(e)) return BaseExceptionSchema().dump(e), 400 return jsonify(mquiz), 200 except Exception as e: app.logger.error(str(e)) return BaseExceptionSchema().dump(e), 500 elif request.method == 'POST': """ Posts requested quiz :param _id: Quiz id :type _id: str :param responses: An array of string representing user choices :type responses: List :return result: Score user achieved on the quiz :rtype result: str :exception QuizNotFoundException: Thrown when submitting responses for a quiz that does not exist :exception InvalidResponsesException: Thrown when responses have invalid structures or at least one response does not exist in the options """ try: id = request.get_json()['_id'] responses = request.get_json()['responses'] quiz = db.get_quiz_internal(id) if quiz is None: e = QuizNotFoundException() app.logger.error(str(e)) return BaseExceptionSchema().dump(e), 400 validator = Validator(quiz, responses) if validator.validate(): db.insert_quiz_response(id, responses, validator.get_result) return jsonify(validator.get_result), 200 else: e = InvalidResponsesException() app.logger.error(str(e)) return BaseExceptionSchema().dump(e), 400 except Exception as e: app.logger.error(str(e)) return BaseExceptionSchema().dump(e), 500
def addBlock(self, block, proof): previous = self.lastBlock.currentHash if previous != block.previousHash: return False if not Validator.isValidProof(block, proof): return False block.currentHash = proof self.chain.append(block) return True
def test_validator(self): validator = Validator() valid = validator.validate('0898474635') self.assertTrue(valid) valid = validator.validate('0752781937') self.assertTrue(valid) validator = Validator() valid = validator.validate('0619871528') self.assertTrue(valid) valid = validator.validate('0549371528') self.assertFalse(valid)
def setup_train(config): model = get_model(config) optimizer = torch.optim.Adam(model.parameters(), lr=config.start_lr) lr_scheduler = CosineAnnealingLR(optimizer, T_max=config.optim_steps, eta_min=config.end_lr) logger = Logger(config) validator = Validator(config, logger) return model, optimizer, lr_scheduler, logger, validator
def test_validatorNum(self): self.validator.validate("None") self.assertFalse(self.validator.isValid) self.validator.validate("12a312") self.assertFalse(self.validator.isValid) self.validator.validate(True) self.assertFalse(self.validator.isValid) val = Validator() self.validator.validate(val) self.assertFalse(self.validator.isValid) self.validator.validate("1745438912") self.assertTrue(self.validator.isValid)
"Example of usage: python3 mlb_cg_generator.py 23/07/2020 --end_date 26/07/2020" ) parser.add_argument( "date", type=str, help="Expects the following format: day/month/year, e.g. 01/11/2020", ) parser.add_argument( "--end_date", type=str, help="Expects the following format: day/month/year, e.g. 01/11/2020", ) parser.add_argument( "--filter_by_team", type=str, help= 'Expects the full name: eg. "New York Yankees", "St. Louis Cardinals", etc.', ) parser.add_argument( "--run_checks", action="store_true", help= "If a lot of links fail, run this option. Use also for older dates. WARNING: Slow.", ) args = parser.parse_args() validator = Validator(args) validator.validate_args() main(args)
for input_file in inputs: if not os.path.isdir(args.output): output_file = args.output else: #formats for instance input50.in --> output50.out in output dir output_file = os.path.join( args.output, os.path.split(input_file)[1].replace('.in', '.out').replace( 'input', 'output')) f = anneal if args.anneal else solve #start functional processing num_guests, num_constraints, guests, constraints = read_input( input_file) solution = f(num_guests, num_constraints, guests, constraints) write_output(output_file, solution) satisfied, constraints_broken = Validator( solution, constraints).validate_solution() if not satisfied: print("Constraints broken were: {}".format(constraints_broken)) else: print("Success, {} solution was verified.".format(output_file)) """ ___________________________________________________________ Complete ___________________________________________________________ """
shape = prediction.shape if len(data[1]) == 155: file_name = "VSD.{}.{}".format(name, pat_id) pred_slice = np.argmax(np.array(data[1]), axis=3).astype(np.int16) mha_path = png_path = os.path.join(out_path_mha, "{}.mha".format(file_name)) ioutil.save_scan_as_mha(pred_slice, mha_path) if save_pngs: png_path = "{}.png".format(file_name) Validator.store_prediction( file_name, mode=TrainingModes.BRATS_SEGMENTATION, path=out_path_png, batch_x=np.array(data[0]), batch_y=np.array(data[0]), batch_tv=np.array(data[0]), prediction=np.array(data[1]), gt_is_one_hot=True) data = [[], []] ioutil.progress(i, int(data_iter.size / batch_size)) if len(data[1]) > 0: raise ValueError( "Something seems to be wrong with number of scans")
def test_validatorStrings(self): validator = Validator() validator.validate("") self.assertFalse(validator.isValid) validator = Validator() validator.validate(" ") self.assertFalse(validator.isValid) validator = Validator() validator.validate("8711a05v0f085") self.assertFalse(validator.isValid)
def test_validatorClass(self): validator = Validator() valid = validator.validate(validator) self.assertFalse(valid)
def test_validatorNone(self): validator = Validator() valid = validator.validate(None) self.assertFalse(valid)
class Tokens: def __init__(self): self.validator = Validator() self.has_comment = False def verify_composite(self, in_, col, token_list): if in_ != "": col_i = col - len(in_) token_list.append((col_i, col, self.validator.validate_lexem(in_))) in_ = "" return in_ def split_token(self, input: str) -> list: token_list = [] number = "" error = "" col = 0 previous_token = "" line_comment = input.find("//") for c in input: col += 1 if c == "{" or col == line_comment + 1: self.has_comment = True if previous_token not in ["", " ", "\t"]: token_type = self.validator.validate_lexem(previous_token) token_list.append((token_type, col, col + 1)) previous_token = "" continue elif c == "}" and self.has_comment: self.has_comment = False continue elif self.has_comment: continue # current_token = self.validator.validate_lexem(c) current_token = self.validator.validate_lexem(previous_token + c) # print("P:", previous_token+c) # print(current_token[previous_token+c]) if current_token[previous_token + c] is None and previous_token != "": # print("P:", previous_token) token_type = self.validator.validate_lexem(previous_token) # token_list.append(Token(previous_token, token_type[previous_token], col) token_list.append((token_type, col - len(previous_token), col)) previous_token = "" if c not in ["", " ", "\t"]: previous_token += c continue if c in ["", " ", "\t"]: continue previous_token += c # number=self.verify_composite(number, col, token_list) # error=self.verify_composite(error, col, token_list) # print("P:", previous_token) if previous_token not in ["", " ", "\t"]: token_type = self.validator.validate_lexem(previous_token) if len(previous_token) == 1: token_list.append((token_type, col, col + 1)) else: token_list.append( (token_type, col - len(previous_token) + 1, col + 1)) if line_comment != -1: self.has_comment = False return token_list def split_tokens(self, inputs: list) -> list: return [self.split_token(in_) for in_ in inputs] def generate_tokens(self, inputs: list) -> list: # [<TIPO_SIMPLES>, <IDENTIFIER>, <COMMA>, <IDENTIFIER>. <SINAL_IGUAL>] token_list = [] for token in inputs: token_type = self.validator.validate_token([*token_list, token[1]]) # print([*token_list, token]) token_list.append(token) # token_type = self.validator.validate_token(inputs) return token_list
def test_validatorValid(self): validator = Validator() validator.validate(" 8711205106085") self.assertTrue(validator.isValid) validator = Validator() validator.validate("8711205106085 ") self.assertTrue(validator.isValid) validator = Validator() validator.validate("8711205106085") self.assertTrue(validator.isValid)
def test_validatorInvalid(self): validator = Validator() validator.validate("7711205106085") self.assertFalse(validator.isValid)
class ValidatorTests(unittest.TestCase): def setUp(self): self.validator = Validator() def test_validatorNone(self): self.validator.validate(None) self.assertFalse(self.validator.isValid) def test_validatorNum(self): self.validator.validate("None") self.assertFalse(self.validator.isValid) self.validator.validate("12a312") self.assertFalse(self.validator.isValid) self.validator.validate(True) self.assertFalse(self.validator.isValid) val = Validator() self.validator.validate(val) self.assertFalse(self.validator.isValid) self.validator.validate("1745438912") self.assertTrue(self.validator.isValid) def test_validatorTrim(self): self.validator.validate(" 1745438912") self.assertTrue(self.validator.isValid) self.validator.validate("1745438912 ") self.assertTrue(self.validator.isValid) def test_validatorLen(self): self.validator.validate(" 1745438912") self.assertTrue(self.validator.isValid) self.validator.validate(" 174543812") self.assertFalse(self.validator.isValid) self.validator.validate("745438912") self.assertFalse(self.validator.isValid) self.validator.validate("1745438912") self.assertTrue(self.validator.isValid) def test_validator(self): # test remainder 10 self.validator.validate("1645418912") self.assertFalse(self.validator.isValid) # test remainder 11 self.validator.validate("1645418822") self.assertFalse(self.validator.isValid) def tearDown(self): self.validator = None
def setUp(self): self.validator = Validator()
import cv2 from src.validator import Validator Validator.init_angle_detector( '/home/lyan/PycharmProjects/face_detection/data/settings.json') camera_port = 0 ramp_frames = 30 camera = cv2.VideoCapture(camera_port) def get_image(): # read is the easiest way to get a full image out of a VideoCapture object. retval, im = camera.read() return im # Ramp the camera - these frames will be discarded and are only used to allow v4l2 # to adjust light levels, if necessary for i in xrange(ramp_frames): temp = get_image() print("Taking image...") while True: im = get_image() print Validator.validate(im) cv2.imshow('result', im) if cv2.waitKey(1) & 0xFF == ord('q'): break
def __init__(self): self.validator = Validator() self.has_comment = False
def __init__(self): self.moves = 0 Timer.__init__(self) Heuristics.__init__(self) Generator.__init__(self) Validator.__init__(self)