- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
for course_id in COURSES: #конфиги для слабаков, реальные пацаны хардкодят константы
participants = {}
print(f'Downloading course {course_id}...')
assignments = M.get_modules(course_id, 'assign')
captions = {item['instance'] : item['name'] for item in assignments}
rawsubs_per_assignment = M.get_submissions(captions.keys())
files = []
print('\tParsing assignments... ',end='')
for i,assign in ProgressBar.each(rawsubs_per_assignment, length=50, donefmt='[OK]\n', errorfmt='[FAIL]\n'):
#самописный прогресс-бар. В скрипте, который 90% времени запускается как демон.
assign_id = assign['assignmentid']
if assign_id not in participants:
lst = M.list_participants(assign_id)
participants[assign_id] = {i['id'] : i['fullname'] for i in lst}
for rs in assign['submissions']:
subfiles = M.get_submission_files(rs)
for sf in subfiles:
f = StoredFile( #самописный псевдо-ORM
id = None,
url = sf['fileurl'],
filename = sf['filename'],
downloaded = False,
size = sf['filesize'],
mimetype = sf['mimetype'],
timestamp = sf['timemodified'],
course = course_id,
instance = assign_id,
submission = rs['id'],
userid = rs['userid'],
username = participants[assign_id][rs['userid']])
files.append(f)
print('\tTotal of {0} assignments and {1} files.'.format(len(participants), len(files)))
print('\tUpdating database... ', end='')
with DB:
for i,f in ProgressBar.each(files, captionfunc = (lambda f:f.filename),
length=25, valuefmt='{ratio:.0%} ', donefmt='[OK]\n', errorfmt='[FAIL]\n'):
DB.update_file(f) #execute_many()? зачем? И так сойдёт.
files_to_download = list(DB.get_nonready_files())
if not files_to_download:
print('All files are up to date.')
else:
ok_count = 0
error_count = 0
print('Downloading missing files... ',end='')
for i,f in ProgressBar.each(files_to_download,
captionfunc = (lambda f: f'[{error_count} errors] {f.filename}'),
length=25, valuefmt='{ratio:4.0%} ', donefmt='[OK]\n', errorfmt='[FAIL]\n'):
#исчо один прогрессбар
path = localpath(f)
dir = os.path.dirname(path)
os.makedirs(dir, exist_ok = True)
if not verify(f):
try:
with open(path, "wb") as dest:
#зачем проверять размер скачиваемого файла или наличие контента?
source = M.get_download_fileobj(f.url)
shutil.copyfileobj(source, dest)
DB.mark_downloaded(f)
except:
error_count += 1
else:
ok_count += 1
else:
ok_count += 1
if error_count > 0:
print(f'{error_count} files failed to download!')
comparisons = list(DB.get_files_to_match())
if comparisons:
print('Matching non-compared files... ',end='')
log = open('errors.txt', 'wt', encoding='utf-8') #logging для слабаков
for i,(f1,f2) in ProgressBar.each(comparisons, length=25, valuefmt='{pos}/{max}', donefmt='[OK]\n', errorfmt='[FAIL]\n'):
#оптимизировать цикл, чтобы не читать один и тот же файл по 50 раз? Нафиг, работает же.
path1, path2 = localpath(f1), localpath(f2)
ok = True
if not verify(f1):
ok = False
DB.mark_downloaded(f1, False)
if not verify(f2):
ok = False
DB.mark_downloaded(f2, False)
if ok:
content1, content2 = None, None
try:
content1 = extract_content(path1)
content2 = extract_content(path2)
similarity = compare_content(content1, content2)
except Exception as E:
if content1 is None:
log.write(path1+'\n')
elif content2 is None:
log.write(path1+'\n')
else:
log.write('Comparison error!\n')
log.write(str(E)+'\n')
else:
DB.save_diff(f1, f2, similarity)
finally: #пусть сборщик мусора порадуется
del content1
del content2
log.close()
Написал тут скрипт, самому стыдно.
Но работает.
ручное управление?
они и так из вобласти видимости выйдут
это не значит, что к выходу из блока ok они удалятся?
да они и так удалятся
не понимаю
фу, говно
фу нахуй
ну, похуй
всё равно не понятно зачем
ну убрал ты переменную из скоупа, и что? зачем ее убирать? и причем там сборщик мусора?
Но это крайне пидорское решение, вот прямо совсем никогда не нужно так делать, в смысле завязываться на такие вещи кмк.
Хотя вот судя по комменту автор думает, что "del" запускает GC кмк.
какой даже не знаю что ))