Esempio n. 1
0
 def execute(self, really_delete):
     """Make changes and return results"""
     if FileUtilities.whitelisted(self.path):
         yield whitelist(self.path)
         return
     ret = {
         # TRANSLATORS: This is the label in the log indicating will be
         # deleted (for previews) or was actually deleted
         'label': _('Delete'),
         'n_deleted': 1,
         'n_special': 0,
         'path': self.path,
         'size': FileUtilities.getsize(self.path)
     }
     if really_delete:
         try:
             FileUtilities.delete(self.path, self.shred)
         except WindowsError, e:
             # WindowsError: [Error 32] The process cannot access the file because it is being
             # used by another process: u'C:\\Documents and
             # Settings\\username\\Cookies\\index.dat'
             if 32 != e.winerror and 5 != e.winerror:
                 raise
             try:
                 Windows.delete_locked_file(self.path)
             except:
                 raise
             else:
                 # TRANSLATORS: The file will be deleted when the
                 # system reboots
                 ret['label'] = _('Mark for deletion')
Esempio n. 2
0
    def execute(self, really_delete):
        """Execute the Windows registry cleaner"""
        if 'nt' != os.name:
            raise StopIteration
        _str = None  # string representation
        ret = None  # return value meaning 'deleted' or 'delete-able'
        if self.valuename:
            _str = '%s<%s>' % (self.keyname, self.valuename)
            ret = Windows.delete_registry_value(self.keyname,
                                                self.valuename, really_delete)
        else:
            ret = Windows.delete_registry_key(self.keyname, really_delete)
            _str = self.keyname
        if not ret:
            # Nothing to delete or nothing was deleted.  This return
            # makes the auto-hide feature work nicely.
            raise StopIteration

        ret = {
            'label': _('Delete registry key'),
            'n_deleted': 0,
            'n_special': 1,
            'path': _str,
            'size': 0}

        yield ret
def calc_freq(date_from,date_to,window_size,wanted_list,n,search=[]):
    groups,wanted_list = group(wanted_list)
    # list of tuples of dates
    all_dates = Windows.get_dates(date_from,date_to,365)  # these are not windows, smaller problems
    # for dates and frequencies
    x = []
    y = np.empty((len(wanted_list), 0)).tolist()
    stevec = 0
    print('grem v zanke')
    for tup in all_dates:
        print('leto')
        windows, time = Windows.get_windows(tup[0], tup[1], window_size,search)
        print('windows')
        x += time
        if n==1: grams = count_words(wanted_list,windows)
        else: grams, words_per_window = N_grams.list_of_ngrams(windows, n)
        print('ngrami narjeni')
        for count, i in enumerate(grams):
            #words = words_per_window[count]  #to calculate frequency
            #besede.append(words)
            words =  besede[stevec]
            stevec+=1
            for j,wanted in enumerate(wanted_list):
                frequency = 0
                if wanted in i:
                    frequency = i[wanted] / words
                y[j].append(frequency)
        
        print('ngrami presteti')
    #print(besede)
    print('plotam')
    #print(x,y,wanted_list,groups)
            
    plot(x,y,wanted_list,groups)
    return x,y
Esempio n. 4
0
 def execute(self, really_delete):
     """Make changes and return results"""
     if FileUtilities.whitelisted(self.path):
         yield whitelist(self.path)
         return
     ret = {
         # TRANSLATORS: This is the label in the log indicating will be
         # deleted (for previews) or was actually deleted
         'label': _('Delete'),
         'n_deleted': 1,
         'n_special': 0,
         'path': self.path,
         'size': FileUtilities.getsize(self.path)}
     if really_delete:
         try:
             FileUtilities.delete(self.path, self.shred)
         except WindowsError, e:
             # WindowsError: [Error 32] The process cannot access the file because it is being
             # used by another process: u'C:\\Documents and
             # Settings\\username\\Cookies\\index.dat'
             if 32 != e.winerror and 5 != e.winerror:
                 raise
             try:
                 Windows.delete_locked_file(self.path)
             except:
                 raise
             else:
                 # TRANSLATORS: The file will be deleted when the
                 # system reboots
                 ret['label'] = _('Mark for deletion')
Esempio n. 5
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.__map = dict()
        self.__rootLayout = QtWidgets.QVBoxLayout(self)
        self.__form = QtWidgets.QFormLayout(self)
        self.__vectorBase = {
            "One-Click": [[[win32con.MOD_SHIFT], 49], 'Shift+1'],
            "Create Note": [[[win32con.MOD_CONTROL], 50], 'Ctrl+2'],
            "Paste Back": [[[win32con.MOD_CONTROL, win32con.MOD_SHIFT], 51],
                           'Ctrl+Shift+3'],
            "Save File": [[[win32con.MOD_ALT], 52], 'Alt+4']
        }
        self.__btn = QtWidgets.QPushButton(self)
        self.__btn.setText("Add Element")
        view = Windows.HotKeyObjectView("Enter name here")
        self.__btn.clicked.connect(lambda: self.onAddButton(view))

        for category in self.__vectorBase:
            self.onOkAddButton(
                Windows.HotKeyObjectView(category,
                                         self.__vectorBase[category][0],
                                         self.__vectorBase[category][1]))
        self.__keyThread = Thread.HotKeyThread(self.__map)
        self.__keyThread.showMessage.connect(self.messageShow)
        self.__keyThread.start()
        self.__rootLayout.addLayout(self.__form)
        self.__rootLayout.addWidget(self.__btn)
        self.setLayout(self.__rootLayout)
Esempio n. 6
0
    def execute(self, really_delete):
        """Execute the Windows registry cleaner"""
        if 'nt' != os.name:
            raise StopIteration
        _str = None  # string representation
        ret = None  # return value meaning 'deleted' or 'delete-able'
        if self.valuename:
            _str = '%s<%s>' % (self.keyname, self.valuename)
            ret = Windows.delete_registry_value(self.keyname, self.valuename,
                                                really_delete)
        else:
            ret = Windows.delete_registry_key(self.keyname, really_delete)
            _str = self.keyname
        if not ret:
            # Nothing to delete or nothing was deleted.  This return
            # makes the auto-hide feature work nicely.
            raise StopIteration

        ret = {
            'label': _('Delete registry key'),
            'n_deleted': 0,
            'n_special': 1,
            'path': _str,
            'size': 0
        }

        yield ret
Esempio n. 7
0
    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)
        self.controller = Controller(self)
        self.console = Console()

        self.preferences = Windows.Preferences(self)
        self.preferences.show()

        #self.timeline = Windows.Timeline(self)
        self.mentions = Windows.Timeline(self, "mentions", "Mentions")

        if self.controller.stringForKey("user_access_token") != "":
            self.authentification_succeded()

        self.app.exec_()
Esempio n. 8
0
def browse_folder(parent, title, multiple, stock_button):
    """Ask the user to select a folder.  Return the full path or None."""

    if 'nt' == os.name and None == os.getenv('BB_NATIVE'):
        ret = Windows.browse_folder(
            parent.window.handle if parent else None, title)
        return [ret] if multiple and not ret is None else ret

    # fall back to GTK+
    chooser = gtk.FileChooserDialog(parent=parent,
                                    title=title,
                                    buttons=(
                                        gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                    stock_button, gtk.RESPONSE_OK),
                                    action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
    chooser.set_select_multiple(multiple)
    chooser.set_current_folder(os.path.expanduser('~'))
    resp = chooser.run()
    if multiple:
        ret = chooser.get_filenames()
    else:
        ret = chooser.get_filename()
    chooser.hide()
    chooser.destroy()
    if gtk.RESPONSE_OK != resp:
        # user cancelled
        return None
    return ret
Esempio n. 9
0
def browse_folder(parent, title, multiple, stock_button):
    """Ask the user to select a folder.  Return the full path or None."""

    if 'nt' == os.name and None == os.getenv('BB_NATIVE'):
        ret = Windows.browse_folder(parent.window.handle if parent else None,
                                    title)
        return [ret] if multiple and not ret is None else ret

    # fall back to GTK+
    chooser = gtk.FileChooserDialog(
        parent=parent,
        title=title,
        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, stock_button,
                 gtk.RESPONSE_OK),
        action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
    chooser.set_select_multiple(multiple)
    chooser.set_current_folder(os.path.expanduser('~'))
    resp = chooser.run()
    if multiple:
        ret = chooser.get_filenames()
    else:
        ret = chooser.get_filename()
    chooser.hide()
    chooser.destroy()
    if gtk.RESPONSE_OK != resp:
        # user cancelled
        return None
    return ret
Esempio n. 10
0
 def __init__(self, uac=True, shred_paths=None):
     if uac and 'nt' == os.name and Windows.elevate_privileges():
         # privileges escalated in other process
         sys.exit(0)
     import RecognizeCleanerML
     RecognizeCleanerML.RecognizeCleanerML()
     register_cleaners()
     self.create_window()
     gobject.threads_init()
     if shred_paths:
         self.shred_paths(shred_paths)
         return
     if options.get("first_start") and 'posix' == os.name:
         pref = PreferencesDialog(self.window, self.cb_refresh_operations)
         pref.run()
         options.set('first_start', False)
     if online_update_notification_enabled and options.get("check_online_updates"):
         self.check_online_updates()
     if 'nt' == os.name:
         # BitDefender false positive.  BitDefender didn't mark BleachBit as infected or show
         # anything in its log, but sqlite would fail to import unless BitDefender was in "game mode."
         # http://bleachbit.sourceforge.net/forum/074-fails-errors
         try:
             import sqlite3
         except ImportError, e:
             print e
             print dir(e)
             self.append_text(
                 _("Error loading the SQLite module: the antivirus software may be blocking it."), 'error')
Esempio n. 11
0
File: gm.py Progetto: lowhrtz/PyGM
 def ok(self):
     self.close()
     system_path = self.choose.currentData()
     # self.w = MainWindow( system_path )
     #sys.path.append(os.path.join(THIS_DIR, 'pylib'))
     sys.path.append(system_path)
     import Windows
     self.w = Windows.MainWindow(system_path)
Esempio n. 12
0
def detectos(required_ver, mock=False):
    """Returns boolean whether the detectos is compatible with the
    current operating system, or the mock version, if given."""
    # Do not compare as string because Windows 10 (build 10.0) comes after
    # Windows 8.1 (build 6.3).
    assert(isinstance(required_ver, (str, unicode)))
    current_os = (mock if mock else Windows.parse_windows_build())
    required_ver = required_ver.strip()
    if required_ver.startswith('|'):
        # This is the maximum version
        # For example, |5.1 means Windows XP (5.1) but not Vista (6.0)
        return current_os <= Windows.parse_windows_build(required_ver[1:])
    elif required_ver.endswith('|'):
        # This is the minimum version
        # For example, 6.1| means Windows 7 or later
        return current_os >= Windows.parse_windows_build(required_ver[:-1])
    else:
        # Exact version
        return Windows.parse_windows_build(required_ver) == current_os
Esempio n. 13
0
def detectos(required_ver, mock=False):
    """Returns boolean whether the detectos is compatible with the
    current operating system, or the mock version, if given."""
    # Do not compare as string because Windows 10 (build 10.0) comes after
    # Windows 8.1 (build 6.3).
    assert(isinstance(required_ver, (str, unicode)))
    current_os = (mock if mock else Windows.parse_windows_build())
    required_ver = required_ver.strip()
    if required_ver.startswith('|'):
        # This is the maximum version
        # For example, |5.1 means Windows XP (5.1) but not Vista (6.0)
        return current_os <= Windows.parse_windows_build(required_ver[1:])
    elif required_ver.endswith('|'):
        # This is the minimum version
        # For example, 6.1| means Windows 7 or later
        return current_os >= Windows.parse_windows_build(required_ver[:-1])
    else:
        # Exact version
        return Windows.parse_windows_build(required_ver) == current_os
Esempio n. 14
0
    def execute(self, really_delete):
        """Execute the Windows registry cleaner"""
        if "nt" != os.name:
            raise StopIteration
        _str = None  # string representation
        ret = None  # return value meaning 'deleted' or 'delete-able'
        if self.valuename:
            _str = "%s<%s>" % (self.keyname, self.valuename)
            ret = Windows.delete_registry_value(self.keyname, self.valuename, really_delete)
        else:
            ret = Windows.delete_registry_key(self.keyname, really_delete)
            _str = self.keyname
        if not ret:
            # Nothing to delete or nothing was deleted.  This return
            # makes the auto-hide feature work nicely.
            raise StopIteration

        ret = {"label": _("Delete registry key"), "n_deleted": 0, "n_special": 1, "path": _str, "size": 0}

        yield ret
Esempio n. 15
0
def browse_file(parent, title):
    """Prompt user to select a single file"""

    if 'nt' == os.name and None == os.getenv('BB_NATIVE'):
        return Windows.browse_file(parent.window.handle, title)

    chooser = gtk.FileChooserDialog(title=title,
                                    parent=parent,
                                    action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                    buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
    chooser.set_current_folder(os.path.expanduser('~'))
    resp = chooser.run()
    path = chooser.get_filename()
    chooser.destroy()

    if gtk.RESPONSE_OK != resp:
        # user cancelled
        return None

    return path
Esempio n. 16
0
    def __init__(self):
        print "INIT GAME"
    #**************************** основное window
        self.win_width = 1024#Ширина создаваемого окна
        self.win_height = 700# Высота
        self.win_display = (self.win_width,self.win_height)# Группируем ширину и высоту в одну переменную
        self.timer = pygame.time.Clock()
        self.online = True
    #**************************** инициализация

        self.left = self.right = self.up = self.down = self.space = False
        self.exit_ = True# флаг для выхода
        self.windows = Windows()# инициализируем Windows
        self.player = Player((100,100))# инициализируем Tank
        #self.bul = self.player.shot_bull()
        self.level1 = Level('level1.txt')#Инициализируем level1
        self.level1.load_level()
        self.platforms = self.level1.ret_tiles()

#******************************* свойства для сетевого взаимодействия
        self.id = None
        self.data = {}
        self.data['type'] = 'game'
        self.data['shoot'] = False
        self.move_coord = (0,0,0,0)
        self.stop_coord = (0,0,0,0)

    #**************************** блоки спрайтов

        self.block_list = pygame.sprite.Group() #Это список спрайтов. Каждый блок добавляется в этот список.
        self.all_sprites_list = pygame.sprite.Group()# # Это список каждого спрайта. Все блоки, а также блок игрока.
        self.bullet_list = pygame.sprite.Group()#тес массив спрайтов пули

        self.block_list.add(self.platforms)
        self.all_sprites_list.add(self.player)

        self.cf = ClientConnFactory(self)
        reactor.connectTCP(HOST,PORT,self.cf)
        reactor.run()
Esempio n. 17
0
def browse_file(parent, title):
    """Prompt user to select a single file"""

    if 'nt' == os.name and None == os.getenv('BB_NATIVE'):
        return Windows.browse_file(parent.window.handle, title)

    chooser = gtk.FileChooserDialog(title=title,
                                    parent=parent,
                                    action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                    buttons=(gtk.STOCK_CANCEL,
                                             gtk.RESPONSE_CANCEL,
                                             gtk.STOCK_OPEN, gtk.RESPONSE_OK))
    chooser.set_current_folder(os.path.expanduser('~'))
    resp = chooser.run()
    path = chooser.get_filename()
    chooser.destroy()

    if gtk.RESPONSE_OK != resp:
        # user cancelled
        return None

    return path
Esempio n. 18
0
 def is_running(self):
     """Return whether the program is currently running"""
     for running in self.running:
         test = running[0]
         pathname = running[1]
         if 'exe' == test and 'posix' == os.name:
             if Unix.is_running(pathname):
                 print "debug: process '%s' is running" % pathname
                 return True
         elif 'exe' == test and 'nt' == os.name:
             if Windows.is_process_running(pathname):
                 print "debug: process '%s' is running" % pathname
                 return True
         elif 'pathname' == test:
             expanded = os.path.expanduser(os.path.expandvars(pathname))
             for globbed in glob.iglob(expanded):
                 if os.path.exists(globbed):
                     print "debug: file '%s' exists indicating '%s' is running" % (globbed, self.name)
                     return True
         else:
             raise RuntimeError("Unknown running-detection test '%s'" % test)
     return False
Esempio n. 19
0
 def is_running(self):
     """Return whether the program is currently running"""
     for running in self.running:
         test = running[0]
         pathname = running[1]
         if 'exe' == test and 'posix' == os.name:
             if Unix.is_running(pathname):
                 print "debug: process '%s' is running" % pathname
                 return True
         elif 'exe' == test and 'nt' == os.name:
             if Windows.is_process_running(pathname):
                 print "debug: process '%s' is running" % pathname
                 return True
         elif 'pathname' == test:
             expanded = os.path.expanduser(os.path.expandvars(pathname))
             for globbed in glob.iglob(expanded):
                 if os.path.exists(globbed):
                     print "debug: file '%s' exists indicating '%s' is running" % (globbed, self.name)
                     return True
         else:
             raise RuntimeError(
                 "Unknown running-detection test '%s'" % test)
     return False
Esempio n. 20
0
    def get_commands(self, option_id):
        # This variable will collect fully expanded file names, and
        # at the end of this function, they will be checked they exist
        # and processed through Command.Delete().
        files = []

        # cache
        if 'posix' == os.name and 'cache' == option_id:
            dirname = os.path.expanduser("~/.cache/")
            for filename in children_in_directory(dirname, True):
                if self.whitelisted(filename):
                    continue
                files += [filename]

        # custom
        if 'custom' == option_id:
            for (c_type, c_path) in options.get_custom_paths():
                if 'file' == c_type:
                    files += [c_path]
                elif 'folder' == c_type:
                    files += [c_path]
                    for path in children_in_directory(c_path, True):
                        files += [path]
                else:
                    raise RuntimeError(
                        'custom folder has invalid type %s' % c_type)

        # menu
        menu_dirs = ['~/.local/share/applications',
                     '~/.config/autostart',
                     '~/.gnome/apps/',
                     '~/.gnome2/panel2.d/default/launchers',
                     '~/.gnome2/vfolders/applications/',
                     '~/.kde/share/apps/RecentDocuments/',
                     '~/.kde/share/mimelnk',
                     '~/.kde/share/mimelnk/application/ram.desktop',
                     '~/.kde2/share/mimelnk/application/',
                     '~/.kde2/share/applnk']

        if 'posix' == os.name and 'desktop_entry' == option_id:
            for dirname in menu_dirs:
                for filename in [fn for fn in children_in_directory(dirname, False)
                                 if fn.endswith('.desktop')]:
                    if Unix.is_broken_xdg_desktop(filename):
                        yield Command.Delete(filename)

        # unwanted locales
        if 'posix' == os.name and 'localizations' == option_id:
            callback = lambda locale, language: options.get_language(language)
            for path in Unix.locales.localization_paths(callback):
                yield Command.Delete(path)

        # Windows logs
        if 'nt' == os.name and 'logs' == option_id:
            paths = (
                '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\*.log',
                '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\user.dmp',
                '$LocalAppData\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*',
                '$LocalAppData\\Microsoft\\Windows\WER\\ReportQueue\\*\\*',
                '$programdata\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*',
                '$programdata\\Microsoft\\Windows\\WER\\ReportQueue\\*\\*',
                '$localappdata\\Microsoft\\Internet Explorer\\brndlog.bak',
                '$localappdata\\Microsoft\\Internet Explorer\\brndlog.txt',
                '$windir\\*.log',
                '$windir\\imsins.BAK',
                '$windir\\OEWABLog.txt',
                '$windir\\SchedLgU.txt',
                '$windir\\ntbtlog.txt',
                '$windir\\setuplog.txt',
                '$windir\\REGLOCS.OLD',
                '$windir\\Debug\\*.log',
                '$windir\\Debug\\Setup\\UpdSh.log',
                '$windir\\Debug\\UserMode\\*.log',
                '$windir\\Debug\\UserMode\\ChkAcc.bak',
                '$windir\\Debug\\UserMode\\userenv.bak',
                '$windir\\Microsoft.NET\Framework\*\*.log',
                '$windir\\pchealth\\helpctr\\Logs\\hcupdate.log',
                '$windir\\security\\logs\\*.log',
                '$windir\\security\\logs\\*.old',
                '$windir\\system32\\TZLog.log',
                '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.bak',
                '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.txt',
                '$windir\\system32\\LogFiles\\AIT\\AitEventLog.etl.???',
                '$windir\\system32\\LogFiles\\Firewall\\pfirewall.log*',
                '$windir\\system32\\LogFiles\\Scm\\SCM.EVM*',
                '$windir\\system32\\LogFiles\\WMI\\Terminal*.etl',
                '$windir\\system32\\LogFiles\\WMI\\RTBackup\EtwRT.*etl',
                '$windir\\system32\\wbem\\Logs\\*.lo_',
                '$windir\\system32\\wbem\\Logs\\*.log', )

            for path in paths:
                expanded = os.path.expandvars(path)
                for globbed in glob.iglob(expanded):
                    files += [globbed]

        # memory
        if sys.platform.startswith('linux') and 'memory' == option_id:
            yield Command.Function(None, Memory.wipe_memory, _('Memory'))

        # memory dump
        # how to manually create this file
        # http://www.pctools.com/guides/registry/detail/856/
        if 'nt' == os.name and 'memory_dump' == option_id:
            fname = os.path.expandvars('$windir\\memory.dmp')
            if os.path.exists(fname):
                files += [fname]
            for fname in glob.iglob(os.path.expandvars('$windir\\Minidump\\*.dmp')):
                files += [fname]

        # most recently used documents list
        if 'posix' == os.name and 'recent_documents' == option_id:
            files += [os.path.expanduser("~/.recently-used")]
            # GNOME 2.26 (as seen on Ubuntu 9.04) will retain the list
            # in memory if it is simply deleted, so it must be shredded
            # (or at least truncated).
            #
            # GNOME 2.28.1 (Ubuntu 9.10) and 2.30 (10.04) do not re-read
            # the file after truncation, but do re-read it after
            # shreading.
            #
            # https://bugzilla.gnome.org/show_bug.cgi?id=591404
            for pathname in ["~/.recently-used.xbel", "~/.local/share/recently-used.xbel"]:
                pathname = os.path.expanduser(pathname)
                if os.path.lexists(pathname):
                    yield Command.Shred(pathname)
                    if HAVE_GTK:
                        gtk.RecentManager().purge_items()

        if 'posix' == os.name and 'rotated_logs' == option_id:
            for path in Unix.rotated_logs():
                yield Command.Delete(path)

        # temporary files
        if 'posix' == os.name and 'tmp' == option_id:
            dirnames = ['/tmp', '/var/tmp']
            for dirname in dirnames:
                for path in children_in_directory(dirname, True):
                    is_open = FileUtilities.openfiles.is_open(path)
                    ok = not is_open and os.path.isfile(path) and \
                        not os.path.islink(path) and \
                        FileUtilities.ego_owner(path) and \
                        not self.whitelisted(path)
                    if ok:
                        yield Command.Delete(path)

        # temporary files
        if 'nt' == os.name and 'tmp' == option_id:
            dirname = os.path.expandvars(
                "$USERPROFILE\\Local Settings\\Temp\\")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expandvars("$windir\\temp\\")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # trash
        if 'posix' == os.name and 'trash' == option_id:
            dirname = os.path.expanduser("~/.Trash")
            for filename in children_in_directory(dirname, False):
                yield Command.Delete(filename)
            # fixme http://www.ramendik.ru/docs/trashspec.html
            # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
            # ~/.local/share/Trash
            # * GNOME 2.22, Fedora 9
            # * KDE 4.1.3, Ubuntu 8.10
            dirname = os.path.expanduser("~/.local/share/Trash/files")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/info")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/expunged")
            # [email protected] tells me that the trash
            # backend puts files in here temporary, but in some situations
            # the files are stuck.
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # clipboard
        if HAVE_GTK and 'clipboard' == option_id:
            def clear_clipboard():
                gtk.gdk.threads_enter()
                clipboard = gtk.clipboard_get()
                clipboard.set_text("")
                gtk.gdk.threads_leave()
                return 0
            yield Command.Function(None, clear_clipboard, _('Clipboard'))

        # overwrite free space
        shred_drives = options.get_list('shred_drives')
        if 'free_disk_space' == option_id and shred_drives:
            for pathname in shred_drives:
                # TRANSLATORS: 'Free' means 'unallocated.'
                # %s expands to a path such as C:\ or /tmp/
                display = _("Overwrite free disk space %s") % pathname

                def wipe_path_func():
                    for ret in FileUtilities.wipe_path(pathname, idle=True):
                        # Yield control to GTK idle because this process
                        # is very slow.  Also display progress.
                        yield ret
                    yield 0
                yield Command.Function(None, wipe_path_func, display)

        # MUICache
        if 'nt' == os.name and 'muicache' == option_id:
            keys = (
                'HKCU\\Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache',
                'HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache')
            for key in keys:
                yield Command.Winreg(key, None)

        # prefetch
        if 'nt' == os.name and 'prefetch' == option_id:
            for path in glob.iglob(os.path.expandvars('$windir\\Prefetch\\*.pf')):
                yield Command.Delete(path)

        # recycle bin
        if 'nt' == os.name and 'recycle_bin' == option_id:
            for drive in Windows.get_fixed_drives():
                # TRANSLATORS: %s expands to a drive letter such as C:\ or D:\
                label = _("Recycle bin %s") % drive

                def emptyrecyclebin():
                    return Windows.empty_recycle_bin(drive, True)
                # fixme: enable size preview
                yield Command.Function(None, emptyrecyclebin, label)

        # Windows Updates
        if 'nt' == os.name and 'updates' == option_id:
            for wu in Windows.delete_updates():
                yield wu

        # return queued files
        for filename in files:
            if os.path.lexists(filename):
                yield Command.Delete(filename)
Esempio n. 21
0
    def get_commands(self, option_id):
        # This variable will collect fully expanded file names, and
        # at the end of this function, they will be checked they exist
        # and processed through Command.Delete().
        files = []

        # cache
        if "posix" == os.name and "cache" == option_id:
            dirname = os.path.expanduser("~/.cache/")
            for filename in children_in_directory(dirname, True):
                if self.whitelisted(filename):
                    continue
                files += [filename]

        # custom
        if "custom" == option_id:
            for (c_type, c_path) in options.get_custom_paths():
                if "file" == c_type:
                    files += [c_path]
                elif "folder" == c_type:
                    files += [c_path]
                    for path in children_in_directory(c_path, True):
                        files += [path]
                else:
                    raise RuntimeError("custom folder has invalid type %s" % c_type)

        # menu
        menu_dirs = [
            "~/.local/share/applications",
            "~/.config/autostart",
            "~/.gnome/apps/",
            "~/.gnome2/panel2.d/default/launchers",
            "~/.gnome2/vfolders/applications/",
            "~/.kde/share/apps/RecentDocuments/",
            "~/.kde/share/mimelnk",
            "~/.kde/share/mimelnk/application/ram.desktop",
            "~/.kde2/share/mimelnk/application/",
            "~/.kde2/share/applnk",
        ]

        if "posix" == os.name and "desktop_entry" == option_id:
            for dirname in menu_dirs:
                for filename in [fn for fn in children_in_directory(dirname, False) if fn.endswith(".desktop")]:
                    if Unix.is_broken_xdg_desktop(filename):
                        yield Command.Delete(filename)

        # unwanted locales
        if "posix" == os.name and "localizations" == option_id:
            for path in Unix.locales.localization_paths(locales_to_keep=options.get_languages()):
                if os.path.isdir(path):
                    for f in FileUtilities.children_in_directory(path, True):
                        yield Command.Delete(f)
                yield Command.Delete(path)

        # Windows logs
        if "nt" == os.name and "logs" == option_id:
            paths = (
                "$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\*.log",
                "$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\user.dmp",
                "$LocalAppData\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*",
                "$LocalAppData\\Microsoft\\Windows\WER\\ReportQueue\\*\\*",
                "$programdata\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*",
                "$programdata\\Microsoft\\Windows\\WER\\ReportQueue\\*\\*",
                "$localappdata\\Microsoft\\Internet Explorer\\brndlog.bak",
                "$localappdata\\Microsoft\\Internet Explorer\\brndlog.txt",
                "$windir\\*.log",
                "$windir\\imsins.BAK",
                "$windir\\OEWABLog.txt",
                "$windir\\SchedLgU.txt",
                "$windir\\ntbtlog.txt",
                "$windir\\setuplog.txt",
                "$windir\\REGLOCS.OLD",
                "$windir\\Debug\\*.log",
                "$windir\\Debug\\Setup\\UpdSh.log",
                "$windir\\Debug\\UserMode\\*.log",
                "$windir\\Debug\\UserMode\\ChkAcc.bak",
                "$windir\\Debug\\UserMode\\userenv.bak",
                "$windir\\Microsoft.NET\Framework\*\*.log",
                "$windir\\pchealth\\helpctr\\Logs\\hcupdate.log",
                "$windir\\security\\logs\\*.log",
                "$windir\\security\\logs\\*.old",
                "$windir\\SoftwareDistribution\\*.log",
                "$windir\\SoftwareDistribution\\DataStore\\Logs\\*",
                "$windir\\system32\\TZLog.log",
                "$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.bak",
                "$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.txt",
                "$windir\\system32\\LogFiles\\AIT\\AitEventLog.etl.???",
                "$windir\\system32\\LogFiles\\Firewall\\pfirewall.log*",
                "$windir\\system32\\LogFiles\\Scm\\SCM.EVM*",
                "$windir\\system32\\LogFiles\\WMI\\Terminal*.etl",
                "$windir\\system32\\LogFiles\\WMI\\RTBackup\EtwRT.*etl",
                "$windir\\system32\\wbem\\Logs\\*.lo_",
                "$windir\\system32\\wbem\\Logs\\*.log",
            )

            for path in paths:
                expanded = os.path.expandvars(path)
                for globbed in glob.iglob(expanded):
                    files += [globbed]

        # memory
        if sys.platform.startswith("linux") and "memory" == option_id:
            yield Command.Function(None, Memory.wipe_memory, _("Memory"))

        # memory dump
        # how to manually create this file
        # http://www.pctools.com/guides/registry/detail/856/
        if "nt" == os.name and "memory_dump" == option_id:
            fname = os.path.expandvars("$windir\\memory.dmp")
            if os.path.exists(fname):
                files += [fname]
            for fname in glob.iglob(os.path.expandvars("$windir\\Minidump\\*.dmp")):
                files += [fname]

        # most recently used documents list
        if "posix" == os.name and "recent_documents" == option_id:
            files += [os.path.expanduser("~/.recently-used")]
            # GNOME 2.26 (as seen on Ubuntu 9.04) will retain the list
            # in memory if it is simply deleted, so it must be shredded
            # (or at least truncated).
            #
            # GNOME 2.28.1 (Ubuntu 9.10) and 2.30 (10.04) do not re-read
            # the file after truncation, but do re-read it after
            # shredding.
            #
            # https://bugzilla.gnome.org/show_bug.cgi?id=591404
            for pathname in ["~/.recently-used.xbel", "~/.local/share/recently-used.xbel"]:
                pathname = os.path.expanduser(pathname)
                if os.path.lexists(pathname):
                    yield Command.Shred(pathname)
                    if HAVE_GTK:
                        gtk.RecentManager().purge_items()

        if "posix" == os.name and "rotated_logs" == option_id:
            for path in Unix.rotated_logs():
                yield Command.Delete(path)

        # temporary files
        if "posix" == os.name and "tmp" == option_id:
            dirnames = ["/tmp", "/var/tmp"]
            for dirname in dirnames:
                for path in children_in_directory(dirname, True):
                    is_open = FileUtilities.openfiles.is_open(path)
                    ok = (
                        not is_open
                        and os.path.isfile(path)
                        and not os.path.islink(path)
                        and FileUtilities.ego_owner(path)
                        and not self.whitelisted(path)
                    )
                    if ok:
                        yield Command.Delete(path)

        # temporary files
        if "nt" == os.name and "tmp" == option_id:
            dirname = os.path.expandvars("$USERPROFILE\\Local Settings\\Temp\\")
            # whitelist the folder %TEMP%\Low but not its contents
            # https://bugs.launchpad.net/bleachbit/+bug/1421726
            low = os.path.join(dirname, "low").lower()
            for filename in children_in_directory(dirname, True):
                if not low == filename.lower():
                    yield Command.Delete(filename)
            dirname = os.path.expandvars("$windir\\temp\\")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # trash
        if "posix" == os.name and "trash" == option_id:
            dirname = os.path.expanduser("~/.Trash")
            for filename in children_in_directory(dirname, False):
                yield Command.Delete(filename)
            # fixme http://www.ramendik.ru/docs/trashspec.html
            # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
            # ~/.local/share/Trash
            # * GNOME 2.22, Fedora 9
            # * KDE 4.1.3, Ubuntu 8.10
            dirname = os.path.expanduser("~/.local/share/Trash/files")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/info")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/expunged")
            # [email protected] tells me that the trash
            # backend puts files in here temporary, but in some situations
            # the files are stuck.
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # clipboard
        if HAVE_GTK and "clipboard" == option_id:

            def clear_clipboard():
                gtk.gdk.threads_enter()
                clipboard = gtk.clipboard_get()
                clipboard.set_text("")
                gtk.gdk.threads_leave()
                return 0

            yield Command.Function(None, clear_clipboard, _("Clipboard"))

        # overwrite free space
        shred_drives = options.get_list("shred_drives")
        if "free_disk_space" == option_id and shred_drives:
            for pathname in shred_drives:
                # TRANSLATORS: 'Free' means 'unallocated.'
                # %s expands to a path such as C:\ or /tmp/
                display = _("Overwrite free disk space %s") % pathname

                def wipe_path_func():
                    for ret in FileUtilities.wipe_path(pathname, idle=True):
                        # Yield control to GTK idle because this process
                        # is very slow.  Also display progress.
                        yield ret
                    yield 0

                yield Command.Function(None, wipe_path_func, display)

        # MUICache
        if "nt" == os.name and "muicache" == option_id:
            keys = (
                "HKCU\\Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache",
                "HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache",
            )
            for key in keys:
                yield Command.Winreg(key, None)

        # prefetch
        if "nt" == os.name and "prefetch" == option_id:
            for path in glob.iglob(os.path.expandvars("$windir\\Prefetch\\*.pf")):
                yield Command.Delete(path)

        # recycle bin
        if "nt" == os.name and "recycle_bin" == option_id:
            # This method allows shredding
            for path in Windows.get_recycle_bin():
                yield Command.Delete(path)
            # If there were any files deleted, Windows XP will show the
            # wrong icon for the recycle bin indicating it is not empty.
            # The icon will be incorrect until logging in to Windows again
            # or until it is emptied using the Windows API call for emptying
            # the recycle bin.

            # Windows 10 refreshes the recycle bin icon when the user
            # opens the recycle bin folder.

            # This is a hack to refresh the icon.
            import tempfile

            tmpdir = tempfile.mkdtemp()
            Windows.move_to_recycle_bin(tmpdir)
            try:
                Windows.empty_recycle_bin(None, True)
            except:
                logger = logging.getLogger(__name__)
                logger.info("error in empty_recycle_bin()", exc_info=True)

        # Windows Updates
        if "nt" == os.name and "updates" == option_id:
            for wu in Windows.delete_updates():
                yield wu

        # return queued files
        for filename in files:
            if os.path.lexists(filename):
                yield Command.Delete(filename)
Esempio n. 22
0
class Game():
    def __init__(self):
        print "INIT GAME"
    #**************************** основное window
        self.win_width = 1024#Ширина создаваемого окна
        self.win_height = 700# Высота
        self.win_display = (self.win_width,self.win_height)# Группируем ширину и высоту в одну переменную
        self.timer = pygame.time.Clock()
        self.online = True
    #**************************** инициализация

        self.left = self.right = self.up = self.down = self.space = False
        self.exit_ = True# флаг для выхода
        self.windows = Windows()# инициализируем Windows
        self.player = Player((100,100))# инициализируем Tank
        #self.bul = self.player.shot_bull()
        self.level1 = Level('level1.txt')#Инициализируем level1
        self.level1.load_level()
        self.platforms = self.level1.ret_tiles()

#******************************* свойства для сетевого взаимодействия
        self.id = None
        self.data = {}
        self.data['type'] = 'game'
        self.data['shoot'] = False
        self.move_coord = (0,0,0,0)
        self.stop_coord = (0,0,0,0)

    #**************************** блоки спрайтов

        self.block_list = pygame.sprite.Group() #Это список спрайтов. Каждый блок добавляется в этот список.
        self.all_sprites_list = pygame.sprite.Group()# # Это список каждого спрайта. Все блоки, а также блок игрока.
        self.bullet_list = pygame.sprite.Group()#тес массив спрайтов пули

        self.block_list.add(self.platforms)
        self.all_sprites_list.add(self.player)

        self.cf = ClientConnFactory(self)
        reactor.connectTCP(HOST,PORT,self.cf)
        reactor.run()
    #****************************инициализируем pygame (получаем screen)
    def init_window(self):
        pygame.init()#инициализируем pygame
        self.screen = pygame.display.set_mode(self.win_display)# Создаем окошко
        pygame.display.set_caption('Tanks')#название шапки "капчи"

    #****************************обработка процессов и действий (обработка нажатий (mouse and keyboard и др.))
    def tick(self):
        self.timer.tick(60)
    #****************************обработка
        for event in pygame.event.get():
            if event.type == KEYDOWN and event.key == K_LEFT:
                self.left = True

                #self.sendData("left = True")
                self.data['coordinate'] = (1,0,0,0)
                self.sendData(self.data)
            if event.type == KEYUP and event.key == K_LEFT:
                self.left = False
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)

            if event.type == KEYDOWN and event.key == K_RIGHT:
                self.right = True
                #self.sendData('self.right = True')
                self.data['coordinate'] = (0,1,0,0)
                self.sendData(self.data)

            if event.type == KEYUP and event.key == K_RIGHT:
                self.right = False
                #self.sendData('self.right = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_UP:
                self.up = True
                #self.sendData('self.up = True')
                self.data['coordinate'] = (0,0,1,0)
                self.sendData(self.data)

            if event.type == KEYUP and event.key == K_UP:
                self.up = False
                #self.sendData('self.up = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_DOWN:
                self.down = True
                self.data['coordinate'] = (0,0,0,1)
                self.sendData(self.data)

                #self.sendData('self.down = True')
            if event.type == KEYUP and event.key == K_DOWN:
                self.down = False
                #self.sendData('self.down = False')
                self.data['coordinate'] = self.stop_coord
                self.sendData(self.data)


            if event.type == KEYDOWN and event.key == K_SPACE:
                self.space = True
                #self.sendData('self.space = True')
                self.data['shoot'] = True
                self.sendData(self.data)
            if event.type == KEYUP and event.key == K_SPACE:
                self.shot_bull_game()
                self.space = False
                self.data['shoot'] = False
                self.sendData(self.data)

            if (event.type == QUIT) or (event.type == KEYDOWN and event.key == K_ESCAPE):
                self.sendData("GOODBYE!!!!!!!")
                reactor.stop()
                sys.exit(0)

        self.draw_game()
        self.update_game()


    #****************************отобрыжение процессов
    def draw_game(self):
        self.windows.draw_windows(self.screen)#рисуем окна
        self.all_sprites_list.draw(self.screen)
        self.block_list.draw(self.screen)
        self.bullet_list.draw(self.screen)
        pygame.display.update()# обновление и вывод всех изменений на экран

    #****************************shot
    def shot_bull_game(self):
        self.player.shot_bull()
        self.bullet_list.add(self.player.ret_bull())

    #**************************** при столкновении пули с объектом удаление пули
    def destroy_bull_game(self):

        sprite.groupcollide(self.block_list,self.bullet_list,0,1)

    #**************************** update
    def update_game(self):
        self.player.tank_update(self.left,self.right,self.up,self.down,self.space,self.platforms)
        self.destroy_bull_game()
        self.player.bull_move()

    #****************************удаление данных (destroy data here)
    def end_pygame():
        pygame.quit()

    #****************************ЗАПУСК ИГРЫ
    def play_game(self):
        print 'play_game'
        self.init_window()
        #self.end_pygame()

    #****************************фунция запуска

    def sendData(self, data):
        self.cf.conn.send(data)

    def getData(self, data):
        print "INCOMING: ", data
        self.parseData(data)

    def parseData(self, data):
        print type(data)
        if isinstance(data, dict):
            print "PARSING"
            print data['id']
            if data.get('type') == 'start':
                print 'START  THE GAME'
            for k in data:
                print "KEY: ",k," VALUE: ",data[k]
Esempio n. 23
0
#
# openWNS is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License version 2 as published by the
# Free Software Foundation;
#
# openWNS is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

import sys
import os
import traceback
import Windows
from PyQt4 import QtGui

application = QtGui.QApplication(sys.argv)
application.setQuitOnLastWindowClosed(True)
application.setApplicationName("ResourceViewer")
application.setWindowIcon(QtGui.QIcon(":/icons/icon.png"))
application.setOrganizationName("TUM")
application.setOrganizationDomain("www.lkn.ei.tum.de")
widget = Windows.Main()
widget.show()
sys.exit(application.exec_())
Esempio n. 24
0
 def handle_section(self, section):
     """Parse a section"""
     def detect_file(rawpath):
         pathname = os.path.expandvars(preexpand(rawpath))
         return os.path.exists(pathname)
     # if simple detection fails then discard the section
     if self.parser.has_option(section, 'detect'):
         key = self.parser.get(section, 'detect')
         if not Windows.detect_registry_key(key):
             return
     if self.parser.has_option(section, 'detectfile'):
         if not detect_file(self.parser.get(section, 'detectfile')):
             return
     if self.parser.has_option(section, 'detectos'):
         required_ver = self.parser.get(section, 'detectos')
         if not detectos(required_ver):
             return
     # in case of multiple detection, discard if none match
     if self.parser.has_option(section, 'detectfile1'):
         matches = 0
         for n in range(1, MAX_DETECT):
             option_id = 'detectfile%d' % n
             if self.parser.has_option(section, option_id):
                 if detect_file(self.parser.get(section, option_id)):
                     matches = matches + 1
         if 0 == matches:
             return
     if self.parser.has_option(section, 'detect1'):
         matches = 0
         for n in range(1, MAX_DETECT):
             option_id = 'detect%d' % n
             if self.parser.has_option(section, option_id):
                 if Windows.detect_registry_key(self.parser.get(section, option_id)):
                     matches = matches + 1
         if 0 == matches:
             return
     # not yet implemented
     if self.parser.has_option(section, 'excludekey'):
         print 'ERROR: ExcludeKey not implemented, section=', section
         return
     # there are two ways to specify sections: langsecref= and section=
     if self.parser.has_option(section, 'langsecref'):
         # verify the langsecref number is known
         # langsecref_num is 3021, games, etc.
         langsecref_num = self.parser.get(section, 'langsecref')
     elif self.parser.has_option(section, 'section'):
         langsecref_num = self.parser.get(section, 'section')
     else:
         print 'ERROR: neither option LangSecRef nor Section found in section %s' % (section)
         return
     # find the BleachBit internal cleaner ID
     lid = self.section_to_cleanerid(langsecref_num)
     self.cleaners[lid].add_option(
         section2option(section), section.replace('*', ''), '')
     for option in self.parser.options(section):
         if option.startswith('filekey'):
             self.handle_filekey(lid, section, option)
         elif option.startswith('regkey'):
             self.handle_regkey(lid, section, option)
         elif option == 'warning':
             self.cleaners[lid].set_warning(
                 section2option(section), self.parser.get(section, 'warning'))
         elif option in ('default', 'detectfile', 'detect', 'langsecref', 'section') \
             or ['detect%d' % x for x in range(1, MAX_DETECT)] \
                 or ['detectfile%d' % x for x in range(1, MAX_DETECT)]:
             pass
         else:
             print 'WARNING: unknown option %s in section %s' % (option, section)
             return
Esempio n. 25
0
 def get_drive_serial(self):
     return Windows.get_volume_serial(self.path[:2])
Esempio n. 26
0
import Windows

Windows.MainWindow()
Esempio n. 27
0
    def __init__(self , cloud_options , migrate_options, sys_adjust_overrides , skip_imaging=False, resume_upload=False, skip_upload=False ,\
        self_checks=False , limits = None , insert_vitio = False , insert_xen = False, backup_mode = False):
        """
        Inits the Migrator mega-class. 

        Args:
            cloud_options: CloudConfig.CloudConfig - options specifiying cloud parameters. These options are passed to cloud instance generators and upload channels
            migrate_options: MigrateConfig.MigrateConfig - options specifiying how the image should be migrated. These options alters the Migrator behaviour
            sys_adjust_overrides: dict - dict-like class overriding default options specifying how the resulting system should be adjusted
            skip_imaging: bool - flag to skip imaging activities. Needed primarily for resume-upload scenarios
            resume_upload: bool - flag to resume upload instead of starting new one. Needed primarily for resume-upload scenarios
            skip_upload: bool - flag to skip upload at all. Needed primarily in case when the upload is already done but cloud server is not created yet
            self_checks: bool - some self-checks on images\registry during the Migrator work (doesn't work for now!)
            limits: ? (currently long) - the limitation of data to be transfered
            insert_vitio : bool - inserts virtio drivers to the running system. Note, this option can be overriden with migrate_options.insertVirtIo()
            insert_xen : bool - inserts xen drivers to the running system. Note, this option can be overriden with migrate_options.insertXen()
            backup_mode : bool - doesn't create a VM inside the cloud. Just stores image there
        """
        self.__adjustedSystemBackupSource = None
        self.__systemBackupSource = None
        self.__systemTransferTarget = None
        self.__systemAdjustOptions = None
        # the channel is underlying connection to transfer the data for system target
        self.__systemTransferChannel = None
        self.__systemMedia = None

        self.__limitUpload = limits

        self.__adjustOption = None
        self.__migrateOptions = migrate_options
        self.__cloudOptions = cloud_options

        self.__dataBackupSourceList = dict(
        )  # the key is data volume device path
        self.__dataTransferTargetList = dict()
        self.__dataChannelList = dict()
        self.__dataMediaList = dict()

        self.__runOnWindows = False

        self.__selfChecks = self_checks
        self.__skipImaging = skip_imaging
        self.__skipUpload = skip_upload
        self.__resumeUpload = resume_upload
        self.__backupMode = backup_mode

        self.__resultingInstance = None

        self.__cloudName = self.__cloudOptions.getTargetCloud()

        #extra megabyte of additional size to store mbr, etc on the image
        self.__additionalMediaSize = 0x800 * 0x200
        self.__os = None

        self.__fileBackup = False
        self.__insertVirtio = insert_vitio or migrate_options.insertVirtIo()
        self.__insertXen = insert_xen or migrate_options.insertXen()

        self.__error = False

        #TODO: pass this parm somehow. Thru migrate\adjust overrides?
        self.__linuxGC = True

        #TODO: analyze both host and source systems
        if self.__migrateOptions.getHostOs() == "Windows":
            import Windows
            self.__windows = Windows.Windows(self.__insertVirtio,
                                             self.__insertXen)
            self.__runOnWindows = True
            self.__winSystemAdjustOptions = self.__windows.createSystemAdjustOptions(
                sys_adjust_overrides)
            self.__systemAdjustOptions = self.__winSystemAdjustOptions
            self.__os = self.__windows
            #self.__winSystemAdjustOptions
        else:
            if self.__linuxGC:
                import Linux_GC
                self.__linux = Linux_GC.Linux()
            else:
                import Linux
                self.__linux = Linux.Linux()
            self.__systemAdjustOptions = self.__linux.createSystemAdjustOptions(
            )
            self.__os = self.__linux
Esempio n. 28
0
 def hash_drive_serial(self, salt=''):
     vol_hash = md5.new()
     vol_serial = Windows.get_volume_serial(self.path[:2])
     vol_hash.update(vol_serial + salt)
     return vol_hash.hexdigest()
Esempio n. 29
0
    def createVolumesList(self,
                          config,
                          configfile,
                          imagedir,
                          imagetype,
                          upload_prefix=""):
        """creates volume list"""
        volumes = list()
        if config.has_section('Volumes'):

            #check what volumes to migrate
            letters = ""
            letterslist = list()
            if config.has_option('Volumes', 'letters'):
                letters = config.get('Volumes', 'letters')
            letterslist = letters.split(',')

            # if system is set , add autolocated system volume by default
            if config.has_option('Volumes', 'system'):
                addsys = config.getboolean('Volumes', 'system')
                if addsys:
                    logging.debug("system is set in volumes config")
                    sysvol = os.environ['windir'].split(
                        ':'
                    )[0]  #todo: change to cross-platform way. windir is set artificially at the program start for linux
                    if not sysvol in letterslist:
                        letterslist.append(sysvol)
                        logging.debug("appending system volume " + sysvol +
                                      " to the volume list")
                    else:
                        logging.debug("skipping  " + sysvol +
                                      " - it is already in the list")

            logging.debug("Volume letters to process are: " + str(letterslist))
            for letter in letterslist:
                letter = str(letter).strip()  #remove spaces between commas
                if not letter:
                    continue
                letter = str(letter).strip()
                if os.name == 'nt':
                    devicepath = '\\\\.\\' + letter + ':'
                    sys.path.append('./Windows')
                    try:
                        import Windows
                        size = Windows.Windows().getSystemInfo().getVolumeInfo(
                            letter + ":").getSize()
                    except Exception as e:
                        logging.debug("Cannot get local data on volume " +
                                      letter + " " + str(e))
                        size = 0
                else:
                    if not "/dev/" in letter:
                        devicepath = "/dev/" + letter
                    else:
                        devicepath = letter
                    sys.path.append('./Linux')
                    try:
                        import Linux
                        size = Linux.Linux().getSystemInfo().getVolumeInfo(
                            devicepath).getSize()
                    except Exception as e:
                        logging.debug("Cannot get local data on volume " +
                                      letter + " " + str(e))
                        size = 0
                volume = VolumeMigrateIniConfig(config, configfile, letter,
                                                devicepath)
                if volume.getImagePath() == '':
                    volume.setImagePath(imagedir + "/" + letter + "." +
                                        imagetype)
                if volume.getImageSize() == 0:
                    volume.setImageSize(size)
                if volume.getUploadPath() == '':
                    volume.setUploadPath(upload_prefix +
                                         os.environ['COMPUTERNAME'] + "-" +
                                         letter)
                volumes.append(volume)
        return volumes
Esempio n. 30
0
 def handle_section(self, section):
     """Parse a section"""
     # if simple detection fails then discard the section
     if self.parser.has_option(section, 'detect'):
         key = self.parser.get(section, 'detect')
         if not Windows.detect_registry_key(key):
             return
     if self.parser.has_option(section, 'detectfile'):
         if not detect_file(self.parser.get(section, 'detectfile')):
             return
     if self.parser.has_option(section, 'detectos'):
         required_ver = self.parser.get(section, 'detectos')
         if not detectos(required_ver):
             return
     # in case of multiple detection, discard if none match
     if self.parser.has_option(section, 'detectfile1'):
         matches = 0
         for n in range(1, MAX_DETECT):
             option_id = 'detectfile%d' % n
             if self.parser.has_option(section, option_id):
                 if detect_file(self.parser.get(section, option_id)):
                     matches = matches + 1
         if 0 == matches:
             return
     if self.parser.has_option(section, 'detect1'):
         matches = 0
         for n in range(1, MAX_DETECT):
             option_id = 'detect%d' % n
             if self.parser.has_option(section, option_id):
                 if Windows.detect_registry_key(self.parser.get(section, option_id)):
                     matches = matches + 1
         if 0 == matches:
             return
     # excludekeys ignores a file, path, or registry key
     excludekeys = []
     if self.parser.has_option(section, 'excludekey1'):
         for n in range(1, MAX_DETECT):
             option_id = 'excludekey%d' % n
             if self.parser.has_option(section, option_id):
                 excludekeys.append(
                     self.excludekey_to_nwholeregex(self.parser.get(section, option_id)))
     # there are two ways to specify sections: langsecref= and section=
     if self.parser.has_option(section, 'langsecref'):
         # verify the langsecref number is known
         # langsecref_num is 3021, games, etc.
         langsecref_num = self.parser.get(section, 'langsecref')
     elif self.parser.has_option(section, 'section'):
         langsecref_num = self.parser.get(section, 'section')
     else:
         print 'ERROR: neither option LangSecRef nor Section found in section %s' % (section)
         return
     # find the BleachBit internal cleaner ID
     lid = self.section_to_cleanerid(langsecref_num)
     self.cleaners[lid].add_option(
         section2option(section), section.replace('*', ''), '')
     for option in self.parser.options(section):
         if option.startswith('filekey'):
             self.handle_filekey(lid, section, option, excludekeys)
         elif option.startswith('regkey'):
             self.handle_regkey(lid, section, option)
         elif option == 'warning':
             self.cleaners[lid].set_warning(
                 section2option(section), self.parser.get(section, 'warning'))
         elif option in ('default', 'detectfile', 'detect', 'langsecref', 'section') \
             or ['detect%d' % x for x in range(1, MAX_DETECT)] \
                 or ['detectfile%d' % x for x in range(1, MAX_DETECT)]:
             pass
         else:
             print 'WARNING: unknown option %s in section %s' % (option, section)
             return
Esempio n. 31
0
 def emptyrecyclebin():
     return Windows.empty_recycle_bin(drive, True)
Esempio n. 32
0
        logging.getLogger().addHandler(handler)
    
        #new random seed
        random.seed()
    
        #some legacy command-line support
        if parser.parse_args().output:
            outhandler = logging.FileHandler(parser.parse_args().output , "w" )
            outhandler.setLevel(logging.INFO)
            logging.getLogger().addHandler(outhandler)

        # little hacks to pre-configure env and args
        if os.name == 'nt':
            import Windows
            #converting to unicode, add "CheckWindows" option
            sys.argv = Windows.win32_unicode_argv()
        else:
            print("Non-Windows OS are not supported")
            sys.exit(1)
    
        # starting the heartbeat thread printing some dots while app works
        if parser.parse_args().heartbeat:
            threading.Thread(target = heartbeat, args=(parser.parse_args().heartbeat,) ).start()

        logging.info("\n>>>>>>>>>>>>>>>>> Disk2VHD+ Process ("+ Version.getShortVersionString() + ") is initializing\n")
        logging.info("Full version: " + Version.getFullVersionString())


        config = MigratorConfigurer.MigratorConfigurer()
        # creatiing the config
        if parser.parse_args().config:
Esempio n. 33
0
File: test014.py Progetto: Afey/pyjs
def greet(sender):
    Windows.alert("Hello AJAX!")
Esempio n. 34
0
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import os
import Windows
import Linux


#获取dns列表
dnslist = open('dns.txt', 'r', encoding='utf-8')
dns_list = dnslist.read().split('\n')
dnslist.close()

#获取测试网址
htmllist=open('html.txt', 'r', encoding='utf-8')
html_list=htmllist.read().split('\n')
htmllist.close()

#判断系统
local_systeam=os.name
if local_systeam == 'nt':
    Windows.run(dns_list,html_list)
if local_systeam=='posix':
    Linux.run(dns_list, html_list)
Esempio n. 35
0
 def onAddButton(self, hotKey):
     self.__addWindow = Windows.ChangeOrAddHotKeyWindow(hotKey)
     self.__addWindow.show()
     self.__addWindow.resetParentTread.connect(self.threadReset)
     self.__addWindow.onOkAddButtonNew.connect(self.onOkAddButton)
def greet(sender):
    Windows.alert("Hello AJAX!")
Esempio n. 37
0
    def get_commands(self, option_id):
        # This variable will collect fully expanded file names, and
        # at the end of this function, they will be checked they exist
        # and processed through Command.Delete().
        files = []

        # cache
        if 'posix' == os.name and 'cache' == option_id:
            dirname = os.path.expanduser("~/.cache/")
            for filename in children_in_directory(dirname, True):
                if self.whitelisted(filename):
                    continue
                files += [filename]

        # custom
        if 'custom' == option_id:
            for (c_type, c_path) in options.get_custom_paths():
                if 'file' == c_type:
                    files += [c_path]
                elif 'folder' == c_type:
                    files += [c_path]
                    for path in children_in_directory(c_path, True):
                        files += [path]
                else:
                    raise RuntimeError(
                        'custom folder has invalid type %s' % c_type)

        # menu
        menu_dirs = ['~/.local/share/applications',
                     '~/.config/autostart',
                     '~/.gnome/apps/',
                     '~/.gnome2/panel2.d/default/launchers',
                     '~/.gnome2/vfolders/applications/',
                     '~/.kde/share/apps/RecentDocuments/',
                     '~/.kde/share/mimelnk',
                     '~/.kde/share/mimelnk/application/ram.desktop',
                     '~/.kde2/share/mimelnk/application/',
                     '~/.kde2/share/applnk']

        if 'posix' == os.name and 'desktop_entry' == option_id:
            for dirname in menu_dirs:
                for filename in [fn for fn in children_in_directory(dirname, False)
                                 if fn.endswith('.desktop')]:
                    if Unix.is_broken_xdg_desktop(filename):
                        yield Command.Delete(filename)

        # unwanted locales
        if 'posix' == os.name and 'localizations' == option_id:
            callback = lambda locale, language: options.get_language(language)
            for path in Unix.locales.localization_paths(callback):
                yield Command.Delete(path)

        # Windows logs
        if 'nt' == os.name and 'logs' == option_id:
            paths = (
                '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\*.log',
                '$ALLUSERSPROFILE\\Application Data\\Microsoft\\Dr Watson\\user.dmp',
                '$LocalAppData\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*',
                '$LocalAppData\\Microsoft\\Windows\WER\\ReportQueue\\*\\*',
                '$programdata\\Microsoft\\Windows\\WER\\ReportArchive\\*\\*',
                '$programdata\\Microsoft\\Windows\\WER\\ReportQueue\\*\\*',
                '$localappdata\\Microsoft\\Internet Explorer\\brndlog.bak',
                '$localappdata\\Microsoft\\Internet Explorer\\brndlog.txt',
                '$windir\\*.log',
                '$windir\\imsins.BAK',
                '$windir\\OEWABLog.txt',
                '$windir\\SchedLgU.txt',
                '$windir\\ntbtlog.txt',
                '$windir\\setuplog.txt',
                '$windir\\REGLOCS.OLD',
                '$windir\\Debug\\*.log',
                '$windir\\Debug\\Setup\\UpdSh.log',
                '$windir\\Debug\\UserMode\\*.log',
                '$windir\\Debug\\UserMode\\ChkAcc.bak',
                '$windir\\Debug\\UserMode\\userenv.bak',
                '$windir\\Microsoft.NET\Framework\*\*.log',
                '$windir\\pchealth\\helpctr\\Logs\\hcupdate.log',
                '$windir\\security\\logs\\*.log',
                '$windir\\security\\logs\\*.old',
                '$windir\\system32\\TZLog.log',
                '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.bak',
                '$windir\\system32\\config\\systemprofile\\Application Data\\Microsoft\\Internet Explorer\\brndlog.txt',
                '$windir\\system32\\LogFiles\\AIT\\AitEventLog.etl.???',
                '$windir\\system32\\LogFiles\\Firewall\\pfirewall.log*',
                '$windir\\system32\\LogFiles\\Scm\\SCM.EVM*',
                '$windir\\system32\\LogFiles\\WMI\\Terminal*.etl',
                '$windir\\system32\\LogFiles\\WMI\\RTBackup\EtwRT.*etl',
                '$windir\\system32\\wbem\\Logs\\*.lo_',
                '$windir\\system32\\wbem\\Logs\\*.log', )

            for path in paths:
                expanded = os.path.expandvars(path)
                for globbed in glob.iglob(expanded):
                    files += [globbed]

        # memory
        if sys.platform.startswith('linux') and 'memory' == option_id:
            yield Command.Function(None, Memory.wipe_memory, _('Memory'))

        # memory dump
        # how to manually create this file
        # http://www.pctools.com/guides/registry/detail/856/
        if 'nt' == os.name and 'memory_dump' == option_id:
            fname = os.path.expandvars('$windir\\memory.dmp')
            if os.path.exists(fname):
                files += [fname]
            for fname in glob.iglob(os.path.expandvars('$windir\\Minidump\\*.dmp')):
                files += [fname]

        # most recently used documents list
        if 'posix' == os.name and 'recent_documents' == option_id:
            files += [os.path.expanduser("~/.recently-used")]
            # GNOME 2.26 (as seen on Ubuntu 9.04) will retain the list
            # in memory if it is simply deleted, so it must be shredded
            # (or at least truncated).
            #
            # GNOME 2.28.1 (Ubuntu 9.10) and 2.30 (10.04) do not re-read
            # the file after truncation, but do re-read it after
            # shreading.
            #
            # https://bugzilla.gnome.org/show_bug.cgi?id=591404
            for pathname in ["~/.recently-used.xbel", "~/.local/share/recently-used.xbel"]:
                pathname = os.path.expanduser(pathname)
                if os.path.lexists(pathname):
                    yield Command.Shred(pathname)
                    if HAVE_GTK:
                        gtk.RecentManager().purge_items()

        if 'posix' == os.name and 'rotated_logs' == option_id:
            for path in Unix.rotated_logs():
                yield Command.Delete(path)

        # temporary files
        if 'posix' == os.name and 'tmp' == option_id:
            dirnames = ['/tmp', '/var/tmp']
            for dirname in dirnames:
                for path in children_in_directory(dirname, True):
                    is_open = FileUtilities.openfiles.is_open(path)
                    ok = not is_open and os.path.isfile(path) and \
                        not os.path.islink(path) and \
                        FileUtilities.ego_owner(path) and \
                        not self.whitelisted(path)
                    if ok:
                        yield Command.Delete(path)

        # temporary files
        if 'nt' == os.name and 'tmp' == option_id:
            dirname = os.path.expandvars(
                "$USERPROFILE\\Local Settings\\Temp\\")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expandvars("$windir\\temp\\")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # trash
        if 'posix' == os.name and 'trash' == option_id:
            dirname = os.path.expanduser("~/.Trash")
            for filename in children_in_directory(dirname, False):
                yield Command.Delete(filename)
            # fixme http://www.ramendik.ru/docs/trashspec.html
            # http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
            # ~/.local/share/Trash
            # * GNOME 2.22, Fedora 9
            # * KDE 4.1.3, Ubuntu 8.10
            dirname = os.path.expanduser("~/.local/share/Trash/files")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/info")
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)
            dirname = os.path.expanduser("~/.local/share/Trash/expunged")
            # [email protected] tells me that the trash
            # backend puts files in here temporary, but in some situations
            # the files are stuck.
            for filename in children_in_directory(dirname, True):
                yield Command.Delete(filename)

        # clipboard
        if HAVE_GTK and 'clipboard' == option_id:
            def clear_clipboard():
                gtk.gdk.threads_enter()
                clipboard = gtk.clipboard_get()
                clipboard.set_text("")
                gtk.gdk.threads_leave()
                return 0
            yield Command.Function(None, clear_clipboard, _('Clipboard'))

        # overwrite free space
        shred_drives = options.get_list('shred_drives')
        if 'free_disk_space' == option_id and shred_drives:
            for pathname in shred_drives:
                # TRANSLATORS: 'Free' means 'unallocated.'
                # %s expands to a path such as C:\ or /tmp/
                display = _("Overwrite free disk space %s") % pathname

                def wipe_path_func():
                    for ret in FileUtilities.wipe_path(pathname, idle=True):
                        # Yield control to GTK idle because this process
                        # is very slow.  Also display progress.
                        yield ret
                    yield 0
                yield Command.Function(None, wipe_path_func, display)

        # MUICache
        if 'nt' == os.name and 'muicache' == option_id:
            keys = (
                'HKCU\\Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache',
                'HKCU\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\MuiCache')
            for key in keys:
                yield Command.Winreg(key, None)

        # prefetch
        if 'nt' == os.name and 'prefetch' == option_id:
            for path in glob.iglob(os.path.expandvars('$windir\\Prefetch\\*.pf')):
                yield Command.Delete(path)

        # recycle bin
        if 'nt' == os.name and 'recycle_bin' == option_id:
            for drive in Windows.get_fixed_drives():
                # TRANSLATORS: %s expands to a drive letter such as C:\ or D:\
                label = _("Recycle bin %s") % drive

                def emptyrecyclebin():
                    return Windows.empty_recycle_bin(drive, True)
                # fixme: enable size preview
                yield Command.Function(None, emptyrecyclebin, label)

        # Windows Updates
        if 'nt' == os.name and 'updates' == option_id:
            for wu in Windows.delete_updates():
                yield wu

        # return queued files
        for filename in files:
            if os.path.lexists(filename):
                yield Command.Delete(filename)
Esempio n. 38
0
 def login_with_entity(self, entity):
     self.controller.setStringForKey(entity, "entity")
     self.oauth_implementation = Windows.Oauth(self)
Esempio n. 39
0
 def emptyrecyclebin():
     return Windows.empty_recycle_bin(drive, True)
Esempio n. 40
0
import Windows
app = Windows.Main()
Dir = "D:\\Programming\\Python"
app.searching_dir = Dir
app.main()
app.title("File Explorer")
app.mainloop()
#!/usr/bin python

from tkinter import *
import tkinter.messagebox
import qrcode
from PIL import Image
import LayoutStandard
import Windows

mainWin = Tk()
mainWin.title("Smart Delivery Box")
mainWin.resizable(False, False)

layout = LayoutStandard.LayoutStandard(mainWin)
layout.pack()

Windows.Windows(layout.centro).requestWindow()

mainWin.mainloop()