def handle_exception(error):
    ErrorHandler.handle_error('The server encounter a ValueError', error)
    return make_response(
        jsonify({
            'error':
            "The server could not process request, please check your input data"
        }), 400)
def handle_exception(error):
    ErrorHandler.handle_error('The server encountered an error', error)
    return make_response(
        jsonify({
            'error':
            "The server encountered an error and failed to process your request"
        }), 400)
Example #3
0
    def intChecker(self, line, leftType, rightType, op):
        if leftType != _int or rightType != _int:
            ErrorHandler.typeError(line, op)
            self.error()
            return _error

        return _int
Example #4
0
 def __config_vm_vulnerable_to_vms(self):
     """Configure the vm_vulnerable_to_vms
     Using all configurations, map each VM to all VMs that can potentially attack it
     """
     app.logger.info(f'initializing the vm_vulnerable_to_vms config')
     vm_vulnerable_to_vms = {}
     for vm in self.__vms_cfg:
         try:
             vm_id = vm["vm_id"]
             vm_vulnerable_to_vms[vm_id] = set()
             source_tags = set()
             for tag in vm["tags"]:
                 if tag in self.dtag_to_stag:
                     source_tags = source_tags.union(self.dtag_to_stag[tag])
             for source_tag in source_tags:
                 if source_tag in self.tag_to_vmid:
                     vm_vulnerable_to_vms[vm_id] = vm_vulnerable_to_vms[
                         vm_id].union(self.tag_to_vmid[source_tag])
         except KeyError as error:
             ErrorHandler.handle_error(
                 'KeyError: Error parsing data, skipping value', error)
             continue
     self.__vm_to_vms = vm_vulnerable_to_vms
     app.logger.info(
         f'Configured vm_vulnerable_to_vms: {vm_vulnerable_to_vms}')
Example #5
0
    def createType(self, line, typeName):
        type = symtab.Type(typeName, self.T)
        if not type.isValid():
            ErrorHandler.nameError(line, typeName)
            self.error()

        return type
Example #6
0
class TodoController(object):
    def __init__(self, filebase='todos'):
        self.error_handler = ErrorHandler()
        self.io_controller = IoController(filebase + '.csv')
        try:
            self.todos = self.io_controller.load()
        except FileNotFoundError:
            self.todos = []
            self.save()

    def list(self):
        views.list(self.todos)

    def add(self, desc):
        if desc == None:
            return views.error(self.error_handler.handle('add', 'No task is provided'))
        self.todos.append(Todo(desc))
        self.save()

    def remove(self, i):
        try:
            self.todos.remove(self.todos[int(i)])
            self.save()
        except Exception as e:
            views.error(self.error_handler.handle('remove', e))

    def check(self, i):
        try:
            self.todos[int(i)].toggle()
            self.save()
        except Exception as e:
            views.error(self.error_handler.handle('check', e))

    def save(self):
        self.io_controller.save(self.todos)
Example #7
0
    def visitMethodDecl(self, ctx: decafParser.MethodDeclContext):
        type = ctx.methodType().getText()
        name = ctx.ID().getText()

        type = self.createType(ctx.start.line, type)

        methodScope = symtab.MethodSymbol(name, type, self.currentScope)
        # Visit the parameters
        for param in ctx.parameter():
            symbol = self.visit(param)
            # Create the signature
            methodScope.args.append(symbol.type.name)

            # Define the parameters in the scope of the method
            if not methodScope.define(symbol):
                ErrorHandler.paramError(ctx.start.line, symbol.name, name)
                self.error()

        # Define the method in the current scope
        self.defineSymbol(ctx.start.line, self.currentScope, methodScope)
        # Set method scope as current scope
        self.currentScope = methodScope
        self.currentMethod = methodScope
        # Visit block
        self.visit(ctx.bl)
        # Save scope
        self.scopes[ctx] = self.currentScope
        # Exit scope
        self.exitScope()
Example #8
0
    def visitAsignStmt(self, ctx: decafParser.AsignStmtContext):
        leftType = self.visit(ctx.location())
        rightType = self.visit(ctx.expression())

        if not leftType == rightType:
            ErrorHandler.typeError(ctx.start.line, "=")
            self.error()
Example #9
0
 def __init__(self, file_name):
     self.file_name = file_name
     self.stack = Stack()
     self.stack.push("EOF")
     self.stack.push("Source")
     self.parser_table = PARSER_TABLE
     self.symbol_table = OOPSymbolTable()
     self.semantic_stack = Stack()
     self.memory_manager = MemoryManager(1000, 2000)
     self.scanner = Scanner(file_name, self.symbol_table)
     self.next_token = self.scanner.get_next_token()
     self.top_stack = self.stack.top()
     self.rule_number = None
     self.rule = ""
     self.grammar = GRAMMAR
     self.error_handler = ErrorHandler(self.scanner)
     self.symbol_table.set_error_handler(self.error_handler)
     self.semantic_analyzer = SemanticAnalyzer(self.symbol_table,
                                               self.memory_manager,
                                               self.semantic_stack,
                                               self.error_handler)
     self.code_generator = CodeGenerator(self.symbol_table,
                                         self.semantic_stack,
                                         self.memory_manager)
     self.current_identifier = None
     self.follow = FOLLOW
     self.non_terminal = 0
     self.must_get = False
Example #10
0
class PidController:
    def __init__(self, kp=7.0, Ti=155.0, Td=0.001):
        self._kp = kp
        self._Ti = Ti
        self._Td = Td
        self.error_handler_inst = ErrorHandler()
        self._control_signal = 0.0

    @property
    def control_signal(self):
        return self._control_signal

    @control_signal.setter
    def control_signal(self, value):
        self._control_signal = value

    def compute_control_signal(self, error, sampling_time):
        self.error_handler_inst.error_writing(error)
        self.error_handler_inst.compute_error_delta()
        control_signal_delta = self._kp * self.error_handler_inst.error_delta + error * sampling_time / self._Ti + self.error_handler_inst.error_delta_2 * self._Td / sampling_time
        self.control_signal = self.control_signal + control_signal_delta
        if self.control_signal > 12:
            self.control_signal = 12
        elif self.control_signal < -12:
            self.control_signal = -12
Example #11
0
    def condChecker(self, line, stmt, expr):
        if expr != _boolean:
            ErrorHandler.typeError(line, stmt, 2)
            self.error()
            return _error

        return _boolean
Example #12
0
 def __init__(self, file_name, symbol_table):
     self.symbolTable = symbol_table
     self.currentIndex = 0
     self.startTokenIndex = 0
     self.error_handler = ErrorHandler(self)
     input_file = open(file_name)
     self.inputCode = input_file.read()
     self.lastToken = None
Example #13
0
 def __init__(self, filebase='todos'):
     self.error_handler = ErrorHandler()
     self.io_controller = IoController(filebase + '.csv')
     try:
         self.todos = self.io_controller.load()
     except FileNotFoundError:
         self.todos = []
         self.save()
Example #14
0
    def visitLocation(self, ctx: decafParser.LocationContext):
        name = ctx.ID().getText()
        symbol = self.currentScope.resolve(name)

        if not symbol:
            ErrorHandler.nameError(ctx.start.line, name)
            self.error()
            return _error

        # Check if it is a built-in type
        builtIn = False
        if symbol.type.name in self.T.builtIn:
            builtIn = True

        if builtIn:
            # Declared as a variable
            if isinstance(symbol, symtab.VariableSymbol):
                if ctx.expr is not None:
                    ErrorHandler.typeError(ctx.start.line, symbol.name, 5)
                    self.error()

                if ctx.loc is not None:
                    ErrorHandler.attributeError(ctx.start.line, symbol.name,
                                                ctx.loc.getText())
                    self.error()

                return symbol.type.name

            # Declared as an array
            elif isinstance(symbol, symtab.ArraySymbol):
                try:
                    index = int(ctx.expr.getText())
                except ValueError:
                    index = None

                if (index is None) or (index < 0) or (index >= int(
                        symbol.num)):
                    ErrorHandler.arrayError(ctx.start.line, symbol.name, 2)
                    self.error()

                if ctx.loc is not None:
                    ErrorHandler.attributeError(ctx.start.line, symbol.name,
                                                ctx.loc.getText())
                    self.error()

                return symbol.type.name

        if not builtIn:
            # Save the actual scope
            actualScope = self.currentScope
            # Because it has a member, we declare the struct as the current scope
            self.currentScope = self.structs.get(symbol.type.name)
            # Visit location
            type = self.visit(ctx.loc)
            # Restore actual scope
            self.currentScope = actualScope
            # Return the type of the location
            return type
 def load_avro_schema_string(self, topic_name):
     if topic_name not in self.config_avro_location:
         raise ErrorHandler("Error. Application does not have avro schema for requested topic")
     try:
         with open(self.directory_avro_schemas + "/" + self.config_avro_location.get(topic_name),
                   'r') as schema_file:
             return schema_file.read().replace('\n', '')
     except Exception as e:
         raise ErrorHandler("Error. Unable to load schema: " + str(e))
Example #16
0
    def visitNegExp(self, ctx: decafParser.NegExpContext):
        exprType = self.visit(ctx.expression())

        if exprType != _boolean:
            ErrorHandler.typeError(ctx.start.line, '!')
            self.error()
            return _error

        return _boolean
Example #17
0
    def visitMinExp(self, ctx: decafParser.MinExpContext):
        exprType = self.visit(ctx.expression())

        if exprType != _int:
            ErrorHandler.typeError(ctx.start.line, '-')
            self.error()
            return _error

        return _int
Example #18
0
def replace_docx(path, old_str, new_str):
    doc = open_docx(path)
    # check none
    if not isinstance(old_str, str) or not isinstance(new_str, str):
        e = "the parameter in replace_docx must not be None"
        return ErrorHandler(path, e)
    # replace the string
    try:
        # paragraph processing
        for para in doc.paragraphs:
            # each para call  matchIndexs
            if old_str in para.text:
                matchedIndices = findMatchedIndices(para.text, 0, old_str)
                for i_matchIndex, matchIndex in enumerate(matchedIndices):
                    # make the instance of matchedRunObj
                    diff = len(new_str) - len(old_str)
                    updatedMatchedIndex = i_matchIndex * diff + matchIndex
                    matchedObj = MatchedRunObj(para, updatedMatchedIndex,
                                               old_str, new_str)
                    matchedObj.findRelatedRunIndex()
                    print("indexOfFirstMatchedChar: ",
                          matchedObj.indexOfFirstMatchedChar)
                    print("indexOfLastMatchedChar: ",
                          matchedObj.indexOfLastMatchedChar)
                    matchedObj.replaceString()

        # table processing
        for table in doc.tables:
            for r in table.rows:
                for cell in r.cells:
                    for para in cell.paragraphs:
                        if old_str in para.text:
                            matchedIndices = findMatchedIndices(
                                para.text, 0, old_str)
                            for i_matchIndex, matchIndex in enumerate(
                                    matchedIndices):
                                # make the instance of matchedRunObj
                                diff = len(new_str) - len(old_str)
                                updatedMatchedIndex = i_matchIndex * diff + matchIndex
                                matchedObj = MatchedRunObj(
                                    para, updatedMatchedIndex, old_str,
                                    new_str)
                                matchedObj.findRelatedRunIndex()
                                print("indexOfFirstMatchedChar: ",
                                      matchedObj.indexOfFirstMatchedChar)
                                print("indexOfLastMatchedChar: ",
                                      matchedObj.indexOfLastMatchedChar)
                                matchedObj.replaceString()
        # heading processing

        # save file in here
        doc.save('.\sample\ex2.docx')
    except AttributeError as e:
        errorObj = ErrorHandler(path, e)
        errorObj.showError()
        return errorObj
 def get_file_contents(cls, file_name: str):
     try:
         input_file = open(file_name, 'r')
         if input_file.mode == 'r':
             return input_file
         pass
     except FileNotFoundError:
         ErrorHandler.no_file_exit(file_name)
         pass
     finally:
         pass
     return None
Example #20
0
    def visitCondExp(self, ctx: decafParser.CondExpContext):
        op = ctx.op.getText()

        leftType = self.visit(ctx.left)
        rightType = self.visit(ctx.right)

        if leftType != _boolean or rightType != _boolean:
            ErrorHandler.typeError(ctx.start.line, op)
            self.error()
            return _error

        return _boolean
 def __export_file__(self, file_contents: str, suffix: str):
     error = None
     export_file_name = self.__get_export_file_name__(suffix)
     try:
         f = open(export_file_name, 'w+')
         f.write(file_contents)
         f.close()
     finally:
         if error:
             ErrorHandler.file_export_failed_exit(export_file_name, None)
         else:
             print('File exported: ' + export_file_name)
         pass
Example #22
0
    def visitReturnStmt(self, ctx: decafParser.ReturnStmtContext):
        methodType = self.currentMethod.type.name
        returnType = None

        if ctx.expression() is None:
            returnType = _void
        else:
            returnType = self.visit(ctx.expression())

        # Check that the return type is the same as the method type
        if returnType != methodType:
            ErrorHandler.returnError(ctx.start.line, methodType, returnType)
            self.error()
Example #23
0
    def visitArrayDecl(self, ctx: decafParser.ArrayDeclContext):
        varType = self.visit(ctx.varType())
        name = ctx.ID().getText()

        num = ctx.NUM().getText()
        # <NUM> in the declaration of an array must be greater than 0.
        if int(num) <= 0:
            ErrorHandler.arrayError(ctx.start.line, name)
            self.error()

        type = self.createType(ctx.start.line, varType)
        symbol = symtab.ArraySymbol(name, type, num)

        self.defineSymbol(ctx.start.line, self.currentScope, symbol)
Example #24
0
 def __retrieve_partition_data(self, topic):
     """
     Returns patition data for given topic.
     :param topic: string, name of topic being searched
     :return: confluent_kafka.TopicPartition()
     """
     if topic not in self.consumer_topic_list:
         raise ErrorHandler(
             "Application does not have access to requested topic: " +
             topic)
     try:
         return self.consumer_topic_list.get(topic).partitions
     except Exception as e:
         raise ErrorHandler("Error retrieving partition data: " + str(e))
Example #25
0
    def process_file_contents(cls, contents: TextIOWrapper) -> [FileContent]:

        all_file_contents: [FileContent] = []

        table_name_plural: str = ''
        field_list: [{str, str}] = []
        table_started: bool = False
        table_ended: bool = False

        for new_line in contents:
            line = new_line.lower()
            if 'create table' in line:
                split_array = line.replace('create table',
                                           '').strip().split(' ')
                table_started = True
                if len(split_array) > 1:
                    table_name_plural = split_array[0]
                    print('Table name : ' + table_name_plural)
                continue

            split_array = []
            if table_started:
                split_array = line.strip().split(' ')

            for text in split_array:
                if 'constraint' in line or ');' in line:
                    table_started = False
                    table_ended = True

            cls.add_field(field_list, line, table_started)

            if table_ended:
                if len(field_list) > 2:
                    table_name = field_list[0]["name"][:-3]
                    new_file_contents = FileContent(table_name,
                                                    table_name_plural,
                                                    field_list)
                    table_name_plural = ''
                    field_list = []
                    table_started = False
                    table_ended = False
                    all_file_contents.append(new_file_contents)
                else:
                    ErrorHandler.insufficient_table_fields(table_name_plural)

        if table_started:
            ErrorHandler.table_structure()

        return all_file_contents
Example #26
0
    def mainCheker(self, line, scope):
        symbol = None
        isMain = False

        for symbolName in scope.symbols:
            if symbolName == "main":
                symbol = scope.symbols.get(symbolName)
                break

        if isinstance(symbol, symtab.MethodSymbol):
            isMain = True

        if not isMain:
            ErrorHandler.nameError(line, "main()")
            self.error()
Example #27
0
 def convert_avro_msg(self, msg):
     try:
         return self.deserializer.__call__(msg.value(), self.serial_context)
     except Exception as e:
         raise ErrorHandler(
             "Error deserializing avro message. Check registry settings: " +
             str(e))
Example #28
0
 def __init__(self, environment):
     self.avro_deserializer = None
     try:
         self.consumer = ConsumerConnectionManager.initialize_kafka_consumer(
             environment)
         try:
             # Retrieve list of topics from KafkaConsumer(). timeout is set as float(10).
             # Timeout errors typically signify a connection error to kafka-broker.
             self.consumer_topic_list = self.consumer.list_topics(
                 timeout=float(10)).topics
         except Exception as e:
             raise ErrorHandler(
                 "Error retrieving list of available topics. Check Kafka connection settings. Error: "
                 + str(e))
     except Exception as e:
         raise ErrorHandler("Error initializing KafkaReader(): " + str(e))
    def __parse_incoming_request(cls, request):
        """
        Parse incoming request convert to dict()
        :return parsed_request dict()
        :rtype dict()
        """
        # Merges form(UI calls), args(Postman form-data) params
        parsed_request = {**request.form.to_dict(), **request.args.to_dict()}

        # Extract json_topics from splash.html if present
        json_topics = request.form.getlist(
            constants.REQUEST_UI_FORM_JSON_TOPICS_KEY)
        if len(json_topics) > 0:
            parsed_request[cls.request_json_topics_key] = json_topics
            parsed_request.pop(constants.REQUEST_UI_FORM_JSON_TOPICS_KEY)

        # Extract avro_topics from splash.html if present
        avro_topics = request.form.getlist(
            constants.REQUEST_UI_FORM_AVRO_TOPICS_KEY)
        if len(avro_topics) > 0:
            parsed_request[cls.request_avro_topics_key] = avro_topics
            parsed_request.pop(constants.REQUEST_UI_FORM_AVRO_TOPICS_KEY)

        # Support for JAVA JSON body requests
        if request.json:
            parsed_request = {**parsed_request, **request.json}

        # Support for POSTMAN raw JSON body requests
        if len(parsed_request) == 0:
            parsed_request = json.loads(request.data.decode())

        if len(parsed_request) == 0:
            raise ErrorHandler("Error parsing params")

        return parsed_request
    def __init__(self, error_callback=None):
        self.error_handler = ErrorHandler(error_callback)

        storage_name = Core.storage.abs_path(
            Core.storage.join_path(Core.bundle_path, 'Contents',
                                   'music.storage'))
        self.music_queue = PlexStorage(storage_name)
    def search(cls, params):
        response = {}
        # Start connection to queue manager
        try:
            queue_manager = QueueManager()
        except Exception as e:
            raise ErrorHandler(
                "Unable to connect to QueueManager, please try again. Error code: "
                + str(e))

        # Iterate through the search queue list and browse all messages,
        # returning all messages that match the search param
        for name in params.get('queue_list'):
            queue_suffix = params.get('queue_suffix')
            try:
                browser = MQReader(queue_manager, name,
                                   params.get('base_queues'), queue_suffix)
                found_msgs = browser.search_for_msgs(
                    params.get('search_string'), params.get('delimiter'),
                    params.get('not_before'))
                browser.close_browser_connection()
            except Exception as e:
                response["QUEUE___" + name + '.' +
                         queue_suffix] = "queue was unresponsive " + str(e)
                continue
            response["QUEUE___" + name + '.' + queue_suffix] = found_msgs

        # Close connection to queue manager
        try:
            queue_manager.close_manager_connection()
        except Exception as e:
            response[
                'ERROR'] = "ISSUE CLOSING QUEUE MANAGER error code: " + str(e)

        return response
Example #32
0
 def __init__(self, filebase='todos'):
     self.error_handler = ErrorHandler()
     self.io_controller = IoController(filebase + '.csv')
     try:
         self.todos = self.io_controller.load()
     except FileNotFoundError:
         self.todos = []
         self.save()
Example #33
0
class Main:
  
    bDebug = False
    bLog = False
    oServices = ''
    oErrorHandler = ''
    oHelpers = ''
    

    def __init__(self):
        self.oErrorHandler = ErrorHandler()
        self.oHelpers = Helpers()
   
    def run(self):
        """Check services for all servers configs data"""
        if self.validateServicesList():
            self.oServices = Services() #Create Services object
            for info in services.services_list:
                self.oServices.check(info)
            # show debug
            self.showDebugResult()
            # save logs 
            self.saveLogFile()

    def validateServicesList(self):
        """Validate if the services list not empty"""
        bResult=True
        if len(services.services_list) == 0:
            print self.oErrorHandler.displayError('cod-003', 'warning')
            bResult=False

        return bResult
        
      
    def showDebugResult(self):
        """ Show debug, first show Error, then Ok results"""
        if self.bDebug == True:
            for x in self.oServices.listDebugResultError:
                print x
  
            for x in self.oServices.listDebugResultOk:
                print x
        
        
    def saveLogFile(self):
      """Save result in log file"""
      if self.bLog:
	try:
	  fileLog = open('logs/log_'+self.oHelpers.getTimeToFileName(), 'w')
	  fileLog.seek(0)
	  fileLog.write("Fecha y Hora: "+self.oHelpers.getTimeToText()+"\r\n \r\n");
	  for result in self.oServices.listTextResultError:
	    fileLog.write(result)
	  for result in self.oServices.listTextResultOk:
	    fileLog.write(result)
	    
	  fileLog.close()
	except IOError:
	  print self.oErrorHandler.displayError('cod-005')

    def showHelp(self):
        """ Read the help file to show help's script"""
        try:
            sHelp = open('docs/help', 'r').read()
            print sHelp
        except:
            print self.oErrorHandler.displayError('cod-004')
 def _error_handler_default(self):
     eh = ErrorHandler()
     eh.logger = self
     return eh
Example #35
0
 def __init__(self):
     self.oErrorHandler = ErrorHandler()
     self.oHelpers = Helpers()