def theirpassword(request, username=""): print "this is called" if not request.user.is_authenticated: return render(request, "login.html", {'login_failed': False, 'is_authenticated': False}) if not request.user.is_superuser: return HttpResponseRedirect('/password/') if request.method == 'POST': if request.POST['password'] == request.POST['confirmpw']: user = User.objects.get(username=request.POST['username']) user.set_password(request.POST['password']) user.save() user = request.user return render(request, "profile.html", { 'is_admin': isAdmin(user.id), 'files': getFiles(user.id), 'username': user.username, 'history': getHistory(user.id) }) else: return render(request, "password.html", { 'failed': True, 'username': user.username, 'is_admin': isAdmin(user.id), 'username2': username, 'viewing': True, }) if request.method == 'GET': user = request.user return render(request, "password.html", { 'username2': username, 'viewing': True, 'username': user.username, 'is_admin': isAdmin(user.id), })
def mypassword(request): if not request.user.is_authenticated: return render(request, "login.html", {'login_failed': False, 'is_authenticated': False}) if request.method == 'POST': user = request.user if request.POST['password'] == request.POST['confirmpw']: user.set_password(request.POST['password']) user.save() return render(request, "profile.html", { 'is_admin': isAdmin(user.id), 'files': getFiles(user.id), 'username': user.username, 'history': getHistory(user.id) }) else: return render(request, "password.html", { 'failed': True, 'username': user.username, 'is_admin': isAdmin(user.id), }) if request.method == 'GET': user = request.user return render(request, "password.html", { 'username': user.username, 'is_admin': isAdmin(user.id), })
def getportfolio(fname=None): # Get list of published pages files_list = sorted(getFiles("templates/portfolio")) with_fnames = [] for f in files_list: with_fnames.append((f, f[:-5], "portfolio/" + f)) if fname is not None and fname in files_list: if session["user_id"] != 1: #log view to history if date or page not in history insert_view(session["user_id"], fname) fname = "portfolio/" + fname return render_template(fname) elif fname is not None: error = "Sorry, that page does not exist" return render_template("portfolio.html", error=error, with_fnames=with_fnames) else: if session["user_id"] != 1: #log view to history if date or page not in history insert_view(session["user_id"], 'portfolio.html') return render_template("portfolio.html", fname=fname, with_fnames=with_fnames)
def task_crop_figures(): for i in helpers.getFiles("figure/"): fname_i = i.split("/")[1] yield { 'name':"cropping " + i + "...", 'actions':["pdf-crop-margins -mo -pf -su " + "\"backup\" " + i, "rm " + "backup_" + fname_i] }
def myprofile(request, username=""): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return HttpResponseRedirect(reverse("onedir.views.myprofile")) if request.method == 'GET': user = request.user if user.id is None: return render(request, "login.html", {'login_failed': True, 'is_authenticated': False}) if user.is_superuser: try: user2 = User.objects.get(username=username) return render(request, "profile.html", { 'is_admin': True, 'files': getFiles(user2.id), 'username': user.username, 'viewing': True, 'user2': user2.username, 'history': getHistory(user2.id) }) except: return render(request, "profile.html", { 'is_admin': True, 'files': getFiles(user.id), 'username': user.username, 'history': getHistory(user.id) }) else: return render(request, "profile.html", { 'is_admin': False, 'files': getFiles(user.id), 'username': user.username, 'history': getHistory(user.id) })
def task_sections(): sectionsFiles = helpers.getFiles(sectionsPath) for i in range(len(sectionsFiles)): fName = sectionsFiles[i].split(".")[0] suffix = sectionsFiles[i].split(".")[1] if suffix == "md": yield { 'name': sectionsFiles[i], 'actions': [ "pandoc --template=" + sectionsTemplate + " -o " + fName + ".pdf " + sectionsFiles[i] ] }
def systemlist(request): if not request.user.is_authenticated: return render(request, "login.html", {'login_failed': False, 'is_authenticated': False}) if not request.user.is_superuser: return HttpResponseRedirect('/myprofile/') system_size = getFileSize("") system_files = getFiles("") user = request.user return render(request, "system.html", { 'username': user.username, 'is_admin': isAdmin(user.id), 'files': system_files, 'size': system_size })
def task_other(): otherFiles = helpers.getFiles("other/") for i in range(len(otherFiles)): fName = otherFiles[i].split(".")[0] suffix = otherFiles[i].split(".")[1] if suffix == "md": yield { 'name': otherFiles[i], 'actions': [ "pandoc --template=templates/cooley-plain.latex -o " + fName + ".pdf " + otherFiles[i] ] }
def task_figs(): figsFiles = helpers.getFiles(figsPath) for i in range(len(figsFiles)): fName = figsFiles[i].split("/")[2].split(".")[0] suffix = figsFiles[i].split("/")[2].split(".")[1] if suffix == "tex": yield { 'name': figsFiles[i], 'actions': [ "cd figs/; latexmk -pdf " + fName + ".tex" + "; latexmk -c; magick -density 300 " + fName + ".pdf " + fName + ".png; cd ..;" ] }
def uploadFile(tokenfilename, credentailsfilename, directorypath, parentID=None): start_time = time.time() service = getToken(tokenfilename, credentailsfilename) for file in getFiles(directorypath): # Get the sub directory absolute path subdir_filepath = os.path.join(directorypath, file) if os.path.isdir(subdir_filepath): # Create metadata for folder dir_metadata = { 'name': file, 'mimeType': 'application/vnd.google-apps.folder', 'parents': ['1pmFLZ-sNeLscJ9pmqA2CPmcYv8FyF2iv'] } # Check if folder exists oldFolderId = checkFolder(service, file) if oldFolderId != 0: # Delete the old folder of files deleteFolder(service, oldFolderId) # Create the new folder newFolderId = createFolder(service, dir_metadata) # Upload files to folder uploadFilesToDir(service, subdir_filepath, newFolderId) print( f'Process completed in {time.time() - start_time} seconds...') else: # Create file metadata file_metadata = { 'name': file, 'mimeType': file.split('.')[1], 'parents': ['1pmFLZ-sNeLscJ9pmqA2CPmcYv8FyF2iv'] } # If file exists delete the file if deleteFile(service, file): # Upload new version of file uploadNewFileVersion(service, file_metadata, os.path.join(directorypath, file)) else: # Upload new version of file uploadNewFileVersion(service, file_metadata, os.path.join(directorypath, file)) print( f'Process completed in {time.time() - start_time} seconds...')
def getdrafts(fname=None): # Get list of draft pages files_list = getFiles("templates/drafts") with_fnames = [] for f in files_list: with_fnames.append((f, f[:-5])) if fname is not None and fname in files_list: fname = "drafts/" + fname return render_template(fname) elif fname is not None: error = "Sorry, that page does not exist" return render_template("drafts.html", error=error, with_fnames=with_fnames) else: return render_template("drafts.html", fname=fname, with_fnames=with_fnames)
def main(argv): ''' Starts program, checks for correct usage, checks platform, sets global variables, and begins analysis of files in directory. ''' parser = argparse.ArgumentParser(usage = 'python rename.py [-h] [-l] [-u]'\ ' [-t n] [-r str1 str2] [-n str] [-v] [-p] [-i] [-d] [-dt] [-D] [-T]' \ ' files') # plain arguments parser.add_argument('-v', '--verbose', action='store_true', help='print old and new filenames during processing') parser.add_argument('-p', '--print', action='store_true', help='only print old and new filenames, do not rename') parser.add_argument( '-i', '--interactive', action='store_true', help='interactive mode, ask user prior to processing each file') parser.add_argument('-l', '--lower', action='store_true', help='convert filenames to lowercase') parser.add_argument('-u', '--upper', action='store_true', help='convert filenames to uppercase') parser.add_argument('-d', '--delete', action='store_true', help='delete files') parser.add_argument( '-dt', '--touch', action='store_true', help='`touch` files (update time/date stamp to current date/time)') # arguments with required parameters, potential consecutive calls parser.add_argument('-t', '--trim', action='append', nargs=1, metavar='n', help='n > 0: trim n characters from the start of \ each filename. n < 0: trim n characters from the end of each filename.', type=int) parser.add_argument('-r', '--replace', action='append', nargs=2, metavar=('A', 'B'), help='do a regular expression replace on the \ given filenames. A is old, B is new.') parser.add_argument('-n', '--number', action='append', nargs=1, metavar='countstring', help='Given a string with a certain number \ of hashes, rename files to new string, numbering in order with hashes') parser.add_argument('-D', '--date', action='append', nargs=1, metavar='DDMMYYYY', help='change file modification datestamps') parser.add_argument('-T', '--time', action='append', nargs=1, metavar='HHMMSS', help='change file modification timestamps') # required arguments parser.add_argument('files', type=str, nargs='+', help='list of files to be modified') # parse command arguments args = parser.parse_args() from helpers import setPlatform, makeList, getFiles # Check platform, if not Linux or Windows return 1 from program. systemPlatform = setPlatform(platform.system()) if systemPlatform == 'E': print('Platform not recognized by file rename tool.') return # Get a list going for commands and their parameters. masterExecutionList = makeList(sys.argv, args) if not masterExecutionList and not args.interactive: print('You must enter at least one command.') return files = [] # List of all files that will be modified (including *). for file in args.files: files += getFiles(file) if not files: print('None of the files you entered could be found.') return # Print Original Names if args.print or args.verbose: print('Input Files:', files) # Get new filenames import copy, modifiers modified = copy.deepcopy(files) if args.interactive: modified = [ input('What would you like to rename `' + file + '` to?\n') for file in modified ] else: # Loop through the execution list and send the tuple to another fxn. for arg, tuple in masterExecutionList: if args.print and (arg in ['time', 'date', 'touch', 'delete']): \ continue else: modified = modifiers.modify[arg](modified, tuple) # Rename Files if not args.print and not args.delete: for start, end in zip(files, modified): rename(start, end) # Print Final Names if args.print or args.verbose: print('Output Files:', modified)
def merge(pullPath, address): conflictCount = 0 conflicts = '' remoteYaml = os.path.join(pullPath, os.listdir(pullPath)[0], '.gaea', 'gaea.yml'); if os.path.exists(remoteYaml): f = open(remoteYaml) remoteInfo = yaml.safe_load(f) f.close() else: raise Exception(address+' is not a Gaea Repository') #check if merge is required if remoteInfo['HEAD'] == globals.REPOINFO['HEAD']: print "Remote HEAD is same as local. No merge required" return #find first common ancestor between remote and local ancestorId = findCommonAncestor(remoteInfo, globals.REPOINFO) #print "Common ancestor id is " + ancestorId basePath = os.path.join(globals.ROOT, '.gaea', 'snaps', ancestorId) newPath = os.path.join(globals.ROOT, '.gaea', 'snaps', globals.REPOINFO['HEAD']) latestPath = os.path.join(pullPath, os.listdir(pullPath)[0], '.gaea', 'snaps', remoteInfo['HEAD']) #delete all the current files in the repo files = helpers.getFiles(globals.ROOT) dirs = helpers.getDirs(globals.ROOT) for directory in dirs: shutil.rmtree(os.path.join(globals.ROOT,directory)) for f in files: os.remove(os.path.join(globals.ROOT, f)) filesDone = [] #merge all the files present in base for root, subFolders, files in os.walk(basePath): if '.gaea' in subFolders: subFolders.remove('.gaea') copyPath = os.path.join(globals.ROOT, os.path.relpath(root, basePath)) #print "copyPath is "+copyPath for f in files: filesDone.append(os.path.join(os.path.relpath(root, basePath),f)) filePathBase = os.path.join(root, f) filePathNew = os.path.join(newPath, os.path.relpath(root, basePath), f) filePathLatest = os.path.join(latestPath, os.path.relpath(root, basePath), f) c,boo = mergeLines(filePathBase, filePathNew, filePathLatest, copyPath, f) if boo: conflictCount += 1 conflicts += c #merge files only in new for root, subFolders, files in os.walk(newPath): if '.gaea' in subFolders: subFolders.remove('.gaea') copyPath = os.path.join(globals.ROOT, os.path.relpath(root, newPath)) if not os.path.exists(copyPath): os.makedirs(copyPath) for f in files: if os.path.join(os.path.relpath(root, newPath), f) not in filesDone: filesDone.append(os.path.join(os.path.relpath(root, newPath),f)) filePathBase = os.path.join(basePath, os.path.relpath(root, newPath), f) filePathNew = os.path.join(root, f) filePathLatest = os.path.join(latestPath, os.path.relpath(root, newPath), f) c, boo = mergeLines(filePathBase, filePathNew, filePathLatest, copyPath, f, new=True) if boo: conflictCount += 1 conflicts += c #merge files only in latest for root, subFolders, files in os.walk(latestPath): if '.gaea' in subFolders: subFolders.remove('.gaea') copyPath = os.path.join(globals.ROOT, os.path.relpath(root, latestPath)) if not os.path.exists(copyPath): os.makedirs(copyPath) for f in files: if os.path.join(os.path.relpath(root, latestPath), f) not in filesDone: filesDone.append(os.path.join(os.path.relpath(root, latestPath),f)) filePathBase = os.path.join(basePath, os.path.relpath(root, newPath), f) filePathNew = os.path.join(newPath, os.path.relpath(root,newPath), f) filePathLatest = os.path.join(root, f) x, boo = mergeLines(filePathBase, filePathNew, filePathLatest, copyPath, f) if boo: conflictCount += 1 conflicts += c return conflicts,conflictCount