Example #1
0
    def parseRegexp(self, scanner):
        # leading '/' is already consumed
        rexp = ""
        in_char_class = False
        token = scanner.next()
        while True:
            rexp += token.value      # accumulate token strings

            # -- Check last token
            # character classes
            if token.value == "[":
                if not Scanner.is_last_escaped(rexp): # i.e. not preceded by an odd number of "\"
                    in_char_class = True
            elif token.value == "]" and in_char_class:
                if not Scanner.is_last_escaped(rexp):
                    in_char_class = False
            # check for termination of rexp
            elif rexp[-1] == "/" and not in_char_class:  # rexp[-1] != token.value if token.value == "//"
                if not Scanner.is_last_escaped(rexp):
                    break

            token = scanner.next()

        # regexp modifiers
        try:
            if scanner.peek()[0].name == "ident":
                token = scanner.next()
                rexp += token.value
        except StopIteration:
            pass

        return rexp
Example #2
0
def parseRegexp(scanner):
    # leading '/' is already consumed
    rexp = ""
    in_char_class = False
    token = scanner.next()
    while True:
        rexp += token.value  # accumulate token strings

        # -- Check last token
        # character classes
        if token.value == "[":
            if not Scanner.is_last_escaped(
                    rexp):  # i.e. not preceded by an odd number of "\"
                in_char_class = True
        elif token.value == "]" and in_char_class:
            if not Scanner.is_last_escaped(rexp):
                in_char_class = False
        # check for termination of rexp
        elif rexp[
                -1] == "/" and not in_char_class:  # rexp[-1] != token.value if token.value == "//"
            if not Scanner.is_last_escaped(rexp):
                break

        token = scanner.next()

    # regexp modifiers
    try:
        if scanner.peek()[0].name == "ident":
            token = scanner.next()
            rexp += token.value
    except StopIteration:
        pass

    return rexp
Example #3
0
def testParser(klienProgram):
    file = open(klienProgram, 'r')
    program = file.read()
    demoScanner = Scanner(program)
    demoScanner.scan(program)
    parser = Parser(demoScanner)
    return parser.parse()
Example #4
0
def Scan(stop_event, path):
    client = ipc.mailslot("client")
    exes = Scanner.find_exe(path)
    global flag
    flag = False
    total = len(exes)
    if total == 0:
        return
    percent = 100 / total
    progress = 1
    for exe in exes:
        progress += percent
        if not stop_event.wait(0.1):
            flag = True
            res = Scanner.scan(exe)
            try:
                client.put({
                    'progress': math.ceil(progress),
                    'exe': exe,
                    'infected': res,
                    'marker': 'scan'
                })
            except Exception:
                print('Клиент отключен')
                break
        else:
            break
Example #5
0
def upload_rules():
    file = request.files['file']

    if file == False or allowed_file(file.filename) == False:
        flash('Invalid File Upload Attempt')
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'csv_load':
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            Scanner.load_rules(
                os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            flash('CSV Scan Rules Loaded')
            return render_template('index.html')
    except:
        flash('CSV Rules Load Failed. Check Rules CSV file.' +
              str(sys.exc_info()))
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'zip_scan':
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            results = Scanner.scan_archive(
                os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            return render_template('report.html',
                                   results=results,
                                   filename=file.filename)
    except:
        flash('ZIP File Scan Failed.' + str(sys.exc_info()))
        return render_template('index.html')
Example #6
0
def upload_rules():
    file = request.files['file']

    if file == False or allowed_file(file.filename) == False:
        flash('Invalid File Upload Attempt')
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'csv_load':
            Scanner.load_rules(file)
            flash('CSV Scan Rules Loaded')
            return render_template('index.html')
    except:
        flash('CSV Rules Load Failed. Check Rules CSV file.')
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'zip_scan':
            results = Scanner.scan_archive(file)
            return render_template('report.html',
                                   results=results,
                                   filename=file.filename)
    except:
        flash('ZIP File Scan Failed.')
        return render_template('index.html')
 def __init__(self, source_text):
     self.scanner = Scanner(
         source_text)  # initialize the scanner with the source_text
     self.scanner.file_read()
     self.symbols = Symbols()  # initialise the Jack standard symbol table
     self.token_list = []
     self.endmark = "\0"
Example #8
0
    def test_cmp_lt(self):
        scanner = Scanner('a > b')
        scanner.lex()

        parser = Parser(scanner.tokens)
        ast = parser.expr()
        self.assertEqual(ast, test_asts['a > b'])
Example #9
0
def getChar():  # get the next character
    global c1, c2, character
    character = scanner.get()
    c1 = character.cargo
    # Every time we get a character from the scanner, we also
    # lookahead to the next character and save the results in c2.
    c2 = c1 + scanner.lookahead(1)
Example #10
0
    def return_results(self, print_to_console = False):
        box_config = self.box_config
        my_scan = Scanner.Scan(box_config)
        front_area = my_scan.front_area()
        net_volume = sum([stem.volume if stem.is_inside_of_the_box(box_config)
                          else 0 for stem in self.stems])
        gross_volume = front_area * box_config.depth
        out_of_box = [stem.is_inside_of_the_box(box_config)
                      for stem in self.stems].count(False)
        dislocated_any = [stem.is_dislocated(box_config) for stem in self.stems].count(True)
        dislocated_position = [stem.is_dislocated_by_position(box_config) for stem in self.stems].count(True)
        dislocated_angle = [stem.is_dislocated_by_angle() for stem in self.stems].count(True)
        if (front_area > 0):
            deflationfactor = net_volume / (front_area * box_config.depth)
        else:
            deflationfactor = "DivBy0Error"

        [front_face_area, back_face_area] = Scanner.face_area(self)
        duration = (self._finish_time - self._starting_time).total_seconds()

        if print_to_console == True:
            print("Out of Box: ", out_of_box, "  Defl.: ", deflationfactor)

        return [out_of_box, dislocated_any, dislocated_position, dislocated_angle,
                front_area, gross_volume, net_volume, deflationfactor,
                my_scan.back_area(), front_face_area, back_face_area, my_scan.box_overflow,
                duration, self.waited_loops, self._tics_count]
Example #11
0
 def duplexScan(self):
     self.setScanning(True)
     self.scan = Scanner(self)
     self.scan.setDuplex(True)
     self.connect(self.scan, SIGNAL('scanned(QImage)'), self.scanned)
     self.connect(self.scan, SIGNAL('error(int)'), self.error)
     self.connect(self.scan, SIGNAL('finished()'), self.finished)
     self.scan.startScan()
Example #12
0
 def testValidId(self):
     testProgram = "A_valid_Id_123"
     answer = [
         Token(TokenType.identifier, "A_valid_Id_123"),
         Token(TokenType.eof)
     ]
     scanner = Scanner(testProgram)
     self.assertEqual(scanner.scan(testProgram), answer)
 def front(self):
     global front_addr
     front_addr,_ = QFileDialog.getOpenFileName(self,'Open File','',"Image files(*.jpg *.png *.jpeg)")#load file ảnh từ máy tính
     Scanner.scan(front_addr,"front")  #đầu vào là ảnh, tiến hành cắt các cạnh trả về là hình ảnh temp_back ở thư mục cùng cấp
     #front_addr = str(front_addr)[2:str(front_addr).find(',')-1]
     pixmap = QPixmap("temp_front.jpg") # đặt ảnh cho pixmap
     self.label_imgf.setPixmap(pixmap)  #hiện thị hình ảnh lên cửa sổ
     self.label_imgf.setScaledContents(True) # đặt hình ảnh vừa với tỉ lệ của khung
Example #14
0
 def __init__(self, log_flag):
     ## Logger object for formatting and printing logs
     self.logger = Logger(log_flag, LOG_FILE)
     self.logger.info('Started Domoleaf Slave daemon')
     ## Array of master daemon on local network
     self.connected_masters = {}
     ## Array of monitor KNX on local network
     self.connected_knx = []
     ## Array of monitor EnOcean on local network
     self.connected_enocean = []
     ## Array of cron running on the system
     self.connected_cron = []
     self._scanner = Scanner(log_flag)
     self._hostlist = []
     myhostname = socket.gethostname().upper()
     if SLAVE_NAME_PREFIX in myhostname:
         self._scanner.scan()
         self._hostlist = self._scanner._HostList
     else:
         self._hostlist.append(Host('', '127.0.0.1', myhostname))
     self._parser = DaemonConfigParser(SLAVE_CONF_FILE)
     ## Keys for encrypting communications
     self.encrypt_keys = {}
     ## Main socket for communication with KNX daemon
     self.knx_sock = None
     ## Main socket for communication with master daemon
     self.master_sock = None
     ## Main socket for communication with enocean daemon
     self.enocean_sock = None
     ## Main socket for communication with cron
     self.cron_sock = None
     ## Private AES key got from configuration file
     self.private_aes = self._parser.getValueFromSection(
         'personnal_key', 'aes')
     self.wifi_init(self._parser.getValueFromSection('wifi', 'ssid'),
                    self._parser.getValueFromSection('wifi', 'password'),
                    self._parser.getValueFromSection('wifi', 'encryption'),
                    self._parser.getValueFromSection('wifi', 'mode'), 0)
     ## Port on which connect got from configuration file
     self.connect_port = self._parser.getValueFromSection(
         SLAVE_CONF_CONNECT_SECTION, SLAVE_CONF_CONNECT_PORT_ENTRY)
     ## Callback array indexed on packet type
     self.functions = {
         KNX_READ_REQUEST: self.knx_read_request,
         KNX_WRITE_SHORT: self.knx_write_short,
         KNX_WRITE_LONG: self.knx_write_long,
         KNX_WRITE_TEMP: self.knx_write_temp,
         CHECK_SLAVE: self.check_slave,
         MONITOR_IP: self.monitor_ip,
         DATA_UPDATE: self.update,
         SEND_TECH: self.send_tech,
         SEND_ALIVE: self.send_alive,
         SEND_INTERFACES: self.send_interfaces,
         SHUTDOWN_D3: self.shutdown_d3,
         REBOOT_D3: self.reboot_d3,
         WIFI_UPDATE: self.wifi_update
     }
Example #15
0
def initialize(textFile):

    global scanner

    # initialize the scanner with the textFile
    scanner.initialize(textFile)

    # use the scanner to read the first character from the textFile
    getChar()
Example #16
0
 def initRequiedVariables(self):
     self.attacked = False
     '''self.JsInjectAtacked=False'''
     self.systemLinux = SystemLinux(self)
     #inicjalizacja, że nie jest zaznaczony żaden host
     self.selected = 0
     self.sc = Scanner()
     self.sqlHandler = SqlHandler()
     self.hosts = []
Example #17
0
 def front(self):
     global front_addr
     front_addr, _ = QFileDialog.getOpenFileName(
         self, 'Open File', '', "Image files(*.jpg *.png *.jpeg)")
     Scanner.scan(front_addr, "front")
     #front_addr = str(front_addr)[2:str(front_addr).find(',')-1]
     pixmap = QPixmap("temp_front.jpg")
     self.label_imgf.setPixmap(pixmap)
     self.label_imgf.setScaledContents(True)
 def back(self):  #như trên
     global back_addr
     back_addr,_ = QFileDialog.getOpenFileName(self,'Open File','',"Image files(*.jpg *.png *.jpeg)")
     Scanner.scan(back_addr,"back")
     #back_addr = str(back_addr)[2:str(back_addr).find(',')-1]
     pixmap = QPixmap("temp_back.jpg")
     
     self.label_imgb.setPixmap(pixmap)
     self.label_imgb.setScaledContents(True)
Example #19
0
 def testNoWhiteSpace(self):
     testProgram = "3/5"
     answer = [
         Token(TokenType.number, 3),
         Token(TokenType.operator, "/"),
         Token(TokenType.number, 5),
         Token(TokenType.eof)
     ]
     scanner = Scanner(testProgram)
     self.assertEqual(scanner.scan(testProgram), answer)
Example #20
0
 def __init__(self, launcher):
     threading.Thread.__init__(self)
     self.face_cascade = cv2.CascadeClassifier(FACE_CASCADE_PATH)
     self.turretOn = False
     self.launcher = launcher
     self.trackingOn = False
     self.imageReady = threading.Event()
     self.scanner = Scanner(launcher)
     self.img = None
     self.outline = None
Example #21
0
    def __init__(self, sourceText, verbose=False):
        """
    """
        # Init the scanner
        self.scanner = Scanner(sourceText, verbose)
        self.ENDMARK = self.scanner.ENDMARK
        # Read first char
        self.getChar()

        self.verbose = verbose
Example #22
0
 def __init__(self):
     self.type_length_dict = {'integer': 4, 'float': 4, 'char': 1}
     self.Dict = {}
     self.position = 0  #标识符在符号表中的位置
     filename = 'example.txt'
     src_filename = 'result.txt'
     Key = ['program', 'var', 'integer', 'float', 'char', 'begin', 'end']
     Symbol = [',', ':', ';', ':=', '*', '/', '+', '-', '.', '(', ')']
     self.Scan = Scanner(filename, src_filename, Key, Symbol)
     self.Scan.output_result()
     self.Strings = self.Scan.strings[::-1]
Example #23
0
def scan(fn):
    f = ReadFile(fn)
    scanner = Scanner(f)
    while True:
        token_data = scanner.next_token()
        # print(token_data)
        if token_data:
            print_token(token_data)

            if token_data[2] == ENDFILE_TYPE:
                break
Example #24
0
class Main:
    def __init__(self):
        self.st = SymbolTable(17)
        self.pif = PIF()
        self.scanner = Scanner()

    def run(self):
        readFile()
        fileName = "p1.txt"
        exceptionMessage = ""

        with open(fileName, 'r') as file:
            lineCounter = 0
            for line in file:
                lineCounter += 1
                tokens = self.scanner.tokenize(line.strip())
                extra = ''
                for i in range(len(tokens)):
                    if tokens[i] in reservedWords + separators + operators:
                        if tokens[i] == ' ':  # ignore adding spaces to the pif
                            continue
                        self.pif.add(tokens[i], (-1, -1))
                    elif tokens[
                            i] in self.scanner.cases and i < len(tokens) - 1:
                        if re.match("[1-9]", tokens[i + 1]):
                            self.pif.add(tokens[i][:-1], (-1, -1))
                            extra = tokens[i][-1]
                            continue
                        else:
                            exceptionMessage += 'Lexical error at token ' + tokens[
                                i] + ', at line ' + str(lineCounter) + "\n"
                    elif self.scanner.isIdentifier(tokens[i]):
                        id = self.st.add(tokens[i])
                        self.pif.add("id", id)
                    elif self.scanner.isConstant(tokens[i]):
                        const = self.st.add(extra + tokens[i])
                        extra = ''
                        self.pif.add("const", const)
                    else:
                        exceptionMessage += 'Lexical error at token ' + tokens[
                            i] + ', at line ' + str(lineCounter) + "\n"

        with open('symboltable.out', 'w') as writer:
            writer.write(str(self.st))

        with open('pif.out', 'w') as writer:
            writer.write(str(self.pif))

        if exceptionMessage == '':
            print("Lexically correct")
        else:
            print(exceptionMessage)
Example #25
0
 def __init__(self, filename):
     import Scanner
     f = open(filename)
     string = f.read()
     string.replace('\t', ' ')
     file_without_comment = Scanner.remove_comments(string)
     scanner = Scanner.Scanner(file_without_comment)
     scanner.next()
     self.rules = []
     self.functions = []
     self.function_map = {}
     self.parse_rules(scanner)
     f.close()
Example #26
0
    def __init__(self, sourceFileName, outputFileName, verbose=False):
        self.sourceFileName = sourceFileName
        f = open(sourceFileName, "r")
        self.sourceText = f.read()
        f.close()

        if os.path.exists(outputFileName):
            os.remove(outputFileName)

        self.outputFile = open(outputFileName, "a")
        self.scanner = Scanner(self.sourceText, verbose)
        self.lexer = Lexer(self.sourceText, verbose)
        self.parser = Parser(self.sourceText, self.outputFile, verbose)
        self.verbose = verbose
Example #27
0
    def common(self, expr, expect):
        scanner = Scanner(expr)
        scanner.lex()

        parser = Parser(scanner.tokens)
        ast = parser.parse()

        eval_visitor = ASTEvalVisitor()
        res = eval_visitor.eval(ast)

        disp_visitor = ASTDisplayVisitor()
        disp_visitor.display(ast)

        self.assertEqual(res, expect)
Example #28
0
def load_rules():

    file = request.files['file']
    if file == False or allowed_file(file.filename) == False:
        return Response(status=500, mimetype='application/json')

    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(file_path)
        Scanner.load_yaml_rules(file_path)
        return Response(status=200, mimetype='application/json')
    except Exception as e:
        logging.error(e)
        return Response(status=500, mimetype='application/json')
Example #29
0
def main():
    filename = 'input.txt'
    pifFile = 'PIF.txt'
    stFile = 'SymbolTable.txt'

    print(codificationTable)

    symbolTable = SymbolTable()
    pif = ProgramInternalForm()
    fileManipulator = FileManipulator(filename, pifFile, stFile)
    scanner = Scanner(pif, symbolTable, fileManipulator)

    fileManipulator.readFromFile(scanner)
    scanner.scan(filename)
def load_rules():

    file = request.files['file']
    if file == False or allowed_file(file.filename) == False:
        return Response(status=500, mimetype='application/json')

    try:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(file_path)
        Scanner.load_yaml_rules(file_path)
        return Response(status=200, mimetype='application/json')
    except Exception as e:
        logging.error(e)
        return Response(status=500, mimetype='application/json')
Example #31
0
    def cmp_ast(self, expr, expect):
        scanner = Scanner(expr)
        scanner.lex()

        parser = Parser(scanner.tokens)
        ast = parser.parse()

        # eval_visitor = ASTEvalVisitor()
        # res = eval_visitor.eval(ast)

        # disp_visitor = ASTDisplayVisitor()
        # disp_visitor.display(ast)

        self.assertEqual(ast, expect)
Example #32
0
def get_found_leaders_list(interface_name):
    found_leaders = []

    s = Scanner()
    results = s.start_scan(interface_name)
    #if no error occurred, parse and decode scan results
    if not results[0]:
        found_leaders = s.parse_scan_results(results[2])
    if_to_mac = netifaces.ifaddresses(interface_name)[
        netifaces.AF_LINK][0]["addr"]
    return {
        'error_message': results[1],
        'found_leaders': found_leaders,
        "used_mac": if_to_mac
    }
Example #33
0
def load_rules(rule_file):
    '''Directly calls :class:`parse_rules` whose scanner acts on rule_file read as a string. 

    :param rule_file: (str) path to rules file
    :returns: (list) classes, (list) lexes
    '''
    f = open(rule_file)
    string = f.read()
    string.replace('\t', ' ')
    file_without_comment = Scanner.remove_comments(string)
    scanner = Scanner.Scanner(file_without_comment)
    scanner.next()
    classes, lexes = parse_rules(scanner)
    f.close()
    return classes, lexes
Example #34
0
 def __init__(self, log_flag):
     self.logger = Logger(log_flag, LOG_FILE);
     self.logger.info('Started Greenleaf Slave daemon');
     print('######## SLAVE DAEMON #######')
     self.connected_masters = {};
     self.connected_knx = [];
     self.connected_enocean = [];
     self.clients = [];
     self._scanner = Scanner(HOST_CONF_FILE);
     self._scanner.scan(False);
     self._hostlist = self._scanner._HostList;
     self._parser = DaemonConfigParser(SLAVE_CONF_FILE);
     self.encrypt_keys = {};
     self.knx_sock = None;
     self.master_sock = None;
     self.enocean_sock = None;
     self.private_aes = hashlib.md5(self._parser.getValueFromSection('personnal_key', 'aes').encode()).hexdigest();
     self.functions = {
         KNX_READ_REQUEST    : self.knx_read_request,
         KNX_WRITE_SHORT     : self.knx_write_short,
         KNX_WRITE_LONG      : self.knx_write_long,
         KNX_WRITE_TEMP      : self.knx_write_temp,
         CHECK_SLAVE         : self.check_slave,
         MONITOR_IP          : self.monitor_ip,
         DATA_UPDATE         : self.update
     };
Example #35
0
class IOManager(object):
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
        #set up connections and variables for button, light, printer, and scanner
    def getButton(self):
        return self.__button.getButtonBool()

    def getScan(self):
        return self.__scanner.getInput()

    def setLight(self, value):
        self.__led.setValue(value)

    def blinkLight(self):
        self.__led.blink()
        
    def printReceipt(self, items):
        if items:
            self.__printer.printHeader()
            for item in items:
                self.__printer.printItem(item)
            self.__printer.printTotals(items)
            self.__printer.complete()
def main():
    """
    Assume we pass this script the image file path as an argument on the
    command line.
    """

    usage = 'usage: %prog [options] imagefile'

    parser = OptionParser(usage=usage)
    parser.add_option('--chunksize', action='store', type='int',
                      dest='chunk_size', default=2048)
    parser.add_option('--oobsize', action='store', type='int',
                      dest='oob_size', default=64)

    options, args = parser.parse_args()

    if len(args) != 1:
        print "Incorrect command line arguments. Missing (or too many) image files"
        return 1

    image = args[0]

    headers = Scanner.get_anchor_headers(image, options.chunk_size,
                                         options.oob_size, 'contacts2.db')

    oobs = YaffsParser.get_oob_bytes(image, headers, options.oob_size)

    for oob in oobs:
        sys.stdout.write(oob)

        #Separate each oob with 16 'X' Bytes.
        sys.stdout.write('X'*16)
Example #37
0
def NetworkSniff():

    sayac = 0

    ip = input("İp aralığını giriniz : ")

    hedef_bilgileri = Scanner.NetworkTara(ip)

    HedefIp = hedef_bilgileri[0]
    HedefMac = hedef_bilgileri[1]
    GateWayIp = hedef_bilgileri[2]
    GateWayMac = hedef_bilgileri[3]

    try:
        while True:
            ArpPois0n.arp_zehirle(HedefIp,GateWayIp,HedefMac)
            ArpPois0n.arp_zehirle(GateWayIp,HedefIp,GateWayMac)

            sayac += 2

            print("\rGiden Paketler " + str(sayac),end="")

            time.sleep(3)

    except KeyboardInterrupt:

        print("CTRL + C Algilandi programdan cikiliyor!")
        Temizle()
        exit(0)
Example #38
0
 def __init__(self, log_flag):
     self.logger = Logger(log_flag, LOG_FILE);
     self.logger.info('Started Domoleaf Slave daemon');
     print('######## SLAVE DAEMON #######')
     self.connected_masters = {};
     self.connected_knx = [];
     self.connected_enocean = [];
     self.connected_cron = [];
     self.clients = [];
     self._scanner = Scanner(HOST_CONF_FILE);
     self._scanner.scan(False);
     self._hostlist = self._scanner._HostList;
     self._parser = DaemonConfigParser(SLAVE_CONF_FILE);
     self.encrypt_keys = {};
     self.knx_sock = None;
     self.master_sock = None;
     self.enocean_sock = None;
     self.cron_sock = None;
     self.private_aes = hashlib.md5(self._parser.getValueFromSection('personnal_key', 'aes').encode()).hexdigest();
     self.wifi_init(self._parser.getValueFromSection('wifi', 'ssid'), self._parser.getValueFromSection('wifi', 'password'), self._parser.getValueFromSection('wifi', 'encryption'), self._parser.getValueFromSection('wifi', 'mode'), 0);
     self.functions = {
         KNX_READ_REQUEST    : self.knx_read_request,
         KNX_WRITE_SHORT     : self.knx_write_short,
         KNX_WRITE_LONG      : self.knx_write_long,
         KNX_WRITE_TEMP      : self.knx_write_temp,
         CHECK_SLAVE         : self.check_slave,
         MONITOR_IP          : self.monitor_ip,
         DATA_UPDATE         : self.update,
         SEND_TECH           : self.send_tech,
         SEND_ALIVE          : self.send_alive,
         SEND_INTERFACES     : self.send_interfaces,
         SHUTDOWN_D3         : self.shutdown_d3,
         REBOOT_D3           : self.reboot_d3,
         WIFI_UPDATE         : self.wifi_update
     };
Example #39
0
    def parseStream(self, content, uniqueId=""):
        self.out_stream = []
        self.uniqueId = uniqueId
        self.line = self.column = 1
        self.sol = 0  # index of start-of-line
        self.scanner = scanner = Scanner.LQueue(tokens_2_obj(content, ))
        scanner.content = content
        scanner.slice = scanner_slice

        # set up internal Token stream
        self.token_pipe = LQueue(self.parseToken())

        for token in self.token_pipe:
            # delayed property settings on tokens (because they need peek ahead in Token stream)
            if token['type'] == 'comment':
                if self.restLineIsEmpty(self.token_pipe):
                    token['end'] = True  # last non-white token on line
                else:
                    token['end'] = False
                if token['end'] and not token['begin']:
                    token['connection'] = "after"
                else:
                    token['connection'] = "before"
            self.out_stream.append(token)

        return self.out_stream
Example #40
0
def parseString(scanner, sstart):
    # parse string literals
    result = ""
    for token in scanner:
        result += token.value
        if token.value == sstart and not Scanner.is_last_escaped(result):  # be aware of escaped quotes
            break
    return result
Example #41
0
	def processSCAN2Phase(self, tran, obj, data):
		# compute scanner for all objects on the map
		playerMap = Scanner.computeMap(self, tran, obj)
		# distribute map
		for playerID, map in playerMap.iteritems():
			player = tran.db[playerID]
			self.cmd(player).mergeScannerMap(tran, player, map)
		return
Example #42
0
	def duplexScan(self):
		self.setScanning( True )
                self.scan = Scanner(self)
		self.scan.setDuplex( True )
                self.connect( self.scan, SIGNAL('scanned(QImage)'), self.scanned )
		self.connect( self.scan, SIGNAL('error(int)'), self.error )
		self.connect( self.scan, SIGNAL('finished()'), self.finished )
                self.scan.startScan()
Example #43
0
 def __init__(self, log_flag):
     ## Logger object for formatting and printing logs
     self.logger = Logger(log_flag, LOG_FILE)
     self.logger.info("Started Domoleaf Slave daemon")
     ## Array of master daemon on local network
     self.connected_masters = {}
     ## Array of monitor KNX on local network
     self.connected_knx = []
     ## Array of monitor EnOcean on local network
     self.connected_enocean = []
     ## Array of cron running on the system
     self.connected_cron = []
     self._scanner = Scanner(log_flag)
     self._hostlist = []
     myhostname = socket.gethostname().upper()
     if SLAVE_NAME_PREFIX in myhostname:
         self._scanner.scan()
         self._hostlist = self._scanner._HostList
     else:
         self._hostlist.append(Host("", "127.0.0.1", myhostname))
     self._parser = DaemonConfigParser(SLAVE_CONF_FILE)
     ## Keys for encrypting communications
     self.encrypt_keys = {}
     ## Main socket for communication with KNX daemon
     self.knx_sock = None
     ## Main socket for communication with master daemon
     self.master_sock = None
     ## Main socket for communication with enocean daemon
     self.enocean_sock = None
     ## Main socket for communication with cron
     self.cron_sock = None
     ## Private AES key got from configuration file
     self.private_aes = self._parser.getValueFromSection("personnal_key", "aes")
     self.wifi_init(
         self._parser.getValueFromSection("wifi", "ssid"),
         self._parser.getValueFromSection("wifi", "password"),
         self._parser.getValueFromSection("wifi", "encryption"),
         self._parser.getValueFromSection("wifi", "mode"),
         0,
     )
     ## Port on which connect got from configuration file
     self.connect_port = self._parser.getValueFromSection(SLAVE_CONF_CONNECT_SECTION, SLAVE_CONF_CONNECT_PORT_ENTRY)
     ## Callback array indexed on packet type
     self.functions = {
         KNX_READ_REQUEST: self.knx_read_request,
         KNX_WRITE_SHORT: self.knx_write_short,
         KNX_WRITE_LONG: self.knx_write_long,
         KNX_WRITE_TEMP: self.knx_write_temp,
         CHECK_SLAVE: self.check_slave,
         MONITOR_IP: self.monitor_ip,
         DATA_UPDATE: self.update,
         SEND_TECH: self.send_tech,
         SEND_ALIVE: self.send_alive,
         SEND_INTERFACES: self.send_interfaces,
         SHUTDOWN_D3: self.shutdown_d3,
         REBOOT_D3: self.reboot_d3,
         WIFI_UPDATE: self.wifi_update,
     }
Example #44
0
 def parseCommentM(self, scanner):
     res = []
     while True:
         token = scanner.next(r'\*/')  # inform the low-level scanner to switch to commentM
         res.append(token.value)
         if not Scanner.is_last_escaped(token.value):
             break
         # run-away comments bomb in the above scanner.next()
     return u"".join(res)
Example #45
0
def networkScan( scheduler ):
	logging.info('Scanning Network')
	scan = Scanner.scanNetwork( mac=config.get('ScannerProperties','target'),
					 network=config.get('ScannerProperties','network'))
	if (scan == 1):
		SqliteHandler.logConnection()
		logging.info('Connection Logged')
	scheduler.enter(60,1,networkScan,(scheduler, ))
	return
Example #46
0
 def parseString(self, scanner, sstart):
     # parse string literals
     result = []
     while True:
         part = scanner.next(sstart)
         result.append(part.value)
         if not Scanner.is_last_escaped(part.value):  # be aware of escaped quotes
             break
         # run-away strings bomb in the above scanner.next()
     return u"".join(result)
Example #47
0
  def __init__(self, sourceText, verbose=False):
    """
    """
    # Init the scanner
    self.scanner = Scanner(sourceText, verbose)
    self.ENDMARK = self.scanner.ENDMARK
    # Read first char
    self.getChar()

    self.verbose = verbose
def scan():
    file = request.files['file']
    if file == False or allowed_file(file.filename) == False:
        return Response(status=500, mimetype='application/json')

    try:
        if not os.path.exists(app.config['UPLOAD_FOLDER']):
            os.makedirs(app.config['UPLOAD_FOLDER'])

        if (len(Scanner.rulebase) == 0):
            Scanner.load_yaml_rules(os.path.join(app.static_folder, 'default-rulebase.yml'))

        file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        results = Scanner.scan_archive(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        return Response(json.dumps(results, cls=JSONEncoderModels), mimetype='application/json')

    except Exception as e:
        logging.error(e)
        return Response(status=500, mimetype='application/json')
Example #49
0
	def __init__(self, launcher):
		threading.Thread.__init__(self)
		self.face_cascade = cv2.CascadeClassifier(FACE_CASCADE_PATH)
		self.turretOn = False
		self.launcher = launcher
		self.trackingOn = False
		self.imageReady = threading.Event()
		self.scanner = Scanner(launcher)
		self.img = None
		self.outline = None
Example #50
0
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
Example #51
0
 def parseCommentM(self, scanner):
     res = []
     try:
         while True:
             token = scanner.next(r'\*/')  # inform the low-level scanner to switch to commentM
             res.append(token.value)
             if not Scanner.is_last_escaped(token.value):
                 break
     except StopIteration:
         raise SyntaxException("Unterminated multi-line comment:\n '%s'" % u''.join(res))
     return u"".join(res)
Example #52
0
 def processSCAN2Phase(self, tran, obj, data):
     # data == True means forced scan (first after generating the galaxy)
     if not obj.timeEnabled and not data:
         return
     # compute scanner for all objects on the map
     playerMap = Scanner.computeMap(self, tran, obj)
     # distribute map
     for playerID, map in playerMap.iteritems():
         player = tran.db[playerID]
         self.cmd(player).mergeScannerMap(tran, player, map)
     return
Example #53
0
 def __init__(self, log_flag):
     self.logger = Logger(log_flag, LOG_FILE);
     self.logger.info('Started Greenleaf Master Daemon');
     self.d3config = {};
     self.aes_slave_keys = {};
     self.aes_master_key = None;
     self.connected_clients = {};
     self.sql = MasterSql();
     self._parser = DaemonConfigParser(MASTER_CONF_FILE);
     self.get_aes_slave_keys();
     self.reload_camera(None, None);
     self.scanner = Scanner(HOSTS_CONF);
     self.scanner.scan(False);
     self.hostlist = self.scanner._HostList;
     self.sql.insert_hostlist_in_db(self.scanner._HostList);
     self.knx_manager = KNXManager(self.aes_slave_keys);
     self.reload_d3config(None, None);
     self.protocol_function = {
         PROTOCOL_KNX        : KNXManager.protocol_knx,
         PROTOCOL_ENOCEAN    : self.protocol_enocean,
         PROTOCOL_IP         : self.protocol_ip
     };
     self.upnp_function = {
         UPNP_PLAY           : self.upnp_set_play,
         UPNP_PAUSE          : self.upnp_set_pause,
         UPNP_NEXT           : self.upnp_set_next,
         UPNP_PREVIOUS       : self.upnp_set_prev,
         UPNP_STOP           : self.upnp_set_stop,
         UPNP_VOLUME_UP      : self.upnp_set_volume_up,
         UPNP_VOLUME_DOWN    : self.upnp_set_volume_down,
         UPNP_SET_VOLUME     : self.upnp_set_volume
     };
     self.enocean_function = {};
     self.data_function = {
         DATA_MONITOR_KNX            	  : self.monitor_knx,
         DATA_MONITOR_IP             	  : self.monitor_ip,
         DATA_MONITOR_ENOCEAN        	  : self.monitor_enocean,
         DATA_MONITOR_BLUETOOTH      	  : self.monitor_bluetooth,
         DATA_KNX_READ               	  : self.knx_read,
         DATA_KNX_WRITE_S            	  : self.knx_write_short,
         DATA_KNX_WRITE_L            	  : self.knx_write_long,
         DATA_SEND_TO_DEVICE         	  : self.send_to_device,
         DATA_CRON_UPNP             		  : self.cron_upnp,
         DATA_SEND_MAIL              	  : self.send_mail,
         DATA_CHECK_SLAVE            	  : self.check_slave,
         DATA_RELOAD_CAMERA          	  : self.reload_camera,
         DATA_RELOAD_D3CONFIG        	  : self.reload_d3config,
         DATA_BACKUP_DB_CREATE_LOCAL       : self.backup_db_create_local,
         DATA_BACKUP_DB_REMOVE_LOCAL       : self.backup_db_remove_local,
         DATA_BACKUP_DB_LIST_LOCAL         : self.backup_db_list_local,
         DATA_BACKUP_DB_RESTORE_LOCAL      : self.backup_db_restore_local,
         DATA_UPDATE                 	  : self.update
     };
Example #54
0
 def parseString(self, scanner, sstart):
     # parse string literals
     result = []
     try:
         while True:
             part = scanner.next(sstart)
             result.append(part.value)
             if not Scanner.is_last_escaped(part.value):  # be aware of escaped quotes
                 break
     except StopIteration:
         raise SyntaxException("Unterminated string: '%s'" % u''.join(result))
     return u"".join(result)
Example #55
0
def parseCommentM(scanner):
    result = []
    res = u""
    for token in scanner:
        result.append(token.value)
        if token.value == "*/":
            res = u"".join(result)
            if not Scanner.is_last_escaped(res):
                break
    else:
        res = u"".join(result)

    return res
Example #56
0
def upload_rules():
    file = request.files['file']

    if file == False or allowed_file(file.filename) == False:
        flash('Invalid File Upload Attempt')
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'csv_load':
            Scanner.load_rules(file)
            flash('CSV Scan Rules Loaded')
            return render_template('index.html')
    except:
        flash('CSV Rules Load Failed. Check Rules CSV file.')
        return render_template('index.html')

    try:
        if request.form.get('submitbtn') == 'zip_scan':
            results = Scanner.scan_archive(file)
            return render_template('report.html', results=results, filename=file.filename)
    except:
        flash('ZIP File Scan Failed.')
        return render_template('index.html')
def load_rules(rule_file):
    '''Directly calls :class:`parse_rules` whose scanner acts on rule_file read as a string. 

    :param rule_file: (str) path to rules file
    :returns: (list) classes, (list) lexes
    '''
    f = open(rule_file)
    string = f.read()
    string.replace('\t', ' ')
    file_without_comment = Scanner.remove_comments(string)
    scanner = Scanner.Scanner(file_without_comment)
    scanner.next()
    classes, lexes = parse_rules(scanner)
    f.close()
    return classes, lexes
Example #58
0
def parseCommentM1(scanner):
    result = []
    res    = u""
    for token in scanner:
        result.append(token.value)
        if token.value == '*/':
            res = u"".join(result)
            if not Scanner.is_last_escaped(res):
                break
    else:
        # this means we've run out of tokens without finishing the comment
        res = u"".join(result)
        raise SyntaxException("Run-away comment", res)

    return res
Example #59
0
def parseString(scanner, sstart):
    # parse string literals
    result = []
    for token in scanner:
        result.append(token.value)
        if token.value == sstart:
            res = u"".join(result)
            if not Scanner.is_last_escaped(res):  # be aware of escaped quotes
                break
    else:
        # this means we've run out of tokens without finishing the string
        res = u"".join(result)
        raise SyntaxException("Non-terminated string", res)

    return res