def update_user_profile(request): name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] result = Result() try: user = update_user(request.user.username, name, phone, email) return HttpResponse(json.dumps({"name": user.first_name, "phone": user.last_name, "email": user.email}), content_type="application/json") except: result.code = Consts.FAILED_CODE result.msg = Consts.UNKNOWN_ERROR return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def execute_return_output(cmd, is_print_cmd=True): if is_print_cmd: print('$ ' + cmd) process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = '' for line in iter(process.stdout.readline, ''): output += line sys.stdout.write(line) sys.stdout.flush() process.poll() return Result(exitcode=process.returncode, message='', data=output)
def auth(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) result = Result() if user: _login(request=request, user=user) result.code = Consts.SUCCESS_CODE else: result.code = Consts.FAILED_CODE result.msg = Consts.LOGIN_FAILED_MSG return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def remove_admin(request, username): result = Result() try: remove_user(username) result.code = Consts.SUCCESS_CODE except User.DoesNotExist: result.code = Consts.FAILED_CODE result.msg = Consts.NOT_FOUND_USER_MSG except: result.code = Consts.FAILED_CODE result.msg = Consts.UNKNOWN_ERROR return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def upload_batch_admin(request): result = Result() try: csv_file = request.FILES.get("uploadInputFile") if not csv_file.name.endswith('.csv'): result.code = Consts.FAILED_CODE result.msg = Consts.INVALID_CSV_FILE_MSG return HttpResponse(json.dumps(result.to_dict()), content_type="application/json") if csv_file.multiple_chunks(): result.code = Consts.FAILED_CODE result.msg = Consts.TOO_LARGE_FILE_MSG return HttpResponse(json.dumps(result.to_dict()), content_type="application/json") reader = csv.DictReader(codecs.EncodedFile(csv_file, "utf-8")) success_count = 0 failed_count = 0 failed_idx = [] failed_reason = [] for i, row in enumerate(reader): username = row['username'] name = row['name'] phone = row['phone'] email = row['email'] if is_username_valid(username): failed_count += 1 failed_idx.append(i+1) failed_reason.append(Consts.USER_EXISTED_MSG) continue try: # todo: generate random password and send email to user password = "******" create_user(username, password, name, phone, email) success_count += 1 except: failed_count += 1 failed_idx.append(i+1) failed_reason.append(Consts.UNKNOWN_ERROR) result.code = Consts.SUCCESS_CODE if failed_count > 0: result.msg = u"成功导入%d条数据, 失败%d条, 原因: \n" % (success_count, failed_count) for i, r in zip(failed_idx, failed_reason): result.msg += "第%d行, %s \n" % (i, r) else: result.msg = u"成功导入%d条数据" % success_count except Exception as e: result.code = Consts.FAILED_CODE result.msg = e.message raise e return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def update_admin_info(request): username = request.POST['username'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] result = Result() try: update_user(username, name, phone, email) result.code = Consts.SUCCESS_CODE except User.DoesNotExist: result.code = Consts.FAILED_CODE result.msg = Consts.NOT_FOUND_USER_MSG except: result.code = Consts.FAILED_CODE result.msg = Consts.UNKNOWN_ERROR return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def coverage_lcov(self): result = Result(message='') try: execute('sh -c "cd {} && lcov -c -d ./ -o {}/lcov.cov"'.format( LINUX_BUILD_DIR, LINUX_BUILD_DIR)) result = execute_return_output('sh -c "cd {} && \ lcov -r {}/lcov.cov \ \*extlibs/\* \*mocks\* /usr/\* \*/test/\* \*/os/linux/\* \ --no-external -o {}/filtered-lcov.cov"'.format( LINUX_BUILD_DIR, LINUX_BUILD_DIR, LINUX_BUILD_DIR)) raise_exception_if_exitcode_is_error(result) execute('sh -c "cd {} && genhtml {}/filtered-lcov.cov -o covhtml"'. format(LINUX_BUILD_DIR, LINUX_BUILD_DIR)) result.message = self.get_coverage_message(result.data) return result except subprocess.CalledProcessError as e: raise RT_OCFError(e.returncode, message=COVERAGE_FAIL_MESSAGE)
def update_user_password(request): pw = request.POST['password'] confirm_pw = request.POST['confirm-password'] result = Result() if pw != confirm_pw: result.code = Consts.FAILED_CODE result.msg = Consts.UPDATE_PASSWORD_UNMATCH_MSG return HttpResponse(json.dumps(result.to_dict()), content_type="application/json") try: user = request.user user.set_password(pw) user.save() result.code = Consts.SUCCESS_CODE except: result.code = Consts.FAILED_CODE result.msg = Consts.UNKNOWN_ERROR return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def create_admin(request): result = Result() username = request.POST['username'] name = request.POST['name'] # todo: generate random password and send email to user password = "******" email = request.POST['email'] phone = request.POST['phone'] if is_username_valid(username): result.code = Consts.FAILED_CODE result.msg = Consts.USER_EXISTED_MSG else: try: create_user(username, password, name, phone, email) result.code = Consts.SUCCESS_CODE except: result.code = Consts.FAILED_CODE result.msg = Consts.UNKNOWN_ERROR return HttpResponse(json.dumps(result.to_dict()), content_type="application/json")
def collect_results(summary_dir: str, metric: Metric, experiment: Experiment) -> List[Result]: """Collect the results for the experiment on the specified metric. Returns a list of Result objects. """ if not isinstance(metric, Metric): raise ValueError("Unknown metric: %s" % metric) if not isinstance(experiment, Experiment): raise ValueError("Unknown experiment: %s" % experiment) if not os.path.isdir(summary_dir): raise FileNotFoundError(summary_dir) results = [] for fname in sorted(os.listdir(summary_dir)): path = os.path.join(summary_dir, fname) summary_data = load_summary(path) dataset_name = summary_data["dataset"] summary_results = summary_data["results"] is_multi = summary_data["dataset_ndim"] > 1 for abed_method in summary_results: # method names returned from Abed are prefixed with the experiment # type, so we skip the ones we don't want if not abed_method.startswith(experiment.name + "_"): continue # extract the metric score for this experiment from the summary # results for the method score = extract_score( summary_results[abed_method], metric=metric, experiment=experiment, ) # strip the experiment from the method name method_name = abed_method[len(experiment.name + "_"):] dataset = Dataset[dataset_name] method = Method[method_name] # determine the placeholder value if there is no score. placeholder = set() if score is None: if (dataset in MISSING_DATASETS) and (not method in MISSING_METHODS): # dataset has missing values and method can't handle it placeholder.add("M") else: for result in summary_results[abed_method]: if result["status"] == "FAIL": placeholder.add("F") elif result["status"] == "TIMEOUT": placeholder.add("T") placeholder = "/".join(sorted(placeholder)) # create a Result object res = Result( dataset=dataset, experiment=experiment, is_multidim=is_multi, method=method, metric=metric, score=score, summary_file=fname, placeholder=placeholder or None, ) results.append(res) return results
def upload(request): res = Result() if request.FILES.has_key('file'): try: f = request.FILES['file'] filename = f.name path = request.POST.get('path', None) if path: foreignPath = path.replace("'", "\"") else: foreignPath = filename galleries = request.POST.get('galleries', '1').split(',') tags = filter(None, request.POST.get('tags', '').split(',')) username = request.POST.get('user', False) if username: user = User.objects.get(username=username) else: if request.user.is_anonymous(): username = '******' user = User.objects.get(username=username) else: user = request.user uniqueName = request.POST.get('uid', Piece.getUniqueID(foreignPath, user)) if f.content_type.startswith('image'): if Path(filename).ext.lower() not in EXT['image']: raise MediaTypeError model = Image else: if Path(filename).ext not in EXT['video']: raise MediaTypeError model = Video obj, created = model.objects.get_or_create( unique_id=uniqueName, defaults={'author': user}) guid = obj.getGuid() hashVal = getHashForFile(f) if hashVal == obj.hash: for gal in galleries: g = Gallery.objects.get(pk=int(gal)) obj.gallery_set.add(g) res.isSuccess = True res.message = "Files were the same" return JsonResponse(res) objPath = ROOT if FROG_PATH: objPath = objPath / FROG_PATH objPath = objPath / guid.guid[-2:] / guid.guid / filename print objPath hashPath = objPath.parent / hashVal + objPath.ext if not objPath.parent.exists(): objPath.parent.makedirs() handle_uploaded_file(hashPath, f) obj.hash = hashVal obj.foreign_path = foreignPath obj.title = objPath.namebase obj.export(hashVal, hashPath, tags=tags, galleries=galleries) res.append(obj.json()) for key, f in request.FILES.iteritems(): if key != 'file': dest = objPath.parent / f.name handle_uploaded_file(dest, f) res.isSuccess = True except MediaTypeError: res.isError = True res.message = 'Filetype not supported' return JsonResponse(res) else: res.isError = True res.message = "No file found" return JsonResponse(res)