Exemplo n.º 1
0
 def next():
     reader = Directory().reader("club")
     entry = reader.search()[0].entry_writable()
     result = entry.neatNextUidNumber.value
     entry.neatNextUidNumber = result + 1
     entry.entry_commit_changes()
     return result
Exemplo n.º 2
0
def getInfoDir(dirPath):
    out = subprocess.Popen(['stat', dirPath],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    stdout, stderr = out.communicate()
    res = stdout.decode("utf-8")
    attrs = res.split()
    permission = attrs[2]
    dirNode = int(attrs[3])
    dirOwner = attrs[4]
    groupOwner = attrs[5]
    dirSize = int(attrs[7])
    dirName = attrs[-1].split("/")[-1]
    date = formatDate(res)
    dir = Directory(dirPath, dirName, permission, dirOwner, groupOwner,
                    dirSize, dirNode, date)
    subout = subprocess.Popen(['ls', '-lh', dirPath],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
    substdout, substderr = subout.communicate()
    if len(substdout) == 0: return dir
    subres = substdout.decode("utf-8").splitlines(True)
    for sub in subres:
        subAttrs = sub.split()
        if subAttrs[0].startswith('d'):
            dir.addDirSub(subAttrs[-1])
    return dir
Exemplo n.º 3
0
    def _list_inventory(self):
        d = Directory(self.nodes_uri)

        entities = {}

        def register_fn(dirpath, filenames):
            for f in filter(lambda f: f.endswith(FILE_EXTENSION), filenames):
                name = f[:-len(FILE_EXTENSION)]
                nodeinfo = self.nodeinfo(name)
                entities[name] = nodeinfo

        d.walk(register_fn)

        applications = {}
        classes = {}
        for f, nodeinfo in entities.iteritems():
            for a in nodeinfo['applications']:
                if a in applications:
                    applications[a].append(f)
                else:
                    applications[a] = [f]
            for c in nodeinfo['classes']:
                if c in classes:
                    classes[c].append(f)
                else:
                    classes[c] = [f]

        return entities, applications, classes
Exemplo n.º 4
0
def backup_directories(directories_to_backup):
    """
    Backs up all the directories which have been selected for backup.
    """
    count = 1

    for d in config.DIRECTORIES:
        directory = Directory(d)

        if directory.name in directories_to_backup:
            print_header("Backing up directory %s of %s: %s" % (str(count), len(directories_to_backup), directory.name))

            if device.has_space:
                directory.backup()
            else:
                print "Not enough space on %s to update %s." % (device.name, directory.name)
                log("    %s:" % directory.name)
                log("      copied: False")

            count += 1

        else:
            log("    %s:" % directory.name)
            log("      copied: False")

    # Add a blank line below this backup event's log event to seperate it
    # from the next one.
    log("")
Exemplo n.º 5
0
def sync(fp_source, fp_target, create_copy):
    bk = BookKeeper()
    lst_synced = bk.read()
    lst_source = Directory(fp_source)
    lst_target = Directory(fp_target)

    count = 0
    what = 'copied' if create_copy else 'moved'

    for source in lst_source:
        if source not in lst_synced and source not in lst_target:
            full_source = os.path.join(lst_source.path, source)
            full_target = os.path.join(lst_target.path, source)
            if create_copy:
                shutil.copy(full_source, full_target)
            else:
                shutil.move(full_source, full_target)
            bk.write(source)
            count += 1
            logging.debug('{}: {} {}'.format(lst_source.path, what, source))
        else:
            if source in lst_synced:
                logging.debug('{}: {} already synced'.format(
                    lst_source.path, source))

            if source in lst_target:
                logging.debug('{}: {} at target location'.format(
                    lst_source.path, source))
    logging.info('{} {} of {} files from {} to {}.'.format(
        what, count, len(lst_source), lst_source.path, lst_target.path))
Exemplo n.º 6
0
 def get_entries(self, rel_path=None):
     root = Directory(self.directory.join(rel_path))
     entries = {}
     for song in self.songs:
         if song.directory.name.startswith(root.name):
             rel_depth = song.directory.get_depth() - \
                 root.get_depth()
             rel_path = song.directory.get_layer(root.name, 0)
             if rel_depth > 1:# and not rel_path in entries:
                 if rel_path not in entries:
                     entries[rel_path] = DirectoryEntry(\
                         parent=self.parent_widget, name=rel_path, \
                         start_screen=self.sing_screen, \
                         player=self.player, song_manager=self
                     )
                 if isinstance(entries[rel_path], DirectoryEntry):
                     entries[rel_path].entries.append(song)
             elif rel_depth == 1:
                 entries[rel_path] = SongEntry(\
                     parent = self.parent_widget, song = song, \
                     start_screen = self.sing_screen, \
                     player = self.player, song_manager=self,
                     start_button_text=self.parent_widget.song_start_text
                 )
     return entries
Exemplo n.º 7
0
class Protocol:
    def __init__(self):
        self.directory = Directory()
    
    def proses(self, json_to_process):
        obj = json.loads(json_to_process)
        pkt = {}
        try:
            command = obj['cmd']
            if command == 'list':
                pkt['list'] = self.directory.get_list()
                res = 'OK'
            elif command == 'get':
                filename = obj['filename']
                ret, binary = self.directory.get_file(filename)
                content = binary.decode()
                pkt['content'] = content
                res = 'OK' if ret else 'ERRNF'
            elif command == 'put':
                filename = obj['filename']
                raw_content = obj['content']
                content = raw_content.encode()
                ret = self.directory.put_file(filename, content)
                res = 'OK' if ret else 'ERRDUP'
            else:
                res = 'ERRCMD'
        except:
            res = 'ERROR'
        finally:
            pkt['res'] = res
            return json.dumps(pkt)
Exemplo n.º 8
0
    def _list_inventory(self):
        d = Directory(self.nodes_uri)

        entities = {}

        def register_fn(dirpath, filenames):
            for f in filter(lambda f: f.endswith(FILE_EXTENSION), filenames):
                name = f[:-len(FILE_EXTENSION)]
                nodeinfo = self.nodeinfo(name)
                entities[name] = nodeinfo

        d.walk(register_fn)

        applications = {}
        classes = {}
        for f, nodeinfo in entities.iteritems():
            for a in nodeinfo['applications']:
                if a in applications:
                    applications[a].append(f)
                else:
                    applications[a] = [f]
            for c in nodeinfo['classes']:
                if c in classes:
                    classes[c].append(f)
                else:
                    classes[c] = [f]

        return entities, applications, classes
Exemplo n.º 9
0
 def test_load(self):
     self.dir.add_contact("pepe", "*****@*****.**", "27", "Mexico")
     self.dir.add_contact("juan", "*****@*****.**", "27", "Mexico")
     self.dir.add_contact("oscar", "*****@*****.**", "29", "Mexico")
     self.dir.save()
     dir2 = Directory(self.file)
     self.assertEqual(self.dir.search_by_email("*****@*****.**"),
                      dir2.search_by_email("*****@*****.**"))
Exemplo n.º 10
0
 def __init__(self, input_=None, output_=None):
     if input_ is None:
         input_ = Directory(path_="../resource/wakachi/",
                            default_extension_=".meishi.wakachi")
     if output_ is None:
         output_ = Directory(path_="../resource/imporwords/",
                             default_extension_=".uniq.csv")
     super().__init__(input_.path, output_.path, input_.default_extension,
                      output_.default_extension)
Exemplo n.º 11
0
def setResolvedUrl(handle, succeeded, listitem):
    log.debug('setResolvedUrl: {}'.format(listitem._path))
    directory = Directory()
    directory.path = Route.current_explored_route.path
    item = Item()
    item.url = listitem._path
    item.listitem = listitem
    item.is_folder = False
    directory.items[1] = item
    Directory.current_directory = directory
Exemplo n.º 12
0
    def create_directory(self, directory, name, attrib=0x10):
        if name in [e.name() for e in directory.entries]:
            print(name, " already exists in directory")
            return None

        cluster = self.next_free_cluster()

        filename, extension = short_filename(name, directory)
        if name == filename.strip() + ('.' + extension.strip()) if len(
                extension.strip()) != 0 else '':
            name = ''

        today = datetime.datetime.today()
        milliseconds = today.microsecond // 10000 + (today.second % 2) * 100

        entry = Entry(filename, extension, Attrib(attrib), 0x00, milliseconds,
                      today.time(), today.date(), today.date(), today.time(),
                      today.date(), cluster, 0, name)
        directory.write(entry)
        self.current_directory.read_from_disk()

        self.write_to_fat(cluster, 0x0FFFFFFF)

        new_directory = Directory(self, cluster)
        self_entry = Entry(".       ", "   ", Attrib(0x10), 0x00, milliseconds,
                           today.time(), today.date(), today.date(),
                           today.time(), today.date(), cluster, 0, '')
        new_directory.write(self_entry)
        new_directory.read_from_disk()

        up_entry = Entry("..      ", "   ", Attrib(0x10), 0x00, milliseconds,
                         today.time(), today.date(), today.date(),
                         today.time(), today.date(), directory.first_cluster,
                         0, '')
        new_directory.write(up_entry)
Exemplo n.º 13
0
 def testcase1(self):
     rootFolder = Directory()
     folderNames = '/home/gcj/finals'
     rootFolder.addDirectory(folderNames.split('/')[1:])
     self.assertEqual(3, rootFolder.size())
     folderNames = '/home/gcj/quals'
     rootFolder.addDirectory(folderNames.split('/')[1:])
     self.assertEqual(4, rootFolder.size())
Exemplo n.º 14
0
    def _enumerate_inventory(self, basedir, duplicate_handler=None):
        ret = {}
        def register_fn(dirpath, filenames):
            filenames = fnmatch.filter(filenames, '*{0}'.format(self._file_extension))
            vvv('REGISTER {0} in path {1}'.format(filenames, dirpath))
            for f in filenames:
                name = os.path.splitext(f)[0]
                uri = os.path.join(dirpath, f)
                if name in ret and callable(duplicate_handler):
                    duplicate_handler(name, os.path.join(basedir, ret[name]), uri)
                ret[name] = os.path.relpath(uri, basedir)

        d = Directory(basedir)
        d.walk(register_fn)
        return ret
Exemplo n.º 15
0
    def _download(self, content):
        cwd = os.getcwd()
        os.chdir(self._working_dir)

        for multihash in content.keys():
            self._ipfs_client.get(multihash)

        for multihash in os.listdir(self._working_dir):
            name = base64.b64decode(content[multihash]).decode()
            os.rename(multihash, name)
            full_path = os.path.join(self._working_dir, name)

            self._content.add(full_path, multihash)

            if os.path.isfile(full_path):
                File(full_path).decrypt_content(cipher=self._cipher,
                                                dst_dir=self._root_dir)
                time.sleep(0.1)
                os.remove(full_path)
            elif os.path.isdir(full_path):
                Directory(full_path).decrypt_content(cipher=self._cipher,
                                                     dst_dir=self._root_dir)
                time.sleep(0.1)
                shutil.rmtree(full_path)

        os.chdir(cwd)
Exemplo n.º 16
0
def start_server(ip, port):

    server = SimpleXMLRPCServer((ip, port))
    PYTHON_LOGGER.info("Server listen at adresse {} port {}".format(ip, port))
    server.register_function(Directory(), "directory_class")
    server.serve_forever()
    PYTHON_LOGGER.info("Server stop")
Exemplo n.º 17
0
 def __init__(self, name):
     self.lock = threading.Lock()
     self.name = name
     self.config = None
     self.cache_layer = {}
     self.c_nodes = 0
     self.links = {}
     self.env = None
     self.compute_nodes = 0
     self.mapper_list = {}
     self.cpu = 0
     self.placement = None
     self.logger = None
     self.blk_dir = Directory('blk_dir')  #block directory
     self.jobStat = JobStat()
     self.hash_ring = None
     self.nic_count = 0
     self.scheduler = None
     self.repType = 'rep'
     self.repCount = 3
     self.ec = []
     self.rep_size = 4
     self.chunk_size = 4
     self.osdMap = None
     self.dl_access = 0
     self.outstanding_req = {}
Exemplo n.º 18
0
    def _parse_entry_table(self) -> (List[Firmware], List[Directory]):
        entries = chunker(self.firmware_entry_table[4:], 4)

        for index, entry in enumerate(entries):
            firmware_type = self._FIRMWARE_ENTRY_TYPES[index] if index < len(
                self._FIRMWARE_ENTRY_TYPES) else 'unknown'
            address = struct.unpack('<I', entry)[0] & 0x00FFFFFF

            # assumption: offset == 0 is an invalid entry
            if address not in [0x0, 0xfffffe]:
                directory = self[address:address + 16 * 8]
                magic = directory[:4]

                # either this entry points to a PSP directory directly
                if magic in [b'$PSP', b'$BHD']:
                    directory = Directory(self, address, firmware_type)
                    self.directories.append(directory)

                    # if this Directory points to a secondary directory: add it, too
                    if directory.secondary_directory_address is not None:
                        secondary_directory = Directory(
                            self, directory.secondary_directory_address,
                            'secondary')
                        self.directories.append(secondary_directory)

                # or this entry points to a combo-directory (i.e. two directories)
                elif magic == b'2PSP':
                    psp_dir_one_addr = struct.unpack(
                        '<I', directory[10 * 4:10 * 4 + 4])[0] & 0x00FFFFFF
                    psp_dir_two_addr = struct.unpack(
                        '<I', directory[14 * 4:14 * 4 + 4])[0] & 0x00FFFFFF

                    for address in [psp_dir_one_addr, psp_dir_two_addr]:
                        directory = Directory(self, address, firmware_type)
                        self.directories.append(directory)

                        # if this Directory points to a secondary directory: add it, too
                        if directory.secondary_directory_address is not None:
                            secondary_directory = Directory(
                                self, directory.secondary_directory_address,
                                'secondary')
                            self.directories.append(secondary_directory)

                # or this entry is unparsable and thus a firmware
                else:
                    firmware = Firmware(self, address, firmware_type, magic)
                    self.firmwares.append(firmware)
Exemplo n.º 19
0
class IOManager(ABC):
    """ファイルを生成するクラスの抽象クラス"""
    def __init__(self, input_dir_path_, output_dir_path_, input_extension_,
                 output_extension_):
        self.input = Directory(input_dir_path_, input_extension_)
        self.output = Directory(output_dir_path_, output_extension_)
        self.import_io_files()

    @abstractmethod
    def generate(self):
        """何かを生成する為の抽象メソッド"""
        pass

    def import_io_files(self):
        """ディレクトリにファイルを登録する"""
        self.input.import_files()
        self.output.import_files()
Exemplo n.º 20
0
    def __init__(self, path, rootdirectory=None, flags=None):
        assert type(path) is list
        self.__path = path
        if rootdirectory is None:
            self.__rootdirectory = Directory()
        else:
            self.__rootdirectory = rootdirectory
            pass
        self.__rootdirectory.set_filesystem(self)

        if flags is None:
            self.__flags = set()
        else:
            self.__flags = flags
            pass

        pass
Exemplo n.º 21
0
    def _enumerate_inventory(self, basedir, duplicate_handler=None):
        ret = {}

        def register_fn(dirpath, filenames):
            filenames = fnmatch.filter(filenames,
                                       '*{0}'.format(FILE_EXTENSION))
            vvv('REGISTER {0} in path {1}'.format(filenames, dirpath))
            for f in filenames:
                name = os.path.splitext(f)[0]
                uri = os.path.join(dirpath, f)
                if name in ret and callable(duplicate_handler):
                    duplicate_handler(name, os.path.join(basedir, ret[name]),
                                      uri)
                ret[name] = os.path.relpath(uri, basedir)

        d = Directory(basedir)
        d.walk(register_fn)
        return ret
Exemplo n.º 22
0
def addDirectoryItems(handle, items_qd, totalItems=0):
    log.debug('addDirectoryItems of {} items'.format(totalItems))
    directory = Directory()
    directory.path = Route.current_explored_route.path

    cnt = 0
    for item_cq in items_qd:
        item = Item()
        cnt += 1
        item.url = item_cq[0]
        item.listitem = item_cq[1]
        item.is_folder = item_cq[2]
        item.key = cnt

        directory.items[cnt] = item

    Directory.current_directory = directory
    return True
Exemplo n.º 23
0
 def __init__(self,
              input_path="./resource/",
              output_path="./resource/testsuite/",
              learn_result_=None,
              units_=None):
     """初期化"""
     super().__init__(input_path, output_path, ".txt", ".testsuite.csv")
     self.vocab = {}
     self.vocab_n = 0
     self.vocab_i = {}
     self.units = units_
     self.learn_model = None
     self.learn_result = learn_result_
     self.length = 30
     self.imporwords = Directory(self.input.path + "imporwords/", ".imporword.csv")
     self.imporwords.import_files()
     np.random.seed(np.random.randint(1, 1000))
     chainer.config.train = False  # 学習中ではないことを明示
Exemplo n.º 24
0
 def testcase1(self):
     rootFolder = Directory()
     folderNames = '/home/gcj/finals'
     rootFolder.addDirectory(folderNames.split('/')[1:])
     self.assertEqual(3, rootFolder.size())
     folderNames = '/home/gcj/quals'
     rootFolder.addDirectory(folderNames.split('/')[1:])
     self.assertEqual(4, rootFolder.size())
Exemplo n.º 25
0
 def getPaths(self):
     dirs = []
     with open(self.__file_path, 'r') as json_file:
         data = json.load(json_file)
         if data['directories'] is not None and len(
                 data['directories']) > 0:
             for data_dir in data['directories']:
                 directory = Directory(dictionary=data_dir)
                 dirs.append(directory)
     return dirs
Exemplo n.º 26
0
def getFolderSizeHelper(folder, dirList, currDir, nested):
    for item in os.scandir(folder):
        if item.is_file():
            currDir.size+=item.stat().st_size
        elif item.is_dir():
            subDir = Directory(item.path[(item.path).rfind('/'):], (nested + 1))
            currDir.size += getFolderSizeHelper(item.path, dirList, subDir, subDir.size)

    dirList.append(currDir)
    return  currDir.size
Exemplo n.º 27
0
 def get_last_backup(self):
     dirs = (x
             for x in sorted((Directory(date=x, path=self.mount_point)
                              for x in os.listdir(self.mount_point)
                              if is_date(date=x, time_format=TIME_FORMAT)),
                             reverse=True))
     try:
         return next(dirs)
     except StopIteration:
         return None
Exemplo n.º 28
0
def addRoot(my_user):
    directory_id = my_user.key.id() + '/'
    directory = Directory(id=directory_id)
    directory.name = 'root'
    directory.parent = None
    directory.path = '/'
    directory.put()
    my_user.root = directory.key
    my_user.put()
Exemplo n.º 29
0
def main():
    # Get configuration
    config = Config(
        (ConfigOption('LDAP_URL',
                      '--ldap-host'), ConfigOption('LDAP_DN', '--ldap-dn'),
         ConfigOption('LDAP_PASSWORD', '--ldap-password'),
         ConfigOption('LDAP_USERS', '--ldap-users'),
         ConfigOption('LDAP_GROUPS', '--ldap-groups'),
         ConfigOption('LDAP_USER_FILTER', '--ldap-user-filter'),
         ConfigOption('GITLAB_URL', '--gitlab-url'),
         ConfigOption('GITLAB_TOKEN', '--gitlab-token'),
         ConfigOption('GITLAB_PARENT', '--gitlab-parent'))).get()

    # Initialize Gitlab and LDAP objects
    directory = Directory(config['LDAP_URL'], config['LDAP_DN'],
                          config['LDAP_PASSWORD'])
    gitlab = Gitlab(config['GITLAB_URL'], private_token=config['GITLAB_TOKEN'])

    users_by_group = {}

    # Create missing groups

    ldap_groups = directory.get_groups(config['LDAP_GROUPS'])
    for dn, attrs in ldap_groups:
        group_name = attrs['cn'][0].decode()
        if group_name.startswith('gitlab-') and group_name != 'gitlab-users':
            create_group_if_missing(gitlab, dn, attrs, config['GITLAB_PARENT'])

            users_by_group[group_name] = directory.get_member_uids(
                config['LDAP_USERS'], dn)

    # Create missing users
    ldap_users = directory.get_users(config['LDAP_USERS'],
                                     config['LDAP_USER_FILTER'])
    for dn, attrs in ldap_users:
        uid = attrs['uid'][0].decode()
        gitlab_user = gitlab.users.list(username=uid)
        if not gitlab_user:
            create_user(gitlab, dn, attrs)

    sync_group_membership(gitlab, users_by_group)
Exemplo n.º 30
0
 def free_space(self, force_clean=False):
     if LOGLEVEL > 0:
         if force_clean is False and not self.has_space():
             print(
                 "Disk at {} has no space left:{}deleting some old backups..."
                 .format(self.mount_point, os.linesep))
         elif force_clean is True:
             print("Force clean on disk {}:{}deleting all old backups...".
                   format(self.mount_point, os.linesep))
     dirs = (x for x in sorted(
         Directory(date=x, path=self.mount_point)
         for x in os.listdir(self.mount_point)
         if is_date(date=x, time_format=TIME_FORMAT)))
     try:
         previous_backup = next(dirs)
         for tmp_dir in dirs:
             if not force_clean and self.has_space():
                 break
             else:
                 if tmp_dir.is_deletable(previous_dir=previous_backup):
                     tmp_dir.remove()
                 else:
                     previous_backup = tmp_dir
     except StopIteration:
         pass
     if not self.has_space():
         if LOGLEVEL > 0:
             print("No more useless backup: deleting from the oldest")
     dirs = (x
             for x in sorted((Directory(date=x, path=self.mount_point)
                              for x in os.listdir(self.mount_point)
                              if is_date(date=x, time_format=TIME_FORMAT))))
     while not self.has_space():
         try:
             next(dirs).remove()
         except StopIteration:
             print(
                 "All backup removed but still not enough space. Aborting.")
             exit(1)
     if LOGLEVEL > 0:
         print("Cleanup finished.")
 def _add_file(self, file_path, add_file=True):
     """A helper function to add a file or directory"""
     paths = file_path.split('/')
     curr = self._root
     for i, path in enumerate(paths):
         next = curr._children.get(path)
         if next is None:
             if i == len(path) - 1 and add_file:
                 next = curr._children[path] = File(path)
             else:
                 next = curr._children[path] = Directory(path)
         curr = next
Exemplo n.º 32
0
def sync(fp_target, remove_synced=False):
    bk = BookKeeper()
    lst_synced = bk.read()

    target = Directory(fp_target)

    ad = AndroidDevice(lst_synced)
    ad.connect()
    ad.get_files_to_sync()
    lst_new = ad.sync(target=target, remove_synced=remove_synced)
    ad.disconnect()
    bk.write(lst_new)
Exemplo n.º 33
0
def main():
    d = Directory()
    folder = d.get_folder_from_user()
    folder_contents = d.get_folder_contents(folder)
    table_name = d.get_table_name()
    df = d.merge_all_tables(folder_contents, table_name)
    df.to_csv('../merged_tables.csv')
Exemplo n.º 34
0
 def add_root_dir(self, start_time):
     for path in os.listdir(self._root_dir_path):
         full_path = os.path.join(self._root_dir_path, path).replace(os.sep, '/')
         if os.path.getctime(full_path) >= start_time:
             continue
         if os.path.isfile(full_path):
             file = File(full_path)
             hash = self._ipfs_client.add_file(file)
             self._content.add(file.path, hash)
         elif os.path.isdir(full_path):
             content_list = self._ipfs_client.add_dir(Directory(full_path))
             self._content.add_list(content_list)
         self._ipfs_cluster.pin(self._content[full_path])
Exemplo n.º 35
0
def main():
    directory = Directory()

    add_persons(directory)
    show_directory(directory)

    find_user(directory, "*****@*****.**", 62)
    find_user(directory, "*****@*****.**", 42)

    delete_user(directory, 2)
    show_directory(directory)

    save_directory(directory)
Exemplo n.º 36
0
    def _enumerate_inventory(self, basedir, name_mangler):
        ret = {}

        def register_fn(dirpath, filenames):
            filenames = fnmatch.filter(filenames, "*{0}".format(FILE_EXTENSION))
            vvv("REGISTER {0} in path {1}".format(filenames, dirpath))
            for f in filenames:
                name = os.path.splitext(f)[0]
                relpath = os.path.relpath(dirpath, basedir)
                if callable(name_mangler):
                    relpath, name = name_mangler(relpath, name)
                uri = os.path.join(dirpath, f)
                if name in ret:
                    E = reclass.errors.DuplicateNodeNameError
                    raise E(self.name, name, os.path.join(basedir, ret[name]), uri)
                if relpath:
                    f = os.path.join(relpath, f)
                ret[name] = f

        d = Directory(basedir)
        d.walk(register_fn)
        return ret
Exemplo n.º 37
0
 def _generate_topology(self, width=7, depth=7):
     if depth > 0:
         topology = list()
         for i in range(0, width):
             isFile = random.choice([True, False])
             print(isFile)
             user_name = random.choice(self._users.keys())
             print(user_name)
             name = ''.join(random.choice(string.lowercase)
                            for _ in range(random.randint(7, 14)))
             print(name)
             if isFile:
                 topology.append(File(user_name, name))
             else:
                 directory = Directory(user_name, name)
                 directory_data = self._generate_topology(width=width,
                                                          depth=depth-1)
                 if directory_data:
                     for accessible_object in directory_data:
                         directory.write(accessible_object)
                 topology.append(directory)
         return topology
     return None
Exemplo n.º 38
0
def add_root_directory(my_user):
    directory_id = my_user.key.id() + '/'
    directory = Directory(id=directory_id)

    directory.parent_directory = None
    directory.name = 'root'
    directory.path = '/'
    directory.put()

    my_user.root_directory = directory.key
    my_user.put()
Exemplo n.º 39
0
 def addDirectory(self, path, recursively = True, followSymLinks = False, forceUpdate = False):
     if path[-1] != u'/':
         path += u'/'
     dirObj = self.store.find(Directory, Directory.path == path).any()
     if dirObj is None:
         dirObj = Directory()
         dirObj.path = path
         dirObj.recursively = recursively
         dirObj.followSymLinks = followSymLinks
         self.store.add(dirObj)
         return dirObj, True
     else:
         dirObj.recursively = recursively
         dirObj.followSymLinks = followSymLinks
         if forceUpdate:
             dirObj.lastScan = 0
         return dirObj, False
Exemplo n.º 40
0
def add_directory(name, parent_directory_key):
    my_user = get_my_user()

    parent_directory_object = parent_directory_key.get()

    path = get_path(name, parent_directory_object)

    directory_id = my_user.key.id() + path
    directory = Directory(id=directory_id)

    # check if directory already exists in this path
    if exists(directory.key, parent_directory_object.directories):
        # Add key to parent directory
        parent_directory_object.directories.append(directory.key)
        parent_directory_object.put()

        # Set all attributes of the directory and save it to datastore
        directory.parent_directory = parent_directory_key
        directory.name = name
        directory.path = path
        directory.put()
Exemplo n.º 41
0
	def buildLevel(self):
		"""
		KEY FOR LEVELS
        P = Platform
        C = player starting position
        A = Spike (Up)    - 1
        V = Spike (Down)  - 2
        > = Spike (Right) - 3
        < = Spike (Left)  - 4
        K = Key
        X = Trophy
        T = Door Top
        B = Door Bottom
        O = Coin
        """
		level = open(Directory.getDirectory() + '/levels/level' + str(self.level) + '.txt', 'r')
		for row in level:
		    for col in row:
		    	if col.isdigit() and self.loadedCoins == False:
		    		if int(col) > 0:
		    			self.loadedCoins = True
		    			self.levelCoins = int(col)
		    		else:
		    			self.loadedCoins = True
		    			self.levelCoins = 1
		        if col == "P":
		            p = Platform(self.x, self.y) # Place a platform at the given x,y
		            self.platforms.insert(0, p) # Insert it into the platforms list
		            self.entities.add(p) # Add to entities so it appears on screen
		        if col == "C":
					self.charX = self.x # The character x found from file loading
					self.charY = self.y # The character y found from file loading
					self.player = Player(self.charX, self.charY) # Set the player along with the x,y of the starting position
		        if col == "A":
		            spike = Spike(self.x, self.y, 1) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "V":
		            spike = Spike(self.x, self.y, 2) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == ">":
		            spike = Spike(self.x, self.y, 3) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "<":
		            spike = Spike(self.x, self.y, 4) # Load a spike at the x,y found 
		            self.entities.add(spike) # Add the spike to the entities
		            self.spikes.add(spike) # Add the spike to the spike sprite group for collison purposes
		        if col == "O":
					coin = Coins(self.x, self.y) # Load a coin image at the given x,y
					self.entities.add(coin) # Coin 1 to the entities
					self.coin.add(coin) # add coin 1 to the coinA sprite group
		        if col == "X":
					try:
						win_object = Trophy(self.x, self.y, self.level) # Load the proper trophy by passing the level to the trophy class and load at the given x,y from file loading
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
					except:
						win_object = Trophy(self.x, self.y, 0)
						self.entities.add(win_object) # Add the trophy to the entities so it appears
						self.trophies.add(win_object) # Also make it a trophy sprite for collision detection purposes
		        if col == "T":
		            self.doorA = Door(self.x, self.y)
		            self.platforms.append(self.doorA) # Make the door top a platform so the player cannot walk through it
		            self.entities.add(self.doorA) # Add the door bottom to the entities
		        if col == "B":
		            self.doorB = Door(self.x, self.y)
		            self.platforms.append(self.doorB) # Make the door bottom a platform so the player cannot walk through it
		            self.entities.add(self.doorB) # Add the door bottom to entities
		        self.x += 32
		    self.y += 32
		    self.x = 0

		# Try loading in the level image and theme; if it fails, use level 0 theme and background
		try:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background' + str(self.level) + '.png').convert_alpha()
		    self.background_rect = self.background.get_rect()
		except:
		    self.background = pygame.image.load(Directory.getDirectory() + '/images/backgrounds/background0.png').convert_alpha()
		    self.background_rect = self.background.get_rect()
Exemplo n.º 42
0
from directory import Directory

main = Directory(0)

Directory.start_the_story(main)
Exemplo n.º 43
0
def main():
    try:
        print('Making root entries...')
        rootdir = Directory('root')
        bindir = Directory('bin')
        tmpdir = Directory('tmp')
        usrdir = Directory('usr')
        rootdir.add(bindir)
        rootdir.add(tmpdir)
        rootdir.add(usrdir)
        bindir.add(MyFile('vi', 10000))
        bindir.add(MyFile('latex', 20000))
        rootdir.accept(ListVisitor())

        print('')
        print('Making user entries...')
        yuki = Directory('yuki')
        hanako = Directory('hanako')
        tomura = Directory('tomura')
        usrdir.add(yuki)
        usrdir.add(hanako)
        usrdir.add(tomura)
        yuki.add(MyFile('diary.html', 100))
        yuki.add(MyFile('Composite.py', 200))
        hanako.add(MyFile('memo.txt', 300))
        tomura.add(MyFile('game.doc', 400))
        tomura.add(MyFile('junk.mail', 500))
        rootdir.accept(ListVisitor())
    except FileTreatmentException as e:
        logging.exception('FileTreatmentException: {0}'.format(e))
Exemplo n.º 44
0
class Viewer:
	def __init__(self,dir):
		self.dir = dir
		pygame.init()
		modes = pygame.display.list_modes()
		self.screen = pygame.display.set_mode(modes[0],pygame.FULLSCREEN)
		self.loc = Directory(dir)
		self.myfont = pygame.font.Font(join(dirname(realpath(__file__)),"verdana.ttf"),32)
		self.index = 0
		self.list = [".."]+self.loc.listdir()
		self.collen = int((self.screen.get_size()[1]*1.0)/self.myfont.size(self.list[1])[1])
		print "collen",self.collen,self.myfont.size(self.list[1])[1],self.screen.get_size()[1]
		self.draw_list()
		clock = pygame.time.Clock()
		while 1:
			clock.tick(5)
			for event in pygame.event.get():
				if event.type is QUIT:
					return
				elif event.type is KEYDOWN:
					oldindex = self.index
					olddir = self.loc.path
					if event.key == K_ESCAPE:
						return
					elif event.key == K_DOWN or event.key == K_UP or event.key == K_LEFT or event.key == K_RIGHT:
						if event.key == K_DOWN or event.key == K_RIGHT:
							if event.key == K_DOWN:
								self.index +=1
							else: # K_RIGHT
								self.index += self.collen
								if self.index>=len(self.list):
									while self.index>=self.collen:
										self.index -= self.collen
							if self.index>=len(self.list):
								self.index -= len(self.list)
						else: # K_UP or K_LEFT
							if event.key == K_UP:
								self.index = self.index - 1
							else:
								self.index = self.index - self.collen
							if self.index<0:
								self.index = len(self.list)+self.index

					elif event.key == K_RETURN or event.key == K_BACKSPACE:
						if event.key == K_BACKSPACE:
							self.index = 0
							
						if self.loc.isfile(self.list[self.index]):
							if self.list[self.index][-4:]=='.cbz' or self.list[self.index][-4:]=='.zip' or self.list[self.index][-4:]=='.cbr' or self.list[self.index][-4:] == ".rar":
								if self.list[self.index]!="..":
									self.loc.chdir(self.list[self.index])
									self.list = [".."]+self.loc.listdir()
									self.index = 0
								else:
									place = self.loc.path[-1]
									self.loc.chdir("..")
									self.list = [".."]+self.loc.listdir()
									self.index=0

									for l in range(len(self.list)):
										if self.list[l]==place:
											self.index = l
											break
							else:
								self.index -=1
								self.browser()
								self.list = [".."]+self.loc.listdir()
								self.index +=1
								self.draw_list()
						else:
							if self.list[self.index]!="..":
								self.loc.chdir(self.list[self.index])
								self.list = [".."]+self.loc.listdir()
								self.index = 0
							else:
								place = [x for x in self.loc.path.split(os.sep) if x!=""][-1]
								print "dir",self.loc.path#,Directory.sep.findall(self.loc.path)
								self.loc.chdir("..")
								self.list = [".."]+self.loc.listdir()
								self.index=0
								print "looking for",place
								for l in range(len(self.list)):
									print self.list[l]
									if self.list[l]==place:
										self.index = l
										break
					elif event.key == K_END:
						self.index = len(self.list)-1
					elif event.key == K_HOME:
						self.index = 0
					elif event.key == K_DELETE:
						self.loc.delete(self.list[self.index])
						self.loc.clear_dir()
						self.list = [".."]+self.loc.listdir()
						if self.index == len(self.list):
							self.index -=1
						self.draw_list()
					elif event.key == K_r:
						self.list = [".."]+self.loc.listdir()
						self.draw_list()
					else:
						print "No binding for "+str(pygame.key.name(event.key))
					if oldindex!=self.index or self.loc.path!=olddir:
						self.draw_list()
					

	def draw_list(self):
		self.screen.fill((0,0,0))
		try:
			height = self.myfont.size(self.list[1])[1]
		except IndexError:
			height=20
		except:
			print "list",self.list
			raise
		y = 0
		min_x = 20
		x = min_x
		max_x = 0
		for f in self.list:
			if self.myfont.size(f)[0]>max_x:
				max_x = self.myfont.size(f)[0]
				
		firstdraw = 0
		width = self.screen.get_size()[0]

		while self.index-firstdraw>self.collen*int(width/(max_x*1.0)):
			if firstdraw+self.collen>self.index:
				break
			firstdraw += self.collen

		for i in range(firstdraw, len(self.list)):
			f = self.list[i]
			if not self.loc.isfile(f):
				f = "["+f+"]"
			if y == self.collen:
				y = 0
				x += max_x+min_x
				if x > width:
					break
			if self.index == i:
				self.screen.blit(self.myfont.render(f,True,(255,255,255),(255,0,0)),(x,y*height))
			else:
				self.screen.blit(self.myfont.render(f,True,(255,255,255)),(x,y*height))

			y += 1
		pygame.display.flip()		

	def browser(self):
		image = self.get_image(self.loc.listdir()[self.index])
		pygame.display.flip()
		while 1:
			for event in pygame.event.get():
				if event.type is QUIT:
					return
				elif event.type is KEYDOWN:
					if event.key == K_ESCAPE or event.key == K_BACKSPACE:
						return
					elif event.key in [K_PAGEDOWN, K_RIGHT, K_DOWN, K_PAGEUP, K_LEFT, K_UP]:
						if event.key in [K_PAGEDOWN, K_RIGHT, K_DOWN]:
							self.index = self.index + 1
							if self.index>len(self.loc.listdir())-1:
								self.index = len(self.loc.listdir())-1							
						else:
							self.index = self.index - 1
							if self.index<0:
								self.index = 0
						
						image = self.get_image(self.loc.listdir()[self.index])
						pygame.display.flip()
					else:
						print "No binding for "+str(pygame.key.name(event.key))

	def get_image(self,filename):
		try:
			print filename
			f = self.loc.open(filename)
			print f
			image = pygame.image.load(f,filename).convert()
			r=[0,0]
			for i in range(2):
				r[i] = self.screen.get_size()[i]/(image.get_size()[i]*1.0)
			if r[0]>r[1]:
				ratio = r[1]
			else:
				ratio = r[0]
			scr = (self.screen.get_size()[0]/(self.screen.get_size()[1]*1.0))
			imr = (image.get_size()[0]/(image.get_size()[1]*1.0))
			print "imr",scr,imr
			if imr<1.0:
				print "small ratio",ratio
				image = pygame.transform.rotate(image,90)
				for i in range(2):
					r[i] = self.screen.get_size()[i]/(image.get_size()[i]*1.0)
				if r[0]>r[1]:
					ratio = r[1]
				else:
					ratio = r[0]

			print ratio,scr,image.get_size(),(image.get_size()[0]*ratio,image.get_size()[1]*ratio),self.screen.get_size()
			image = pygame.transform.smoothscale(image,(image.get_size()[0]*ratio,image.get_size()[1]*ratio))
			self.screen.fill((0,0,0))
			self.screen.blit(image, ((self.screen.get_size()[0]-image.get_size()[0])/2, (self.screen.get_size()[1]-image.get_size()[1])/2))
			return image
		except pygame.error, message:
			if str(message) == "Unsupported image format":
				return None
			else:
				print "\""+str(message)+"\""
				raise
Exemplo n.º 45
0
	def __init__(self,dir):
		self.dir = dir
		pygame.init()
		modes = pygame.display.list_modes()
		self.screen = pygame.display.set_mode(modes[0],pygame.FULLSCREEN)
		self.loc = Directory(dir)
		self.myfont = pygame.font.Font(join(dirname(realpath(__file__)),"verdana.ttf"),32)
		self.index = 0
		self.list = [".."]+self.loc.listdir()
		self.collen = int((self.screen.get_size()[1]*1.0)/self.myfont.size(self.list[1])[1])
		print "collen",self.collen,self.myfont.size(self.list[1])[1],self.screen.get_size()[1]
		self.draw_list()
		clock = pygame.time.Clock()
		while 1:
			clock.tick(5)
			for event in pygame.event.get():
				if event.type is QUIT:
					return
				elif event.type is KEYDOWN:
					oldindex = self.index
					olddir = self.loc.path
					if event.key == K_ESCAPE:
						return
					elif event.key == K_DOWN or event.key == K_UP or event.key == K_LEFT or event.key == K_RIGHT:
						if event.key == K_DOWN or event.key == K_RIGHT:
							if event.key == K_DOWN:
								self.index +=1
							else: # K_RIGHT
								self.index += self.collen
								if self.index>=len(self.list):
									while self.index>=self.collen:
										self.index -= self.collen
							if self.index>=len(self.list):
								self.index -= len(self.list)
						else: # K_UP or K_LEFT
							if event.key == K_UP:
								self.index = self.index - 1
							else:
								self.index = self.index - self.collen
							if self.index<0:
								self.index = len(self.list)+self.index

					elif event.key == K_RETURN or event.key == K_BACKSPACE:
						if event.key == K_BACKSPACE:
							self.index = 0
							
						if self.loc.isfile(self.list[self.index]):
							if self.list[self.index][-4:]=='.cbz' or self.list[self.index][-4:]=='.zip' or self.list[self.index][-4:]=='.cbr' or self.list[self.index][-4:] == ".rar":
								if self.list[self.index]!="..":
									self.loc.chdir(self.list[self.index])
									self.list = [".."]+self.loc.listdir()
									self.index = 0
								else:
									place = self.loc.path[-1]
									self.loc.chdir("..")
									self.list = [".."]+self.loc.listdir()
									self.index=0

									for l in range(len(self.list)):
										if self.list[l]==place:
											self.index = l
											break
							else:
								self.index -=1
								self.browser()
								self.list = [".."]+self.loc.listdir()
								self.index +=1
								self.draw_list()
						else:
							if self.list[self.index]!="..":
								self.loc.chdir(self.list[self.index])
								self.list = [".."]+self.loc.listdir()
								self.index = 0
							else:
								place = [x for x in self.loc.path.split(os.sep) if x!=""][-1]
								print "dir",self.loc.path#,Directory.sep.findall(self.loc.path)
								self.loc.chdir("..")
								self.list = [".."]+self.loc.listdir()
								self.index=0
								print "looking for",place
								for l in range(len(self.list)):
									print self.list[l]
									if self.list[l]==place:
										self.index = l
										break
					elif event.key == K_END:
						self.index = len(self.list)-1
					elif event.key == K_HOME:
						self.index = 0
					elif event.key == K_DELETE:
						self.loc.delete(self.list[self.index])
						self.loc.clear_dir()
						self.list = [".."]+self.loc.listdir()
						if self.index == len(self.list):
							self.index -=1
						self.draw_list()
					elif event.key == K_r:
						self.list = [".."]+self.loc.listdir()
						self.draw_list()
					else:
						print "No binding for "+str(pygame.key.name(event.key))
					if oldindex!=self.index or self.loc.path!=olddir:
						self.draw_list()