def main() : POST_LIMIT = 10 STREAMING_SUBS = ['mlbstreams', 'nbastreams', 'soccerstreams'] #, 'nflstreams', 'nhlstreams', 'cfbstreams', 'ncaabballstreams', 'boxingstreams', 'mmastreams'] db = DB.initialize(rebuild = False); # Connect to Reddit reddit_obj = Reddit.connect() # Create submissions and comments for sub in STREAMING_SUBS: submissions_with_comments = Reddit.scrape_posts(reddit_obj, sub, POST_LIMIT) Submission.create_with_comments(submissions_with_comments, db) # Parse comments for streams comment_data = Comment.get_all(db) stream_list = Reddit.parse_comments_for_streams(comment_data, db) # Create streams for stream in stream_list: Stream.create(stream, db) # Print the matches table from SQLite Submission.print_all(db) # Close the DB connection DB.close(db)
def evaluate(source_code_name, user_id, task, contest): extension = get_extension(source_code_name) command = get_command(extension) contest_id = contest.contest_id os.system(command.format(DEST_FOLDER.format(contest_id) + source_code_name, DEST_FOLDER.format(contest_id) + remove_extension(source_code_name))) source_code_name = remove_extension(source_code_name) task_id = task.task_id status = True for input_file in os.listdir(INPUT_FOLDER.format(contest_id, task_id)): if get_extension(input_file) == 'zip': continue user_output = subprocess.check_output(DEST_FOLDER.format(contest_id) + source_code_name + "< " + INPUT_FOLDER.format(contest_id, task_id) + input_file, shell=True) user_output = re.sub('[\s+]\\n', '\n', user_output) user_output = user_output.strip() input_num = input_file.split('_')[1].split('.')[0] with open(OUTPUT_FOLDER.format(contest_id, task_id) + 'out_' + input_num + '.out') as f: output = f.read().strip() print 'worker' print 'output\n {} \n user_output\n {}'.format(output, user_output) status = user_output == output accepted = 'Accepted' if status else 'Wrong Answer' submission = Submission(accepted, extension, datetime.utcnow(), task.name, user_id, task.task_id, contest.contest_id) submission.save()
def judgeProblem(request, name): if not request.user.is_authenticated(): return HttpResponse("Please log in to submit your solution.") language = request.POST.get('language') sourceCode = request.POST.get('editor') problem = Problem.objects.get(name=name) inputString = problem.standardInput outputString = problem.expectedOutput.replace('\r', '') result = judge.subprocessJudge(sourceCode, language, inputString, outputString) resultTuple = status.resultCodeToText(result) if resultTuple: s = Submission(user=request.user, problem=problem, result=resultTuple[0], sourceCode=sourceCode, language=language) s.save() resultText = resultTuple[1] return HttpResponse(resultText) else: return HttpResponse("Invalid response. Something went wrong!")
def submit(request): team = get_team(request.user) params = dict() if request.method == 'POST': form = forms.UploadSubmissionForm(request.POST, request.FILES) params['form'] = form if form.is_valid(): submission = Submission( team=team, package=request.FILES['file'], command=request.POST['command'], ) submission.save() error = utils.unzip(submission.package.path) if error: submission.delete() params['error'] = error return render_submit(request, params) try: execute_tester(submission) except Exception as error: print u'ERROR: Blad wewnetrzny testerki:', error return my_results( request, message=_(u'Rozwiązanie zostało wysłane.')) return render_submit(request, params)
def main(): POST_LIMIT = 10 STREAMING_SUBS = [ 'mlbstreams', 'nbastreams', 'soccerstreams' ] #, 'nflstreams', 'nhlstreams', 'cfbstreams', 'ncaabballstreams', 'boxingstreams', 'mmastreams'] db = DB.initialize(rebuild=False) # Connect to Reddit reddit_obj = Reddit.connect() # Create submissions and comments for sub in STREAMING_SUBS: submissions_with_comments = Reddit.scrape_posts( reddit_obj, sub, POST_LIMIT) Submission.create_with_comments(submissions_with_comments, db) # Parse comments for streams comment_data = Comment.get_all(db) stream_list = Reddit.parse_comments_for_streams(comment_data, db) # Create streams for stream in stream_list: Stream.create(stream, db) # Print the matches table from SQLite Submission.print_all(db) # Close the DB connection DB.close(db)
def save(self, user, problem): new_submission = Submission(problem=problem, user=user, is_public=self.public, language=self.cleaned_data["language"], length=len(self.cleaned_data["source"]), source=self.cleaned_data["source"]) new_submission.save()
def put_submission(self, problem_name, level, score, answer): submission = Submission(student_magic_number = self.magic, problem_id = self.problem_id, answer = answer, score = score, type = problem_name, level = level) # logging.warn("submit: %s %s %s %s %s %s" % (self.magic, self.problem_id, answer, score, problem_name, level)) submission.put() self.increment_number_of_attempts(self.magic, self.level, self.problem_id, problem_name) self.best_score(self.magic, self.level, self.problem_id, problem_name, score)
def getSubmissionInfo(inputFile): """ submission.csv data format: submission ID | track ID | track name | title | authors | submit time | last update time | form fields | keywords | decision | notified | reviews sent | abstract File has header """ submission = Submission(inputFile) return submission.getSubmissionInfo()
def setUp(self) -> None: # Create a submission model self.mock_submission = MockSubmissionObject(name='mock_submission', sub_name="mock_subreddit", num_comments=10, ups=3, comments=None) self.submission_model = Submission(self.mock_submission)
def submit(request): if request.method == 'POST': f = SubmitForm(request.POST, request.FILES) if f.is_valid(): u = uuid1() s = Submission(uuid=u) answer_file = f.cleaned_data['answer_file'] answer_file.name = 'answer.csv' truth_file = f.cleaned_data['truth_file'] truth_file.name = 'truth.csv' s.answer = answer_file s.truth = truth_file s.type = f.cleaned_data['tasktype'] redundancy_json, redundancy = get_worker_redundancy(answer_file) quality_json, quality = get_worker_quality(answer_file, truth_file) s.redundancy = repr(redundancy) s.quality = repr(quality) s.save() # return HttpResponse('success!') return redirect('/show/?sid=' + str(u)) else: return HttpResponse(str(f.errors)) else: return redirect('/')
def new_submission(assignment_id): assignment = Assignment.query.get(assignment_id) if request.method == 'POST' and 'file' in request.files: filename = submissions.save(request.files['file']) rec = Submission( filename=filename, is_official=False, assignment_id=assignment_id, user_id=g.user.id) rec.save() rec.officialize() return redirect(url_for('view_assignment', assignment_id=assignment_id))
def new_abandoned_submission(self, source_id): '''For issue #1189''' source = Source.query.filter(Source.filesystem_id.isnot(None)).all()[0] filename = self.fake_file(source.filesystem_id) # Use this as hack to create a real submission then swap out the # source_id submission = Submission(source, filename) submission.source_id = source_id db.session.add(submission) db.session.commit() self.delete_source(source_id)
def post(self): format = self.request.get('format', 'json').lower() id = self.request.get('level_id', None) if id is None: res = {"response": {"error": "no level id with submission"}} else: level = Level.get_by_id(long(id)) user_name = self.request.get('user') user = User.all().filter('name =', user_name).get() if user is None: user = User(name = user_name) user.put() score = self.request.get('score', 0) words_found = self.request.get('words_found').split(",") submission = Submission() submission.user = user submission.level = level submission.score = score submission.words_found = words_found submission.time = datetime.datetime.now() submission.put() res = {"response": {"status" : "OK"}} if format == "json": self.response.out.write(simplejson.dumps(res)) elif format == "xml": self.response.out.write(dict2xml(res).to_string())
def remote_judge_create_submission(uuid: str, client_session_id: str, code: str, language: str, uid: int, hj2_problem_id: str, public: bool, message: str, contest_id: int = -1, contest_problem_id: int = -1): print(locals()) """ 评测端向远程OJ提交代码成功后,创建相应的提交记录 """ if uuid not in config.JUDGERS: return make_response(-1, message="未认证评测机") import datetime if contest_id != -1: contest: Contest = Contest.by_id(contest_id) submission: Submission = Submission( uid=uid, language=language, problem_id=contest.problems[contest_problem_id]["id"], submit_time=datetime.datetime.now(), public=False, code=code, status="waiting", contest_id=contest_id) else: submission: Submission = Submission( uid=uid, language=language, problem_id=hj2_problem_id, submit_time=datetime.datetime.now(), public=public, code=code, status="waiting", ) db.session.add(submission) db.session.commit() print("Submit done. ", submission.id) emit("server_response", { "ok": True, "data": { "submission_id": submission.id } }, room=client_session_id, namespace="/ws/remote_judge") return make_response(0, data={"submission_id": submission.id})
def save(request): form = request.POST sub = Submission( user=form["user"], date=time.strftime("%Y-%m-%d %H:%M:%S"), language=form["language"], code=form["code"], input=form["input"], ) try: sub["memory"] = form["memory"] sub["time"] = form["time"] finally: sub.save() return HttpResponse("OK")
def get(self, test, colour): """Retrieve recent submission, limited to a certain colour.""" self.response.content_type = "application/json" qry = Submission.query() if colour is not None: qry = qry.filter(Submission.colour == colour) qry = qry.order(-Submission.date) items = [] submissions = qry.fetch(50) for submission in submissions: items.append({ "id": submission.key.id(), "colour": submission.colour, "url": submission.url, "date": submission.date.strftime("%Y-%m-%dT%H:%M:%S.%f") }) self.response.out.write(json.dumps({"items": items}))
def submit_handle(): if request.method == 'POST': pid = int(request.form['probID']) lang = request.form['lang'] code = request.form['code'] prob = Problem.query.get(pid) if prob: info = json.loads(prob.info) num_td = int(info['td_num']) date_time = datetime.datetime.now() sub = Submission(result='Wait', resTime=-1.0, resMem=-1.0, code=code, lang=lang, rank=-1, time=date_time, account=current_user, problem=prob) db.session.add(sub) db.session.commit() log.debug('Add problem pid={} subid={}'.format( prob.problem_id, sub.submit_id)) manage.add_judger(sub.submit_id, prob.problem_id, judge.JUDGE_CPP, code, 3.0, 65536, num_td) return redirect(url_for('submissions_page.submissions_handle')) # not if return render_template('submit.html')
def mark_submission(user_id: UUID, user_role: Role, submission: schemas.Submission): is_authorized(user_role, "mark_submission") mark = Mark.tick if submission.mark == "tick" else Mark.cross marks_to_award = submission.marks submission_id = submission.submission_id submission = Submission.get(id=submission_id) if not submission: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=("Submission not found : submission_id: {}".format( submission_id))) if submission.mark == Mark.unmarked: submission.mark = mark if marks_to_award: submission.marks_obtained = marks_to_award else: submission.marks_obtained = (submission.question.marks if mark == Mark.tick else 0) performance_review(submission) return submission.to_dict() raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=("Submission already auto marked : submission_id: {}".format( submission_id)))
def get(self, test): """Retrieve submissions for the current user.""" self.response.content_type = "application/json" gplus_id = self.session.get("gplus_id") if gplus_id is None: self.response.status = 401 self.response.out.write(utils.createError(401, "Current user not connected.")) return if test is not None: user = ndb.Key("TestUser", gplus_id).get() else: user = ndb.Key("User", gplus_id).get() if user is None: self.response.status = 401 self.response.out.write(utils.createError(401, "Current user not connected.")) return items = [] submissions = Submission.query(ancestor=user.key).order(-Submission.date).fetch(50) for submission in submissions: items.append({ "id": submission.key.id(), "colour": submission.colour, "url": submission.url, "date": submission.date.strftime("%Y-%m-%dT%H:%M:%S.%f") }) self.response.out.write(json.dumps({"items": items}))
def get_level_stats(self, format, delta = datetime.timedelta(), page = 0, limit = 100): level = get_current_level() if level is not None: submissions = Submission.all().filter("time >", level.time - delta).order('time').order('-score').fetch(limit, page * limit) i = 1 ranks = [] for submission in submissions: obj = {"rank" : i, "user" : submission.user.name, "score" : submission.score} if format == "json": ranks.append(obj) elif format == "xml": ranks.append({"ranking": obj}) i = i + 1 res = {"response": ranks} else : res = {"response": {"error": "could not get the level"}} if format == "json": return simplejson.dumps(res) elif format == "xml": return dict2xml(res).to_string()
def post(self): form = json.loads(self.request.get('form')) name = form['name'] usid = form['usid'] pid = form['pid'] image_url = form['image-url'] Submission(name=name, usid=usid, pid=pid, image_url=image_url).put()
def __init__(self, submissions: list): """ Generates a submission generator object :param submissions: list of PRAW submission objects. """ self.submissions_generator = (Submission(submission) for submission in submissions)
def get_list(submissions: list): """ Returns a list of submission objects :param submissions: :return: list """ return [Submission(submission) for submission in submissions]
def insert_message(self, filename, submitter, region, date, message_id, attachment_id, attachment): # Check if file is already in database else return None if self.duplicate_file(filename) and config.enforce_unique_files: log.info( 'Attempt to insert file {} in database disallowed. Set enforce_unique_files in ' 'config.py to "False" to allow'.format(filename)) return None new_submission = Submission(Filename=filename, Submitter=submitter, Region=region, Date=date, Message_Id=message_id, Attachment_Id=attachment_id, Attachment_Binary=attachment) self.session.add(new_submission) self.session.commit() log.info( "Message from {} with eligible attached files committed to database." .format(submitter)) i = new_submission.Id log.debug('Last message insert available on row %s in database' % str(i)) return i
def get_all_attempts(self, magic, level, problemid, prob_type): return ( Submission.all() .filter("student_magic_number =", str(magic)) .filter("type =", str(prob_type)) .filter("level =", level) .filter("problem_id =", problemid) )
def upload_file(): title = request.form['song'] artist = request.form['artist'] picture_file = request.files['file'] photo = Photo() photo.file.put(picture_file) photo.save() track = Track.get_from_spotify(artist, title) if track is None: return "No track found!" track.save() submission = Submission(photo=photo, track=track) submission.save() return redirect('/submissions')
def create_source_and_submissions( source_index, source_count, num_submissions=2, num_replies=2, journalist_who_replied=None # noqa: W605, E501 ): # Store source in database codename = current_app.crypto_util.genrandomid() filesystem_id = current_app.crypto_util.hash_codename(codename) journalist_designation = current_app.crypto_util.display_id() source = Source(filesystem_id, journalist_designation) source.pending = False db.session.add(source) db.session.commit() # Generate submissions directory and generate source key os.mkdir(current_app.storage.path(source.filesystem_id)) current_app.crypto_util.genkeypair(source.filesystem_id, codename) # Generate some test submissions for _ in range(num_submissions): source.interaction_count += 1 submission_text = next(submissions) fpath = current_app.storage.save_message_submission( source.filesystem_id, source.interaction_count, source.journalist_filename, submission_text) source.last_updated = datetime.datetime.utcnow() submission = Submission(source, fpath) db.session.add(submission) # Generate some test replies for _ in range(num_replies): source.interaction_count += 1 fname = "{}-{}-reply.gpg".format(source.interaction_count, source.journalist_filename) current_app.crypto_util.encrypt( next(replies), [ current_app.crypto_util.get_fingerprint(source.filesystem_id), config.JOURNALIST_KEY ], current_app.storage.path(source.filesystem_id, fname)) if not journalist_who_replied: journalist = Journalist.query.first() else: journalist = journalist_who_replied reply = Reply(journalist, source, fname) db.session.add(reply) db.session.flush() seen_reply = SeenReply(reply_id=reply.id, journalist_id=journalist.id) db.session.add(seen_reply) db.session.commit() print("Test source {}/{} (codename: '{}', journalist designation '{}') " "added with {} submissions and {} replies".format( source_index, source_count, codename, journalist_designation, num_submissions, num_replies))
def get(self): magic = self.request.get('student') submissions = Submission.all().filter('student_magic_number =', str(magic)) submissions_objects = [] for submission in submissions: utc = int(time.mktime(submission.answered_on.timetuple())) submissions_objects.append({"type":submission.type, "level":submission.level, "id":submission.problem_id, "score":submission.score, "answered_on":utc, "answer":submission.answer}) blob = json.dumps(submissions_objects) self.response.out.write(blob)
def _save_submission(self,request): def get_type(request): try: return FacilityType.objects.get(name=request.POST['type']) except KeyError: return None submit_args = { 'submitter':request.user, 'raw':repr(request.POST), 'name':request.POST.get('name',None), 'address':request.POST.get('address',None), 'type':get_type(request), 'location':get_location(request.POST) } submission = Submission(**submit_args) submission.save() return submission
def _create_source_and_submission(config_in_use: SecureDropConfig) -> Path: """Directly create a source and a submission within the app. Some tests for the journalist app require a submission to already be present, and this function is used to create the source user and submission when the journalist app starts. This implementation is much faster than using Selenium to navigate the source app in order to create a submission: it takes 0.2s to run, while the Selenium implementation takes 7s. """ # This function will be called in a separate Process that runs the app # Hence the late imports from encryption import EncryptionManager from models import Submission from passphrases import PassphraseGenerator from source_user import create_source_user from store import Storage, add_checksum_for_file from tests.functional.db_session import get_database_session # Create a source passphrase = PassphraseGenerator.get_default().generate_passphrase() with get_database_session( database_uri=config_in_use.DATABASE_URI) as db_session: source_user = create_source_user( db_session=db_session, source_passphrase=passphrase, source_app_storage=Storage.get_default(), ) source_db_record = source_user.get_db_record() EncryptionManager.get_default().generate_source_key_pair(source_user) # Create a file submission from this source source_db_record.interaction_count += 1 app_storage = Storage.get_default() encrypted_file_name = app_storage.save_file_submission( filesystem_id=source_user.filesystem_id, count=source_db_record.interaction_count, journalist_filename=source_db_record.journalist_filename, filename="filename.txt", stream=BytesIO(b"File with S3cr3t content"), ) submission = Submission(source_db_record, encrypted_file_name, app_storage) db_session.add(submission) source_db_record.pending = False source_db_record.last_updated = datetime.now(timezone.utc) db_session.commit() submission_file_path = app_storage.path(source_user.filesystem_id, submission.filename) add_checksum_for_file( session=db_session, db_obj=submission, file_path=submission_file_path, ) return Path(submission_file_path)
def update_group(self, key): if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if group.owner.user_id() != user.user_id() and not auth.user_is_admin(): Messages.add('Only the owner of the group owner may modify it') return self.redirect('/groups') name = self.request.get('name') public = self.request.get('public') == 'public' abandon = self.request.get('abandon-project') sub_text = self.request.get('submission-text') sub_url = self.request.get('submission-url') remove_submission = self.request.get_all('remove-submission') remove = self.request.get_all('remove') owner = self.request.get('owner') delete = self.request.get('delete') if delete: group.delete() return self.redirect('/groups') group.name = name group.public = public if abandon: group.project = None if sub_text and sub_url: Submission(text=sub_text, url=sub_url, group=group).put() for sub in Submission.get(remove_submission): sub.delete() pending = list(group.pending_users) for user in pending: approve = self.request.get("approve-%s" % user) if approve == "approve": group.members.append(user) group.pending_users.remove(user) elif approve == "refuse": group.pending_users.remove(user) group.owner = auth.user_from_email(owner) for user in remove: if auth.user_from_email(user) == group.owner: Messages.add('Cannot remove the group owner') return self.redirect('/groups/%s/edit' % key) else: group.members.remove(auth.user_from_email(user)) group.put() return self.redirect('/groups/%s' % key)
def post_queue_copytoava(): if (not request.json) or (not 'queueId' in request.json): abort(400) if (not 'avaQueueId' in request.json): abort(400) q_id = int(request.json['queueId']) aq_id = int(request.json['avaQueueId']) # Get the queue information queue = Queue.query.filter(Queue.id == q_id).first() ava_queue = Queue.query.filter(Queue.id == aq_id).first() if not queue: abort(404) if not ava_queue: abort(404) # Check if queue is a scheduled queue if queue.qType != 2: abort(403) if ava_queue.qType != 1: abort(403) # Submit to queue using normal submission function subs = queue.submissions subs_to_remove = ava_queue.submissions for sub in subs_to_remove: db.session.delete(sub) db.session.commit() ava_subs = [] for sub in subs: ava_sub = Submission() ava_sub.ava_clone(sub, ava_queue) db.session.add(ava_sub) ava_subs.append(ava_sub) db.session.commit() # Create match to be scheduled for p, q in itertools.combinations(ava_subs,2): match = schedule_match(ava_queue, p, q, test=False) return jsonify({'done': True}), 201
def get(self): submissions = [] #subs= Submission.gql("WHERE pid=:1", 11) for submission in Submission.all().order('-post_time'): submissions.append({ 'name': submission.name, 'pid': submission.pid, 'image_url': submission.image_url, }) self.response.out.write(json.dumps(submissions))
def _addSubmission(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Please login to continue") data = { field.name: getattr(request, field.name) for field in request.all_fields() } q_key = ndb.Key(urlsafe=request.websafekey) del data['websafekey'] s_id = Submission.allocate_ids(size=1, parent=q_key)[0] s_key = ndb.Key(Submission, s_id, parent=q_key) data['key'] = s_key data['user'] = user data['subskey'] = s_key.urlsafe() Submission(**data).put() return SubmissionForm(code=data['code'], score=data['score'], language=data['language'])
def new_submission(self, source_id): source = Source.query.get(source_id) # A source may have a null fid according to the DB, but this will # break storage.path. if source.filesystem_id is None: return filename = self.fake_file(source.filesystem_id) submission = Submission(source, filename) # For issue #1189 if random_bool(): submission.source_id = None submission.downloaded = bool_or_none() db.session.add(submission) db.session.flush() self.submissions.append(submission.id)
def get(self): submissions = [] for submission in Submission.all().order('-post_time'): submissions.append({ 'name': submission.name, 'usid': submission.usid, 'pid': submission.pid, 'image_url': submission.image_url, 'post_time': str(submission.post_time), }) self.response.out.write(json.dumps(submissions))
def submit(): if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr form = SubmissionForm(request.form) if request.method == 'POST': text = form.body.data try: if session['qb'] == True: status = 'quietbanremoval' submission = Submission(body=text, ip=ip, u_a=request.user_agent.string, status=status) db.session.add(submission) db.session.commit() except KeyError: # if a KeyError is thrown, the user is not quietbanned. pass # search to see if the post contains any filtered expressions exp = re.compile(g.settings.regex_filter) if exp.search(text): status = 'autoremoval' else: status = 'unset' submission = Submission(body=text, ip=ip, u_a=request.user_agent.string, status=status) db.session.add(submission) db.session.commit() return render_template("submit.html", form=form, admin=g.admin, message=True) else: return render_template('submit.html', form=form, admin=g.admin)
def submit(request): team = get_team(request.user) params = dict() if request.method == 'POST': form = forms.UploadSubmissionForm(request.POST, request.FILES) params['form'] = form if form.is_valid(): submission = Submission( team=team, package=request.FILES['file'], command=request.POST['command'], ) submission.save() error = utils.unzip(submission.package.path) if error: submission.delete() params['error'] = error return render_submit(request, params) try: execute_tester(submission) except Exception as error: print u'ERROR: Blad wewnetrzny testerki:', error return my_results(request, message=_(u'Rozwiązanie zostało wysłane.')) return render_submit(request, params)
def save_update_db(load_info): latinput = load_info['lat_input'] lnginput = load_info['lng_input'] datepicker = load_info['datepicker'] tipo = load_info['tipo'] notes = load_info['notes'] print('entrou update', latinput, lnginput) newsub = Submission(latinput=latinput, lnginput=lnginput, type_S=tipo, temp=datepicker, notes=notes) db.session.add(newsub) db.session.flush() print('ppppp ', newsub, newsub.id) file_urls = [] image_list = load_info['images'] for k, image in enumerate(image_list): print(allowed_image(image.filename)) if allowed_image(image.filename): ext = image.filename.rsplit(".", 1)[1] new_filename = image.filename.rsplit(".", 1)[0] + '_sub' + str( newsub.id) + '.' + ext filename = photos.save(image, name=new_filename) print('rrr', filename) file_urls.append(photos.url(filename)) newfile = Images(sub=newsub, img_data=image.read(), img_name=new_filename, stamp_save=date.today()) db.session.add(newfile) print('aaaa ', newfile) print(file_urls) db.session.commit() session['images_urls'] = file_urls print('saved to database') return 'Saved to database'
def create_submission(user_id: UUID, user_role: Role, submission: schemas.Submission): is_authorized(user_role, "create_submission") question = Question.get(id=submission.question_id) if not question: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=("Question not found : question_id: {}".format( submission.question_id))) participant = Participant.get(exam=question.exam, user=User[user_id]) if not participant: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=("Participant not found : exam_id: {}".format( question.exam.id))) if len(question.multi_choice) > 0: if submission.answer == question.answer: marks_obtained = question.marks mark = Mark.auto_tick else: marks_obtained = 0 mark = Mark.auto_cross submission = Submission(answer=submission.answer, question=question, user=User[user_id], marks_obtained=marks_obtained, mark=mark) else: submission = Submission(answer=submission.answer, question=question, user=User[user_id]) performance_review(submission) return submission.to_dict()
def handle(self, sms): """Método chamado pelo RapidSMS para processar uma mensagem""" sub_type = Submission.TYPE_SMS # estamos organizando as outras branchs do projeto answer = Config.get("message_unknown_format") if Submission.has_confirmation_pending(sms.connection.identity): submission = Submission.get_unconfirmed(sms.connection.identity) answer = submission.confirm(sms.text) return self.send_answer(sms, answer) if Form.main_form_exists(): form = Form.get_main_form() else: keyword, separator, remaining_message = Form.extract_keyword(sms.text) sms.text = remaining_message form = Form.get_by_keyword_and_separator(keyword, separator) if form: answer = form.process_submission(sms, sub_type) or answer return self.send_answer(sms, answer)
def _addSubmission(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Please login to continue") data = {field.name: getattr(request, field.name) for field in request.all_fields()} q_key = ndb.Key(urlsafe=request.websafekey) del data['websafekey'] s_id = Submission.allocate_ids(size = 1, parent=q_key)[0] s_key = ndb.Key(Submission, s_id, parent=q_key) data['key'] = s_key data['user'] = user data['subskey'] = s_key.urlsafe() Submission(**data).put() return SubmissionForm(code=data['code'], score=data['score'], language=data['language'])
def populate(connection_string, root_path, ignore_lock=False): """ Populates database with submission objects :connection_string: :root_path: :return: list of Submission models """ ret = [] # Check is not populated alread if not ignore_lock and os.path.exists(config.DATABASE_POPULATED_LOCK_FILE): logging.info( "Database lock file {} exists, will not seed database".format( config.DATABASE_POPULATED_LOCK_FILE)) return for (path, directories, files) in os.walk(root_path): if not files: continue if files == [config.RESULTS_FILENAME]: group, student_id, module, submission_date = path.split("/")[-4:] fn = path + "/" + files[0] with open(fn, "r") as fp: results = json.load(fp) submission = Submission().load(path, results) ret.append(submission) else: msg = "Unexpected files {} found in directory {}".format( files, path) logging.warning(msg) connect(host=connection_string) for submission in ret: submission.save() # Create lockfile open(config.DATABASE_POPULATED_LOCK_FILE, "w").close() return ret
def submit(request): team = request.user.team params = dict() if request.method == 'POST': form = UploadSubmissionForm(request.POST, request.FILES) params['form'] = form if form.is_valid(): submission = Submission( team=team, package=request.FILES['file'], user=request.user, ) submission.save() error = utils.unzip(submission.package.path) if error: submission.delete() params['error'] = error return render_submit(request, params) submissions = team.submission_set.all() if len(submissions) > 2: for sub in submissions[2:]: sub.delete() execute_tester(submission) messages.add_message(request, messages.INFO, _(u'Rozwiązanie zostało wysłane')) return redirect('my_results') #return my_results( # request, message=_(u'Rozwiązanie zostało wysłane.')) else: print form.errors return render_submit(request, params)
def get_field_objects(submission): """ Get a list of field objects for a particular submission/collection """ # Slightly evil, do type checking to see if submission is a Submission object or string if isinstance(submission, str) or isinstance(submission, unicode): # Get the queryset for the form collection to pass in our dictionary try: submission = Submission.objects.get(slug=submission) except Submission.DoesNotExist: raise Submission.DoesNotExist('Submission %s does not exist. Make sure the slug name is correct.' % submission) fields = Field.objects.filter(dataform__collection__submission__id=submission.id).order_by('dataform__collectiondataform', 'dataformfield__order') return fields
def submit_file(module_number): if not allowed_module(module_number - 1): abort(404) file = request.files.get('file') if not file or file.filename == '': return jsonify({"errors":"no file attached"}) if not allowed_file(file.filename): return jsonify({"errors":"invalid file type"}) filename = secure_filename(file.filename) file.save(os.path.join(uploads_dir, filename)) key = current_user.username + "_" + str(module_number) + "." + filename.rsplit('.', 1)[1].lower() client.upload_file(os.path.join(uploads_dir, filename), 'online-portal', key) uploaded = Submission(username=current_user.username, module=module_number-1, key=key) db.session.add(uploaded) db.session.commit() return render_template('submitted.jinja2')
def new_submission(assignment_id): assignment = Assignment.query.get(assignment_id) if request.method == 'POST' and 'file' in request.files: filename = submissions.save(request.files['file']) rec = Submission(filename=filename, is_official=False, assignment_id=assignment_id, user_id=g.user.id) rec.save() rec.officialize() return redirect(url_for('view_assignment', assignment_id=assignment_id))
def get(self, test): """Retrieve recent submissions""" self.response.content_type = "application/json" qry = Submission.query() qry = qry.order(-Submission.date) items = [] users = set() curs = Cursor(urlsafe=self.request.get('cursor')) submissions, next_curs, more = qry.fetch_page(10, start_cursor=curs) for submission in submissions: items.append({ "id": submission.key.id(), "user": submission.key.parent().id(), "colour": submission.colour, "url": submission.url, "date": submission.date.strftime("%Y-%m-%dT%H:%M:%S.%f") }) users.add(submission.key.parent().id()) user_data = dict() for user_id in users: user = ndb.Key("User", user_id).get() if user is None: user = ndb.Key("TestUser", user_id).get() if user is not None: user_data[user_id] = { "displayName": user.displayName, "imageUrl": user.imageUrl } response = {} response["items"] = items response["users"] = user_data if more and next_curs: response["next"] = next_curs.urlsafe() self.response.out.write(json.dumps(response))
def create_submission( title=u'submission titlé', description=u'submission déscription', url=u'http://www.url.com/test', created=datetime.datetime.now(), submitted=datetime.datetime.now()): submission = Submission() submission.title = title submission.description = description submission.url = url submission.created = created submission.submitted = submitted return submission
def form_valid(self, form): # header = "{email} supplied a form!".format( # email=form.cleaned_data.get('email_address')) # message = "\n\nType: {0}".format(form.cleaned_data.get('ticket_type').encode('utf-8')) # message += "\n\nCourt: {0}".format(form.cleaned_data.get('group_court')) # message += "\n\ncontact_method: {0}".format(form.cleaned_data.get('contact_method')) # send_mail( # subject=header, # message=message, # from_email='*****@*****.**', # recipient_list=['*****@*****.**'], # ) c = Submission() c.software_download = form.cleaned_data.get('software_download') c.email_address = form.cleaned_data.get('email_address') c.submitter_name = form.cleaned_data.get('submitter_name') c.institution = form.cleaned_data.get('institution') c.save() return super(ContactFormView, self).form_valid(form)
def update_group(self, key): """Updates a group with information from the moderation form. Form Variables: name: the name of the group public: true if the group should be joinable by the public abandon-project: true if the group moderator wants to abandon the current project submission-text: the text to be displayed for the new submission submission-url: the URL of the new submission remove-submission: a list of submissions to be removed remove: a list of users to be removed from the group owner: the owner of the group delete: true if the group moderator wants to disband the group """ if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if (group.owner.user_id() != user.user_id() and not auth.user_is_admin()): Messages.add('Only the owner of the group owner may modify it') return self.redirect('/groups') name = self.request.get('name') public = self.request.get('public') == 'public' abandon = self.request.get('abandon-project') sub_text = self.request.get('submission-text') sub_url = self.request.get('submission-url') remove_submission = self.request.get_all('remove-submission') remove = self.request.get_all('remove') owner = self.request.get('owner') delete = self.request.get('delete') if delete: group.delete() return self.redirect('/groups') group.name = name group.public = public if abandon: group.project = None if sub_text and sub_url: Submission(text=sub_text, url=sub_url, group=group).put() for sub in Submission.get(remove_submission): sub.delete() pending = list(group.pending_users) for user in pending: approve = self.request.get("approve-%s" % user) if approve == "approve": group.members.append(user) group.pending_users.remove(user) elif approve == "refuse": group.pending_users.remove(user) group.owner = auth.user_from_email(owner) for user in remove: if auth.user_from_email(user) == group.owner: Messages.add('Cannot remove the group owner') return self.redirect('/groups/%s/edit' % key) else: group.members.remove(auth.user_from_email(user)) group.put() return self.redirect('/groups/%s' % key)
def get_all_attempts(self, magic, level, problemid, prob_type): return Submission.all().filter('student_magic_number =', str(magic)).filter('type =', str(prob_type)).filter('level =', level).filter('problem_id =', problemid)
def rebuild_tables(db) : Submission.create_table(db) Comment.create_table(db) Stream.create_table(db)
def submit(self, request, object_id): submission = Submission.from_message(self._getobj(request, object_id)) return HttpResponseRedirect('../../../submission/%s/' % submission.id)