Exemple #1
1
def set_color(color, state="on"):
    if not color in functions_optcode.keys():
        raise UnknownColor(color)
    if color in colors_connection.keys():
        for connection in colors_connection[color]:
            Core.send_byte(functions_optcode[connection]["off" if state == "on" else "on"])
    Core.send_byte(functions_optcode[color][state])
Exemple #2
0
def DeleteGenerateData(
        mode,
        fileName=None,
        path=r"D:\tr11\tr11_dev\GeneratedData\gameassets\cooked_durango-dev"):
    if mode == "Wwise":
        try:
            cr.DeleteFlies(
                r"D:\tr11\tr11_dev\GeneratedData\gameassets\cooked_durango-dev\wwise"
            )
        except Exception:
            print("Wwise")
    elif mode == "Simplygon":
        try:
            cr.DeleteFlies(
                r"D:\tr11\tr11_dev\GeneratedData\gameassets\build_DURANGO-DEV\mesh"
            )
        except Exception:
            print("Simplygon")
    elif mode == "Filename":
        filesToDelete = []
        filesToDelete = cr.FindFile(fileName, path, "file")
        print("Here is flie list to delete:" + str(filesToDelete))
        cr.MutiDelete(filesToDelete)
    else:
        print("Wrong parameter")
Exemple #3
0
def run():
    """
    """
    mode = 'pose'
    if UIData.menuAnim.isChecked() == True:
        mode = 'anim'
    Core.run(mode=mode)
Exemple #4
0
 def request_connection(self, input_file, outputfile, mode):
     socket = self.socket
     request = None
     if mode == "put":
         mode = Resources.WRITE_REQUEST
         request = Utils.Structure(Resources.WRITE_REQUEST)
         request = request.request_struct(outputfile, Resources.OCTAL_MODE)
     elif mode == "get":
         mode = Resources.READ_REQUEST
         request = Utils.Structure(Resources.READ_REQUEST)
         request = request.request_struct(input_file, Resources.OCTAL_MODE)
     struct_packed = request
     rand = randint(0, 100)
     if rand >= self.average:
         socket.sendto(struct_packed, (self.hostname, self.port))
     core = Core(socket,
                 input_file,
                 outputfile,
                 struct_packed,
                 self.average,
                 self.socket,
                 address=self.hostname,
                 port=self.port)
     core.GetAnswer(mode)
     return
Exemple #5
0
def enforcedLocalPath(relpath, dirpath, context='Path'):
    """ Return a forced local path, relative to a directory.
    
        Throw an error if the combination of path and directory seems to
        specify a remote path, e.g. "/path" and "http://example.com".
    
        Although a configuration file can be parsed from a remote URL, some
        paths (e.g. the location of a disk cache) must be local to the server.
        In cases where we mix a remote configuration location with a local
        cache location, e.g. "http://example.com/tilestache.cfg", the disk path
        must include the "file://" prefix instead of an ambiguous absolute
        path such as "/tmp/tilestache".
    """
    parsed_dir = urlparse(dirpath)
    parsed_rel = urlparse(relpath)
    
    if parsed_rel.scheme not in ('file', ''):
        raise Core.KnownUnknown('%s path must be a local file path, absolute or "file://", not "%s".' % (context, relpath))
    
    if parsed_dir.scheme not in ('file', '') and parsed_rel.scheme != 'file':
        raise Core.KnownUnknown('%s path must start with "file://" in a remote configuration ("%s" relative to %s)' % (context, relpath, dirpath))
    
    if parsed_rel.scheme == 'file':
        # file:// is an absolute local reference for the disk cache.
        return parsed_rel.path

    if parsed_dir.scheme == 'file':
        # file:// is an absolute local reference for the directory.
        return urljoin(parsed_dir.path, parsed_rel.path)
    
    # nothing has a scheme, it's probably just a bunch of
    # dumb local paths, so let's see what happens next.
    return pathjoin(dirpath, relpath)
Exemple #6
0
def Encrypt_File(filename,keyText=None):
    try:
        EncryptionFile = open(filename, 'rb')
    except IOError:
        raise IOError
    fileContent = EncryptionFile.read()
    EncryptionFile.close()
    key = []
    if keyText==None:
        key = Core.keyGenerator()
    else:
        key = Core.convert_block(list(keyText))

    IV, EncryptedText = Encrypt_all_blocks(fileContent,key)
    tempiv = ''.join(Core.convert_to_chars(IV))
    Final = tempiv+EncryptedText
    #for i,line in enumerate(fileContent):
        #IV.append(None)
       # EncryptedText.append(None)
        #IV[i], EncryptedText[i] = Encrypt_all_blocks(line[:-1], key)

        #Final.append([tempiv,EncryptedText[i]])
    keyFile = ''.join(Core.convert_to_chars(key))
    EncryptionFile = open(filename, 'w')
    #pickle.dump(keyFile, EncryptionFile)
    pickle.dump(Final,EncryptionFile)
    EncryptionFile.close()
    return keyFile
Exemple #7
0
def main():

	parser = OptionParser()

	#Parser Options
	parser.add_option("-s", "--starting-point", dest="start",
	help="Use <name>|<email>|<username>|<id> to set the OSINT starting point. \
	Use <id> to OSINT based on a Profile template", metavar="START")

	parser.add_option("-o", "--outdir", dest="outdir",
	help="The IDENTIFIER will name the directory that contains the collected information", metavar="IDENTIFIER")

	parser.add_option("-l", "--level", dest="level",
	help="Use FAST|MEDIUM|HIGH|EXTREME to set LEVEL to the depth of the information gathering.",
	metavar="LEVEL")

	parser.add_option("-v", "--verbose", dest="verbosity",
	help="Use VERBOSITY SILENT|NORMAL|DEBUG to set the verbosity level", metavar="VERBOSITY", default="NORMAL")

	options, arguments = parser.parse_args()

	core = Core("sana.abrahimen")
	core.username_osint()

	return 0
Exemple #8
0
def main(argv):
    port = 5000
    folder = None
    packet_loss = 0

    for n in range(len(argv)):
        if argv[n] == "-p" or argv[n] == "--port":
            port = int(argv[n + 1])
        if argv[n] == "-h" or argv[n] == "--help":
            usage()
            sys.exit(0)
        if argv[n] == "-la" or argv[n] == "--lose-average":
            if int(argv[n + 1]) < 0:
                packet_loss = 0
            elif int(argv[n + 1]) >= 100:
                packet_loss = 100
            else:
                packet_loss = int(argv[n + 1])
        if argv[n] == "-f" or argv[n] == "--folder":
            folder = argv[n + 1]
    if None == folder:
        print("No such folder.")
        usage()
        sys.exit(-1)
    socket_srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket_srv.bind(("0.0.0.0", port))
    data, addr = socket_srv.recvfrom(PACKET_SIZE)
    timer = Timeout(15.0, socket_srv)
    while True:
        if None == data and None == addr:
            timer.cancel_timer()
            data, addr = socket_srv.recvfrom(PACKET_SIZE)
        app = Core(socket_srv, data, addr, packet_loss, folder)
        data, addr = app.GetAnswer()
    return
Exemple #9
0
 def TextButton3(self,event, option):
     if option == 1:
         path = self.entry1.get()
         self.keyEntry.delete(0, 'end')
         originalDirectory = os.getcwd()
         try:
             os.chdir(path)
         except WindowsError:
             self.status.configure(text="Path is invalid!", bg='red')
             return
         keyText = ''.join(Core.convert_to_chars(Core.keyGenerator()))
         DirectoryList = os.listdir(os.getcwd())
         for i, fileName in enumerate(DirectoryList):
             keyText = Encrypt.Encrypt_File(fileName, keyText)
             self.status.configure(text="Encrypted %d out of %d files" % (i, len(DirectoryList)), bg='orange')
         self.keyEntry.insert(0, keyText)
         self.status.configure(text="Folder Encryption complete.", bg='light green')
     else:
         originalDirectory = os.getcwd()
         path = self.entry1.get()
         try:
             os.chdir(path)
         except WindowsError:
             self.status.configure(text="Path is invalid!", bg='red')
             return
         DirectoryList = os.listdir(os.getcwd())
         for i, fileName in enumerate(DirectoryList):
             KeyText = self.keyEntry.get()
             self.status.configure(text="Decrypted %d out of %d files" % (i, len(DirectoryList)), bg='orange')
             Decrypt.Decrypt_File(fileName, KeyText)
         self.status.configure(text="Folder Decryption complete.", bg='light green')
     os.chdir(originalDirectory)
Exemple #10
0
def move_calc():
    global raw_speed_value, raw_turn_value, last_val
    if (last_val != 0 and last_val + raw_speed_value
            == 0):  # Filter out sudden polarity changes
        raw_speed_value = last_val
    else:
        last_val = raw_speed_value
    raw_speed_value = -raw_speed_value  # Change polarity of raw_speed_value
    # Scale joystick values to motor values
    speed_value = Core.motor_max_value * (raw_speed_value / joystick_max_value)
    turn_value = Core.motor_max_value * (raw_turn_value / joystick_max_value)

    left_speed = speed_value  # Set left motor speed variable
    right_speed = speed_value  # Set right motor speed variable
    if (raw_speed_value > 0):  # If forward
        if (turn_value > 0):  # Right turn
            right_speed = right_speed - turn_value  # Change right motor speed variable (right is positive)
        else:  # Left turn or NO turn
            left_speed = left_speed + turn_value  # Change left motor speed variable (left is negative)
    else:  # If backwards
        if (turn_value > 0):  # Right turn
            right_speed = right_speed + turn_value  # Change right motor speed variable (right is positive)
        else:  # Left turn or NO turn
            left_speed = left_speed - turn_value  # Change left motor speed variable (left is negative)
    Core.move(left_speed, right_speed)
    def pointLocation(self, point):
        """ Return a geographical location on the map image for a given x, y point.
        """
        hizoomCoord = self.coordinate.zoomTo(Core.Coordinate.MAX_ZOOM)
        
        # because of the center/corner business
        point = Core.Point(point.x - self.dimensions.x/2,
                           point.y - self.dimensions.y/2)
        
        # distance in tile widths from reference tile to point
        xTiles = (point.x - self.offset.x) / self.provider.tileWidth();
        yTiles = (point.y - self.offset.y) / self.provider.tileHeight();
        
        # distance in rows & columns at maximum zoom
        xDistance = xTiles * math.pow(2, (Core.Coordinate.MAX_ZOOM - self.coordinate.zoom));
        yDistance = yTiles * math.pow(2, (Core.Coordinate.MAX_ZOOM - self.coordinate.zoom));
        
        # new point coordinate reflecting that distance
        coord = Core.Coordinate(round(hizoomCoord.row + yDistance),
                                round(hizoomCoord.column + xDistance),
                                hizoomCoord.zoom)

        coord = coord.zoomTo(self.coordinate.zoom)
        
        location = self.provider.coordinateLocation(coord)
        
        return location
Exemple #12
0
def experiment(k):
    np.random.seed()

    # Agent initialization
    agent = AgentPrior(budgetTot=1000, deadline=deadline, nCampaigns=nCampaigns, nBudget=nIntervals, nBids=nBids, maxBudget=100.0,usePrior=False)
    agent.initGPs()
    print "Experiment3D : ",k

    if show:
        plotter = Plotter(agent, env)
        [trueClicks, trueBudgets] = plotter.trueSample(1.0, maxBudget=100.0, nsimul=400)
    if save:
        trueClicks = np.array([trueClicks])
        trueBudgets = np.array([trueBudgets])
        np.save(path + 'trueClicks', trueClicks)
        np.save(path + 'trueBudgets', trueBudgets)

    # Set the GPs hyperparameters
    for c in range(0,nCampaigns):
        agent.setGPKernel(c , oracle.gps3D[c].kernel_)

    # Init the Core and execute the experiment
    env = Environment(copy.copy(campaigns))
    core = Core(agent, copy.copy(env), deadline)

    core.runEpisode()
    np.save(path+"policy3D_" +str(k), [agent.prevBids,agent.prevBudgets])
    np.save(path+"experiment3D_" + str(k),np.sum(agent.prevConversions,axis=1))
    return np.sum(agent.prevConversions,axis=1)
    def draw(self, verbose=False):
        """ Draw map out to a PIL.Image and return it.
        """
        coord = self.coordinate.copy()
        corner = Core.Point(int(self.offset.x + self.dimensions.x/2), int(self.offset.y + self.dimensions.y/2))

        while corner.x > 0:
            corner.x -= self.provider.tileWidth()
            coord = coord.left()
        
        while corner.y > 0:
            corner.y -= self.provider.tileHeight()
            coord = coord.up()
        
        tiles = TileQueue()
        
        rowCoord = coord.copy()
        for y in range(corner.y, self.dimensions.y, self.provider.tileHeight()):
            tileCoord = rowCoord.copy()
            for x in range(corner.x, self.dimensions.x, self.provider.tileWidth()):
                tiles.append(TileRequest(self.provider, tileCoord, Core.Point(x, y)))
                tileCoord = tileCoord.right()
            rowCoord = rowCoord.down()

        return self.render_tiles(tiles, self.dimensions.x, self.dimensions.y, verbose)
Exemple #14
0
def requestHandler(config, path_info, query_string):
    """ Generate a mime-type and response body for a given request.
    
        Requires a configuration and PATH_INFO (e.g. "/example/0/0/0.png").
        
        Config parameter can be a file path string for a JSON configuration file
        or a configuration object with 'cache', 'layers', and 'dirpath' properties.
        
        Query string is optional and not currently used. Calls getTile()
        to render actual tiles, and getPreview() to render preview.html.
    """
    try:
        if path_info is None:
            raise Core.KnownUnknown('Missing path_info in requestHandler().')

        layer = requestLayer(config, path_info)
        query = parse_qs(query_string or '')

        coord, extension = splitPathInfo(path_info)[1:]

        if extension == 'html' and coord is None:
            mimetype, content = getPreview(layer)

        else:
            mimetype, content = getTile(layer, coord, extension)

    except Core.KnownUnknown, e:
        out = StringIO()

        print >> out, 'Known unknown!'
        print >> out, e
        print >> out, ''
        print >> out, '\n'.join(Core._rummy())

        mimetype, content = 'text/plain', out.getvalue()
    def backup(self, historicalData):
        '''Writes historical data to file'''
        
        #If true exit due to exception
        exit = False
        # Get file path from config
        location = self.CONFIG.getConfig("Application", "offlineFile")
        #Check if config is empty
        if len(location) == 0:
            # Use current directory
            location = os.path.join(os.getcwd(), "backup.p")
            self.LOGGER.warning("offlineFile is empty. Using default: '" + location + "'")
        
        try:
            # Append to file
            path = file(location, "a")

            # Ensure object has data
            if historicalData is not None:
                self.LOGGER.info("Writing data to file:" + str(historicalData.__dict__))
                pickle.dump(historicalData, path)
        except IOError:
            #Debug.writeOut("Unable to write to backup file: '" + location + "'")
            # No point running program if it's unable to write to file
            exit = True
        finally:
            # Close file
            try:
                path.close()
            except UnboundLocalError:
                # File was not opened
                pass
        # Check to exit
        if exit:
            Core.shutdown()
Exemple #16
0
def main():
    australia = Cities(5, 219)
    readMap(australia)
    createGraph(australia)

    root = Core.Node(None, 0, [5], 0)
    solution = Core.greedy(root, Cities)
    print(
        f'depth: {solution.depth}\ncost:{Cities.g_cost(solution.state)}\ncities list:'
    )
    i = 0
    for citie in solution.state:
        print("\t order: ", i, " id: ", citie, " city: ",
              Cities.list[citie].name)
        i += 1

    print(solution.state)

    australia = Cities(5, 219)
    readMap(australia)
    createGraph(australia)

    root = Core.Node(None, 0, [5], 0)
    solution = Core.a_star(root, Cities)
    print(
        f'depth: {solution.depth}\ncost:{Cities.g_cost(solution.state)}\ncities list:'
    )
    i = 0
    for citie in solution.state:
        print("\t order: ", i, " id: ", citie, " city: ",
              Cities.list[citie].name)
        i += 1

    print(solution.state)
Exemple #17
0
def generate_action(info):
    import Core

    if info.root:
        Core.Core(info.root).run()
    else:
        Core.Core(os.getcwd()).run()
Exemple #18
0
 def createApparatus(self, template, args, kwargs):
     self.apparatus = Core.Apparatus()
     if template == 'file':
         self.apparatus = Core.Apparatus()
     else:
         templateFunc = import_module(template)
         templateFunc(*args, **kwargs)
def experiment(k):
    # Agent initialization
    np.random.seed()

    agent = AgentFactored(budgetTot=1000,
                          deadline=deadline,
                          nCampaigns=nCampaigns,
                          nBudget=nIntervals,
                          nBids=nBids,
                          maxBudget=100.0)
    agent.initGPs()
    print "Experiment : ", k
    print "A"

    # Set the GPs hyperparameters
    for c in range(0, nCampaigns):
        agent.setGPKernel(c, oracle.gpsClicks[c].kernel_,
                          oracle.gpsCosts[c].kernel_)

    # Init the Core and execute the experiment
    env = Environment(copy.copy(campaigns))
    core = Core(agent, copy.copy(env), deadline)

    core.runEpisode()
    np.save(path + "policy_" + str(k), [agent.prevBids, agent.prevBudgets])
    np.save(path + "experiment_" + str(k), np.sum(agent.prevConversions,
                                                  axis=1))
    return np.sum(agent.prevConversions, axis=1), agent
Exemple #20
0
def main(input_medium, output_medium):
    """
    Run Jarvis on this system using the given
    preferred input and output media if possible
    """

    Core.main(Inputter(input_medium), Outputter(output_medium))
Exemple #21
0
 def CleanLocal(self):
     bigfileMark = "BF_TR11_"
     dirlist = os.listdir(self.localRoot)
     virsionArray = []
     for dir in dirlist:
         filePath = os.path.join(self.localRoot, dir)
         if bigfileMark in dir:
             if not self.CheckBigfileComplement(filePath):
                 cr.Delete(filePath)
                 print("Delete imcomplete bigfiles success")
             else:
                 version = dir.split('_', 4)[4]
                 virsionArray.append(version)
         else:
             cr.Delete(filePath)
             print("Delete extra local files success")
     virsionArray.sort()
     if len(virsionArray) > 3:
         virsionArray = virsionArray[:-3]  #slice 去除列表后三位
         for virsion in virsionArray:
             for dir in dirlist:
                 if virsion in dir:
                     oldBigfilePath = os.path.join(self.localRoot, dir)
                     cr.Delete(oldBigfilePath)
     else:
         pass
Exemple #22
0
def requestHandler(config_hint, path_info, query_string):
    """ Generate a mime-type and response body for a given request.
    
        Requires a configuration and PATH_INFO (e.g. "/example/0/0/0.png").
        
        Config_hint parameter can be a path string for a JSON configuration file
        or a configuration object with 'cache', 'layers', and 'dirpath' properties.
        
        Query string is optional, currently used for JSON callbacks.
        
        Calls getTile() to render actual tiles, and getPreview() to render preview.html.
    """
    try:
        # ensure that path_info is at least a single "/"
        path_info = '/' + (path_info or '').lstrip('/')

        layer = requestLayer(config_hint, path_info)
        query = parse_qs(query_string or '')
        try:
            callback = query['callback'][0]
        except KeyError:
            callback = None

        #
        # Special case for index page.
        #
        if path_info == '/':
            return getattr(layer.config, 'index',
                           ('text/plain', 'TileStache says hello.'))

        coord, extension = splitPathInfo(path_info)[1:]

        if path_info == '/':
            raise Exception(path_info)

        elif extension == 'html' and coord is None:
            mimetype, content = getPreview(layer)

        elif extension.lower() in layer.redirects:
            other_extension = layer.redirects[extension.lower()]
            other_path_info = mergePathInfo(layer.name(), coord,
                                            other_extension)
            raise Core.TheTileIsInAnotherCastle(other_path_info)

        else:
            mimetype, content = getTile(layer, coord, extension)

        if callback and 'json' in mimetype:
            mimetype, content = 'application/javascript', '%s(%s)' % (callback,
                                                                      content)

    except Core.KnownUnknown, e:
        out = StringIO()

        print >> out, 'Known unknown!'
        print >> out, e
        print >> out, ''
        print >> out, '\n'.join(Core._rummy())

        mimetype, content = 'text/plain', out.getvalue()
Exemple #23
0
    def event_step(self, time_passed, delta_mult):
        position = pygame.math.Vector2(self.x, self.y)

        if self.sprite is self.sprite_walk:
            if sge.mouse.get_pressed("left"):
                mouse_vec = pygame.math.Vector2(sge.game.mouse.x,
                                                sge.game.mouse.y)
                if position.distance_to(mouse_vec) > self.image_width / 6:
                    self.target.x = mouse_vec.x
                    self.target.y = mouse_vec.y
            self.z = self.y

        self.target.x = Core.clamp(self.target.x, self.image_width / 2,
                                   ROOM_WIDTH - self.image_width / 2)
        self.target.y = Core.clamp(self.target.y,
                                   sge.game.height - FLOOR_HEIGHT,
                                   sge.game.height)

        if position.distance_to(self.target) > self.move_speed + 0.1:
            direction = self.move_speed * (self.target - position).normalize()
            self.xvelocity = direction.x
            self.yvelocity = direction.y
            self.image_speed = self.move_speed * (time_passed / 1000)
        else:
            self.xvelocity = 0
            self.yvelocity = 0
            self.image_speed = 0
            self.image_index = 0
        # Flip sprite to face direction
        self.image_xscale = math.copysign(1, self.xvelocity)
        # adjust view to player's position
        sge.game.current_room.views[0].x = (self.x - sge.game.width / 4)
Exemple #24
0
def RunUDPFlooder(TargetIP, SourcePort, TargetPort, SpoofedIP, PacketsToSend,
                  CustomPayload):

    try:
        Core.RemoveLine()
        i = 0
        print("Beginning Stress Test")
        while (i < PacketsToSend):
            i = i + 1
            send(IP(src=SpoofedIP, dst=TargetIP) /
                 UDP(sport=int(SourcePort), dport=int(TargetPort)) /
                 CustomPayload,
                 verbose=False)
            Core.RemoveLine()
            print('Sent ' + str(i) + '/' + str(PacketsToSend) + ' Packets')

            if (i == PacketsToSend):
                Core.RemoveLine()
                print(Fore.GREEN + "Finished")
                input(Fore.RESET + 'Press Enter to return to the main menu')
                Core.RemoveLine()
                break
    except:
        print("An Error Occured")

    Core.ReturnToMenu(Menus.StressMenu)
Exemple #25
0
def experiment(k):
    np.random.seed()
    print "Esperimento: ", k
    agentGPUCB = AgentFactored(1000, deadline, ncampaigns, nIntervals, nBids,
                               maxBudget, 1.0, "GPUCB")
    agentGPUCB.initGPs()
    envGPUCB = Environment(copy.copy(campaigns))
    coreGPUCB = Core(agentGPUCB, envGPUCB, deadline)
    meanConvGPUCB = np.zeros(deadline)

    # in questo ciclo mi salvo le conversioni medie in ogni istante
    for t in range(deadline):
        print "Day: ", t + 1
        coreGPUCB.step()
        meanConvGPUCB[t] = lastMeanConv(agentGPUCB)

    # ora invece mi salvo le conversioni istantanee
    instConvGPUCB = np.sum(agentGPUCB.prevConversions, axis=1)

    positionGPUCB1 = path_dati + "inst_conv_3camp_" + str(k)
    positionGPUCB2 = path_dati + "mean_conv_3camp_" + str(k)
    np.save(positionGPUCB1, instConvGPUCB)
    np.save(positionGPUCB2, meanConvGPUCB)

    return
Exemple #26
0
def run():
    mode = 'constraint'
    if UIData.menuBake.isChecked():
        mode = 'bake'
    elif UIData.menuDriver.isChecked():
        mode = 'driver'

    Core.run(mode=mode)
Exemple #27
0
 def run(self):
     Core.on_drv()
     list1 = Core.get_vil_list("http://werewolf.co.kr")
     list3 = Core.get_vil_list("http://werewolf6.cafe24.com")
     vil_list = list1 + list3
     self.signals.ListReady.emit(vil_list)
     print(vil_list)
     len(vil_list)
Exemple #28
0
 def run(self):
     if self.outputDir == "":
         notice = QMessageBox.information(self, "경고", "경로를 선택하십시오.")
     else:
         self.summaryText = self.description.text()
         self.fileName = self.fileNameEdit.text()
         Core.doAction(self.oneDigit, self.startYear, self.endYear,
                       self.summaryText, self.outputDir, self.fileName)
Exemple #29
0
def shiftKey(mode='right'):
    """
    """
    val = int(UIData.qLineEditShiftKey.text())
    if mode == 'right':
        Core.run(amount=val)
    elif mode == 'left':
        Core.run(amount=-1 * val)
Exemple #30
0
def shiftKey(mode='right'):
    """
    """
    val = int(cmds.textField(UIContainer.textFieldShiftKey, q=True, text=True))
    if mode == 'right':
        Core.run(amount=val)
    elif mode == 'left':
        Core.run(amount=-1 * val)
Exemple #31
0
def runDecalComanie():
    """
    """
    mode = 'pose'
    if cmds.menuItem(UIContainer.radioMenuItemDCNModeAnim,
                     q=True,
                     radioButton=True):
        mode = 'anim'
    Core.run(mode=mode)
Exemple #32
0
def microControlRun(mode, *args):
    """
    @param mode string "add" or "sub"
    """
    val = round(float((UIData.qLineEditMc.text())), 3)
    if mode == "add":
        Core.run(val)
    else:
        Core.run(val*-1)
Exemple #33
0
def LU(A,Pivoting=False):
    U = A
    m = A.rows
    L = Core.MatrixGallery("I",A.rows,A.cols)
    P = Core.MatrixGallery("I",A.rows,A.cols)
    if A.rows != A.cols:
        print("LU Factorization only with square matrix (I'm lazy not yet implemented not square)!")
    if A.Sparse == True:
        print("LU Factorization only works with dense matrix please convert it first")
    if A.onlyMP == True:
        print("LU Factorization not yet implemented for high precision")
    if Pivoting:
        if A.onlyNP == True:
            U = copy(U.NP)
            A = copy(A.NP)
            L = copy(L.NP)
            P = copy(P.NP)
            for k in range(m-1):
                M = [np.absolute(U[i,k]) for i in range(k,m)]
                i = np.argmax(M)+k
                #print(M)
                #print(U[i,k])

                tmp1 = copy(U[k,k:m])
                tmp2 = copy(U[i,k:m])
                U[k,k:m] = copy(tmp2)
                U[i,k:m] = copy(tmp1)
                del tmp1, tmp2

                tmp1 = copy(L[k,0:k])
                tmp2 = copy(L[i,0:k])
                L[k,0:k] = copy(tmp2)
                L[i,0:k] = copy(tmp1)
                del tmp1, tmp2

                tmp1 = copy(P[k,:])
                tmp2 = copy(P[i,:])
                P[k,:] = copy(tmp2)
                P[i,:] = copy(tmp1)
                del tmp1, tmp2

                for j in range(k+1,m):
                    L[j,k]=copy(U[j,k]/U[k,k])
                    U[j,k:m]=U[j,k:m]-L[j,k]*U[k,k:m]
            U = Matrix(U.tolist(),onlyNP=True)
            L = Matrix(L.tolist(),onlyNP=True)
            P = Matrix(P.tolist(),onlyNP=True)
        return [P.T(),L,U]
    else:
        for i in range(A.cols-1):
            for j in range(i+1,A.cols):
                L[j,i]=U[j,i]/U[i,i]
                if A.onlyNP == True:
                    #print(U.NP[j,i:A.cols])
                    U.NP[j,i:A.cols]=U.NP[j,i:A.cols]-U.NP[i,i:A.cols]*L[j,i]
                    U = Matrix(U.NP.tolist(),onlyNP=True)
        return [L,U]
 def DoRun(self, savefile="FileZilla.xml"):
     if os.path.isfile(self.txtFile.GetValue()):
         r = Core.XML2Dict().parse(self.txtFile.GetValue())
         if Core.writeFilezillaXmlFile(r, savefile):
             wx.MessageBox(_L["run_complete"], _L["msg"])
         else:
             wx.MessageBox(_L["run_faild"], _L["msg"])
     else:
         wx.MessageBox(_L["file_not_exist"], _L["error"], wx.ICON_ERROR)
def notFixed():
	fileOpen = "boot.txt"
	section = "/proc/cmdline"
	content = {}
	SERVER = SUSE.getHostInfo()
#	print "SERVER = " + str(SERVER)
	if( SERVER['DistroVersion'] == 11 ):
		if( SERVER['DistroPatchLevel'] == 3 ):
			FIXED_VERSION = '3.0.101-0.21'
		elif( SERVER['DistroPatchLevel'] == 2 ):
			FIXED_VERSION = '3.0.101-0.7.19'
		else:
			Core.updateStatus(Core.ERROR, "Outside Service Pack scope, skipping IRQ remap test")
			return False

		if( SUSE.compareKernel(FIXED_VERSION) >= 0 ):
			Core.updateStatus(Core.IGNORE, "Patch applied, IRQ remap issue AVOIDED")
			return False
	else:
		Core.updateStatus(Core.ERROR, "Outside Distribution scope, skipping IRQ remap test")
		return False
		
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if "intremap=off" in content[line]:
				Core.updateStatus(Core.IGNORE, "Found interrupt remapping issue intremap=off work around")
				return False
	return True
Exemple #36
0
def getSBDInfo():
	"""
	Gets split brain detection partition information. Gathers information from the sbd dump command and the /etc/sysconfig/sbd file. SBD partitions with invalid sbd dump output are ignored.

	Args:		None
	Returns:	List of SBD Dictionaries with keys
		SBD_DEVICE (String) - The /etc/sysconfig/sbd SDB_DEVICE variable. This value applies to all and is stored with each sbd device.
		SBD_OPTS (String) - The /etc/sysconfig/sbd SBD_OPTS variable
		Version (Int) - The SDB header version string
		Slots (Int) - The number of SDB slots
		Sector_Size (Int) - The SBD sector size
		Watchdog (Int) - The SBD watchdog timeout
		Allocate (Int) - The SBD allocate timeout
		Loop (Int) - The SBD loop timeout
		MsgWait (Int) - The SBD msgwait timeout
	Example:

	SBD = HAE.getSBDInfo()
	MSG_WAIT_MIN = 300
	MSG_WAIT_OVERALL = MSG_WAIT_MIN
	# Find the smallest msgwait value among the SBD partitions
	for I in range(0, len(SBD)):
		if( SBD[I]['MsgWait'] < MSG_WAIT_OVERALL ):
			MSG_WAIT_OVERALL = SBD[I]['MsgWait']
	# See if the smallest msgwait is less than the minimum required
	if ( MSG_WAIT_OVERALL < MSG_WAIT_MIN ):
		Core.updateStatus(Core.REC, "Consider changing your msgwait time")
	else:
		Core.updateStatus(Core.IGNORE, "The msgwait is sufficient")
	"""
	SBD_LIST = []
	SBD_DICTIONARY = { 
		'Device': '',
		'SBD_DEVICE': '',
		'SBD_OPTS': '',
		'Version': '',
		'Slots': -1,
		'Sector_Size': -1,
		'Watchdog': -1,
		'Allocate': -1,
		'Loop': -1,
		'MsgWait': -1,
	}
	FILE_OPEN = "ha.txt"
	CONTENT = {}
	IDX_PATH = 3
	IDX_VALUE = 1
	SYSCONFIG_FOUND = False
	DUMP_FOUND = False

	try:
		FILE = open(Core.path + "/" + FILE_OPEN)
	except Exception, error:
#		print "Error opening file: %s" % error
		Core.updateStatus(Core.ERROR, "ERROR: Cannot open " + FILE_OPEN)
Exemple #37
0
def set_register():
    '''Function to switch on all the
    lamps in the installation.
    '''
    for color in functions_optcode.keys():
        if color in [ 'set', 'clear' ]:
            continue
        if not color in connections_relations.keys():
            Core.send_byte( functions_optcode[ color ][ 'on' ] )
        else:
            Core.send_byte( functions_optcode[ color ][ 'off' ] )
Exemple #38
0
def Decrypt_all_blocks(ciphertext, key, IV):
    ciphertext_list = Core.convert_to_block(ciphertext)
    Bit_List = Core.convert_to_ASCII(ciphertext_list)
    plain = []
    temp = IV[:]
    for block in Bit_List:
        AfterDecrypt = decrypt_block(block, key)
        plain_block = Core.XOR_previous_block(AfterDecrypt, temp)
        plain.append(plain_block)
        temp = block
    DecryptedText = Core.convert_all_blocks_to_chars(plain)
    return DecryptedText
Exemple #39
0
def Encrypt_all_blocks(plaintext, key):
    plaintext_list = Core.convert_to_block(plaintext)
    Bit_List = Core.convert_to_ASCII(plaintext_list)
    IV = Core.keyGenerator()
    temp = IV[:]
    cipher = []
    for block in Bit_List:
        AfterXOR = Core.XOR_previous_block(block, temp)
        cipher_block = encrypt_block(AfterXOR, key)
        cipher.append(cipher_block)
        temp = cipher_block
    EncryptedText = Core.convert_all_blocks_to_chars(cipher)
    return IV, EncryptedText
Exemple #40
0
def Decrypt_File(filename,keyFile):
    try:
        DecryptionFile = open(filename, 'r')
    except IOError:
        raise IOError
    #keyFile = pickle.load(DecryptionFile)
    key = Core.convert_block(keyFile)
    msg = pickle.load(DecryptionFile)
    IVFile = msg[0:BLOCK_SIZE]
    line = msg[BLOCK_SIZE:]
    IV = Core.convert_block(list(IVFile))
    DecryptedText = Core.remove_nulls(Decrypt_all_blocks(line, key, IV))
    DecryptionFile = open(filename, 'wb')
    DecryptionFile.write((DecryptedText+"\n"))
    DecryptionFile.close()
Exemple #41
0
def save(playername, playerdata):
    def _save(filename, coords):
        tmpfilename = filename+".tmp"
        file = open(tmpfilename, "w+")
        coords_list = list(coords)
        coords_list.sort()
        for el in coords_list:
            file.write(str(el[0])+SEP+str(el[1])+"\n")
        file.close()
        if (os.path.exists(filename)):
            os.remove(filename)
        os.rename(tmpfilename, filename)
    _save(Core.prefix(playername)+".txt", playerdata[0])
    _save(Core.prefix(playername)+".objectifs.txt", playerdata[1])
    Core.saveconfigfile(playerdata[2], Core.prefix(playername)+".infos.ini")
Exemple #42
0
def getConfigCTDB():
	"""
	Gets the /etc/sysconfig/ctdb configuration file information.

	Args:		None
	Returns:	Dictionary with keys
		*All key:value pairs are derived from the configuration file itself. All key names are changed to uppercase. All values are left as is.
	Example:

	CTDB = HAE.getConfigCTDB()
	if 'CTDB_START_AS_DISABLED' in CTDB:
		if "yes" in CTDB['CTDB_START_AS_DISABLED']:
			Core.updateStatus(Core.IGNORE, "CTDB Starting disabled")
		else:
			Core.updateStatus(Core.WARN, "CTDB Starting enabled")
	else:
		Core.updateStatus(Core.ERROR, "Missing CTDB_START_AS_DISABLED, ignoring test")
	"""
	IDX_KEY = 0
	IDX_VALUE = 1
	CONFIG = {}
	FILE_OPEN = 'ha.txt'
	SECTION = "/etc/sysconfig/ctdb"
	CONTENT = {}
	if Core.getSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if( len(CONTENT[LINE]) > 0 ):
				KEY = CONTENT[LINE].split('=')[IDX_KEY].strip().upper()
				VALUE = re.sub('"|\'', '', CONTENT[LINE].split('=')[IDX_VALUE]).strip()
				CONFIG.update({KEY:VALUE})

#	print "CONFIG Size = " + str(len(CONFIG))
#	print "CONFIG =      " + str(CONFIG)
	return CONFIG
Exemple #43
0
def cgiHandler(environ, config='./tilestache.cfg', debug=False):
    """ Read environment PATH_INFO, load up configuration, talk to stdout by CGI.
    """
    if debug:
        import cgitb
        cgitb.enable()
    
    try:
        if not environ.has_key('PATH_INFO'):
            raise Core.KnownUnknown('Missing PATH_INFO in TileStache.cgiHandler().')
    
        config = parseConfigfile(config)
        layername, coord, extension = _splitPathInfo(environ['PATH_INFO'])
        
        if layername not in config.layers:
            raise Core.KnownUnknown('"%s" is not a layer I know about. Here are some that I do know about: %s.' % (layername, ', '.join(config.layers.keys())))
        
        query = parse_qs(environ['QUERY_STRING'])
        layer = config.layers[layername]
        
        mimetype, content = handleRequest(layer, coord, extension)

    except Core.KnownUnknown, e:
        out = StringIO()
        
        print >> out, 'Known unknown!'
        print >> out, e
        print >> out, ''
        print >> out, '\n'.join(Core._rummy())
        
        mimetype, content = 'text/plain', out.getvalue()
def errorMessagesFound():
	FILE_OPEN = "messages.txt"
	ERROR_MSG = re.compile("OraInstall.*libmawt.so.*cannot open shared object file.*No such file or directory", re.IGNORECASE)
	SECTION = "/var/log/warn"
	CONTENT = []
	if Core.getRegExSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if ERROR_MSG.search(LINE):
				return True
	SECTION = "/var/log/messages"
	CONTENT = []
	if Core.getRegExSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if ERROR_MSG.search(LINE):
				return True
	return False
def securityObject603error():
	fileOpen = "novell-edir.txt"
	section1 = "/ndsd.log -"
	section2 = "/ndsd.log\n"
	content = {}
	if Core.getSection(fileOpen, section1, content):
		for line in content:
			if "Error from pkiInstallCreatePKIObjects" in content[line]:
				if "= -603" in content[line]:
					return True
	elif Core.getSection(fileOpen, section2, content):
		for line in content:
			if "Error from pkiInstallCreatePKIObjects" in content[line]:
				if "= -603" in content[line]:
					return True
	return False
def sas603error():
	fileOpen = "y2log.txt"
	section1 = "/var/log/YaST2/y2log -"
	section2 = "/var/log/YaST2/y2log\n"
	content = {}
	if Core.getSection(fileOpen, section1, content):
		for line in content:
			if "Failed to configure SAS service" in content[line]:
				if "no such attribute err=-603" in content[line]:
					return True
	elif Core.getSection(fileOpen, section2, content):
		for line in content:
			if "Failed to configure SAS service" in content[line]:
				if "no such attribute err=-603" in content[line]:
					return True
	return False
Exemple #47
0
def ncsActive():
	"""
	Returns true is Novell Cluster Services is active on the server, otherwise it returns false.

	Args:		None
	Returns:	Boolean
		True = NCS is active
		False = NCS is not active

	Example:

	if( oes.ncsActive() ):
		Core.updateStatus(Core.IGNORE, "NCS is Active on the Server")
	else:
		Core.updateStatus(Core.WARN, "NCS is NOT active on the Server")

	"""
	FILE_OPEN = "novell-ncs.txt"
	SECTION = "cluster stats display"
	CONTENT = {}
	if Core.getSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if CONTENT[LINE].startswith("node"):
				return True
	return False
Exemple #48
0
def shadowVolumesFound():
	"""
	Checks if Dynamic Storage Technology (DST) shadow volumes are present.

	Args:		None
	Returns:	Boolean
		True = DST Shadow Volumes in use
		False = No DST Shadow Volumes in use

	Example:

	if( oes.shadowVolumesFound() ):
		Core.updateStatus(Core.IGNORE, "DST Shadow Volumes in Use")
	else:
		Core.updateStatus(Core.WARN, "No DST Shadow Volumes in Use")

	"""
	FILE_OPEN = "novell-ncp.txt"
	SECTION = "/etc/opt/novell/ncpserv.conf"
	CONTENT = {}
	if Core.getSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if "SHADOW_VOLUME" in CONTENT[LINE]:
				return True
	return False
Exemple #49
0
def dsfwCapable():
	"""
	Checks for DSfW capabilities from the LDAP root DSE server in novell-lum.txt file.

	Args:		None
	Returns:	Boolean
		True = Server is DSfW capable
		False = Server is NOT DSfW capable or novell-lum.txt cannot be found

	Example:

	if( oes.dsfwCapable() ):
		Core.updateStatus(Core.IGNORE, "Server is DSfW Capable")
	else:
		Core.updateStatus(Core.WARN, "Server is not DSfW Capable")

	"""
	FILE_OPEN = "novell-lum.txt"
	SECTION = "ldapsearch -x"
	CONTENT = {}
	if Core.getSection(FILE_OPEN, SECTION, CONTENT):
		for LINE in CONTENT:
			if "2.16.840.1.113719.1.513.7.1" in CONTENT[LINE]:
				return True
	return False
Exemple #50
0
def requestHandler(config, path_info, query_string):
    """ Generate a mime-type and response body for a given request.
    
        Requires a configuration and PATH_INFO (e.g. "/example/0/0/0.png").
        
        Config parameter can be a file path string for a JSON configuration file
        or a configuration object with 'cache', 'layers', and 'dirpath' properties.
        
        Query string is optional and not currently used. Calls getTile()
        to render actual tiles, and getPreview() to render preview.html.
    """
    try:
        if path_info is None:
            raise Core.KnownUnknown('Missing path_info in requestHandler().')
    
        layer = requestLayer(config, path_info)
        query = parse_qs(query_string or '')
        
        coord, extension = splitPathInfo(path_info)[1:]
        
        if extension == 'html' and coord is None:
            mimetype, content = getPreview(layer)

        else:
            mimetype, content = getTile(layer, coord, extension)

    except Core.KnownUnknown, e:
        out = StringIO()
        
        print >> out, 'Known unknown!'
        print >> out, e
        print >> out, ''
        print >> out, '\n'.join(Core._rummy())
        
        mimetype, content = 'text/plain', out.getvalue()
def getRPfilter():
	fileOpen = "env.txt"
	section = "/sbin/sysctl -a"
	VALUE = -1
	VALUE_ALL = -1
	VALUE_INT = -1
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if "net.ipv4.conf.all.rp_filter" in content[line]:
#				print content[line]
				RP_LIST = content[line].split('=')
				VALUE_ALL = int(RP_LIST[1].strip())
				break
		for line in content:
			if content[line].startswith('net.ipv4.conf'):
				if '.all.rp_filter' in content[line] or '.default.rp_filter' in content[line]:
					continue
				elif '.rp_filter' in content[line]:
#					print content[line]
					RP_LIST = content[line].split('=')
					VALUE_INT = int(RP_LIST[1].strip())
					if( VALUE_ALL < VALUE_INT ):
						VALUE_TMP = VALUE_INT
					else:
						VALUE_TMP = VALUE_ALL
					if( VALUE_TMP == 1 ):
						VALUE = 1
						break
					else:
						if( VALUE_TMP > VALUE ):
							VALUE = VALUE_TMP
#	print "VALUE = " + str(VALUE)
	return int(VALUE)
Exemple #52
0
def jabberdRunning():
	"""
	Confirms if all the processes required for jabberd are running.

	Args: None
	Returns: True or False
		True - The jabberd processes are running
		False - One or more jabberd processes are NOT running

	Example:

	if ( suma.jabberdRunning() ):
		Core.updateStatus(Core.IGNORE, "The jabberd process(es) are running")
	else:
		Core.updateStatus(Core.WARN, "ERROR: The jabberd process(es) are not running")
	"""
	CONTENT = {}
	COUNT = {}
	if Core.getSection('basic-health-check.txt', '/ps a', CONTENT):
		for line in CONTENT:
			STR = CONTENT[line].lower()
			if "/usr/bin/router " in STR:
				COUNT['router'] = True
			elif "/usr/bin/sm " in STR:
				COUNT['sm'] = True
			elif "/usr/bin/c2s " in STR:
				COUNT['c2s'] = True
			elif "/usr/bin/s2s " in STR:
				COUNT['s2s'] = True
#	print COUNT
	if( len(COUNT) == 4 ):
		return True
	else:
		return False
def checkVFX():
	fileOpen = "messages.txt"
	section = "/var/log/warn"
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if "vx_iget - inode table overflow" in content[line]:
				return True

	section = "/var/log/messages"
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if "vx_iget - inode table overflow" in content[line]:
				return True
	return False
def qlaRampFound():
	fileOpen = "messages.txt"
	msg = re.compile("kernel:.*qla2xxx.*Ramping down queue depth", re.IGNORECASE)
	section = "/var/log/warn"
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if msg.search(content[line]):
				return True
	section = "/var/log/messages"
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if msg.search(content[line]):
				return True
	return False
def lowDiskSpace():
	fileOpen = "basic-health-check.txt"
	section = "/bin/df -h"
	content = {}
	DISK_LOW = 85
	FULL = 6
	SHORT = 5
	iFULL = 4
	iSHORT = 3
	if Core.getSection(fileOpen, section, content):
		for line in content:
			FIELDS = content[line].split()
			PERCENT = 0
			if( len(FIELDS) == FULL ):
				PERCENT = FIELDS[iFULL].rstrip('%')
				if ( PERCENT.isdigit() ):
					PERCENT = int(PERCENT)
				else:
					PERCENT = 0
			elif( len(FIELDS) == SHORT ):
				PERCENT = FIELDS[iSHORT].rstrip('%')
				if ( PERCENT.isdigit() ):
					PERCENT = int(PERCENT)
				else:
					PERCENT = 0

#			print str(len(FIELDS)) + ':' + str(PERCENT) + ':' + str(DISK_LOW) + ": " + str(FIELDS)
			if( PERCENT > DISK_LOW ):
				return True

	return False
def changeableMTU(bond):
	fileOpen = "network.txt"
	(NAME, MTU_ACTIVE) = bond.split(',')
	if( len(MTU_ACTIVE) > 0 ):
		MTU_ACTIVE = int(MTU_ACTIVE)
	else:
		MTU_ACTIVE = MTU_DEF
	section = "/etc/sysconfig/network/ifcfg-" + NAME
	content = {}
	UP_ENSLAVE = False
	MTU_CONFIG = MTU_DEF
	if Core.getSection(fileOpen, section, content):
		mtu = re.compile("^MTU=")
		config = re.compile("^BONDING_MASTER_UP_ENSLAVE=.*yes", re.IGNORECASE)
		for line in content:
			if mtu.search(content[line]):
				MTU_CONFIG = content[line].split("=")[1].replace("'", '').replace('"', '').strip()
				if ( len(MTU_CONFIG) > 0 ):
					MTU_CONFIG = int(MTU_CONFIG)
				else:
					MTU_CONFIG = MTU_DEF
			elif config.search(content[line]):
				UP_ENSLAVE = True
#		print str(bond)+ ": MTU_ACTIVE = " + str(MTU_ACTIVE) + " MTU_CONFIG = " + str(MTU_CONFIG) + " UP_ENSLAVE = " + str(UP_ENSLAVE)
		if( UP_ENSLAVE ):
			if( MTU_CONFIG != MTU_ACTIVE ):
				return STATE_MTU_CHANGED
			else:
				return STATE_MTU_UNCHANGED
		elif( MTU_CONFIG != MTU_DEF ):
			if( MTU_CONFIG != MTU_ACTIVE ):
				return STATE_MTU_CHANGED
			else:
				return STATE_MTU_CHANGEABLE
	return STATE_MTU_UNCHANGED
def checkeDirCerts(CERTS):
	fileOpen = "novell-edir.txt"
	section = "objectclass=nDSPKIKeyMaterial"
	content = {}
	IN_STATE = 0
	DN = ''
	DN_EXP = []
	DN_THIRTY = []
	if Core.getSection(fileOpen, section, content):
		NOW = datetime.datetime.now()
#		print ("Now:     '%s'" % NOW)
		for line in content:
			if( IN_STATE ):
				if content[line].startswith("nDSPKINotAfter"):
					CERTS[EXP_TOTAL] += 1
					EXPIRES = content[line].split()[1]
#					print "EXPIRES = " + str(EXPIRES)
					EX_YEAR = int(EXPIRES[0:4])
#					print "EX_YEAR = " + str(EX_YEAR)
					EX_MONTH = int(EXPIRES[4:6])
#					print "EX_MONTH = " + str(EX_MONTH)
					EX_DAY = int(EXPIRES[6:8])
#					print "EX_DAY = " + str(EX_DAY)
					EX_HOUR = int(EXPIRES[8:10])
#					print "EX_HOUR = " + str(EX_HOUR)
					EX_MIN = int(EXPIRES[10:12])
#					print "EX_MIN = " + str(EX_MIN)
					# confirm the date/time includes seconds
					if( len(EXPIRES) > 12 ):
						EX_SEC = int(EXPIRES[12:])
					else:
						EX_SEC = 0
#					print "EX_SEC = " + str(EX_SEC)
					THEN = datetime.datetime(EX_YEAR, EX_MONTH, EX_DAY, EX_HOUR, EX_MIN, EX_SEC)
#					print ("Expires: '%s'" % THEN)
					DELTA = THEN - NOW
					DELTA30 = THEN - NOW - datetime.timedelta(days=30)
#					print "Delta = {0}, Delta 30 Days = {1}".format(DELTA.days, DELTA30.days)
					if( DELTA.days < 0 ):
#						print ("Exp DN: %s" % DN )
						CERTS[EXP_EXPIRED] += 1
						DN_EXP.append(DN)
					elif( DELTA30.days < 0 ):
#						print ("Exp30 DN: %s" % DN )
						CERTS[EXP_THIRTY] += 1
						DN_THIRTY.append(DN)
					IN_STATE = 0
					DN = ''
				elif content[line].startswith("#"):
					IN_STATE = 0
					DN = ''
			elif content[line].startswith("dn: "):
				IN_STATE = 1
				SPLIT_LINE = content[line].split()
				del SPLIT_LINE[0]
				DN = " ".join(SPLIT_LINE)
#				print ("DN: %s" % DN )
		CERTS[EXP_EXPIRED_STR] = ";".join(DN_EXP)
		CERTS[EXP_THIRTY_STR] = ";".join(DN_THIRTY)
def checkMessages():
	fileOpen = "messages.txt"
	section = "/var/log/warn"
	content = {}
	if Core.getSection(fileOpen, section, content):
		for line in content:
			if "nfs: RPC call returned error 88" in content[line]:
				return True
	return False

        section = "/var/log/messages"
        content = {}
        if Core.getSection(fileOpen, section, content):
                for line in content:
                        if "nfs: RPC call returned error 88" in content[line]:
                                return True
        return False
def activeNetFilters():
	fileOpen = "network.txt"
	section = "iptables -t filter"
	content = {}
	if Core.getSection(fileOpen, section, content):
		if( len(content) > 1 ):
			return True
	return False
Exemple #60
0
def start():

	pygame.init() 

	core = Core()
	Globals.core = core
	
	quit = False
	while not quit: 

	   core.update()
	   core.draw()

	   for event in pygame.event.get(): 
	      if event.type == pygame.QUIT: 
	        sys.exit(0) 

	      # resize
	      elif event.type==pygame.VIDEORESIZE:
	      	screen_size = event.dict['size']
	      	Globals.screen_size = screen_size
	      	core.initWindow()

	      elif (event.type == pygame.KEYDOWN) and (event.key == pygame.K_ESCAPE):
	      	quit = True

	      else:
	        pass