示例#1
0
def hello(name=None):
	form = SubmissionForm()
	print(threading.activeCount())
	runningCounter = {
		"JPred": 0,
		"PSI": 0,
		"PSS": 0,
		"RaptorX": 0,
		"Sable": 0,
		"Yaspin": 0,
		"SSPro": 0
	}
	for t in threading.enumerate():
		if t.getName() in runningCounter.keys():
			runningCounter[t.getName()] += 1

	if form.validate_on_submit():

		if threading.activeCount() > 100:
			return redirect(url_for('errorpage'))
		post_data = {
			'seqtext': ''.join(form.seqtext.data.split()),
			'email': form.email.data,
			'JPred': form.JPred.data,
			'PSI':   form.PSI.data,
			'PSS':   form.PSS.data,
			'RaptorX': form.RaptorX.data,
			'Sable':   form.Sable.data,
			'Yaspin':   form.Yaspin.data,
			'SSPro':   form.SSPro.data,
			'submitbtn': 'Submit'
			}

		total_sites = validate_sites(post_data)
		post_data.update({'total_sites' : total_sites, 'completed': 0}) # add total into to post_data dictionary and a completed prediction counter
		print(post_data)
		seq = post_data['seqtext']

		startTime = batchtools.randBase62()		

		if post_data['email'] != "": #send email to let users know input was received
			emailtools.sendEmail(email_service, post_data['email'],"Prediction Input Received", "<div>Input received for the following sequence:</div><div>" + seq + "</div><div>Results with customization options will be displayed at the following link as soon as they are available:</div><div>" + siteurl + "/dboutput/" + startTime +"</div>")

		#Stores currently completed predictions
		ssObject = []

		dbinsert(startTime, seq)

		pdbdata = None
		if form.structureId.data is not None:
			pdbdata = batchtools.pdbget(form.structureId.data, form.chainId.data)
			if pdbdata is not None:
				dbupdate(startTime, 'pdb', json.dumps(pdbdata))
				dbupdate(startTime, 'seq', pdbdata['primary'])
				seq = pdbdata['primary']
		
		sendData(seq, startTime, ssObject, post_data, pdbdata)
		return redirect(url_for('showdboutput', var = startTime))
		
	return render_template('index.html', form = form, counter = runningCounter) #default submission page
示例#2
0
def index():
	form = SubmissionForm()

	global correct_sentence
	global location
	if form.validate_on_submit():
		sentence = form.sentence.data
		correct_sentence, location = locate_missin_word(sentence, vocabulary, bigram_table, trigram_table)
示例#3
0
def ask_question():
    form = SubmissionForm()
    if form.validate_on_submit():
        flash('Your question "{}" has been submitted successfully!'.format(
            form.title.data))
        return redirect('/experts_recommendation')
    return render_template('new_question.html',
                           title='New Question',
                           form=form)
示例#4
0
def prediction():
    form = SubmissionForm(request.form)

    # Form has been submitted
    if request.method == 'POST' and form.validate():

        data = {
            "Inputs": {
                "input1": [{
                    'Salary_class_2-8-greater8': "1",
                    'FG': form.FG.data.lower(),
                    'PTS': form.PTS.data.lower(),
                    'FGA': form.FGA.data.lower(),
                    'Two_P': form.Two_P.data.lower()
                }],
            },
            # "GlobalParameters":  {
            # }
            "GlobalParameters": {
                'The initial learning weights diameter': "0.01",
            }
        }
        # Serialize the input data into json string
        body = str.encode(json.dumps(data))

        # Formulate the request
        req = urllib.request.Request(NBA_ML_URL, body, HEADERS)

        # Send this request to the AML service and render the results on page
        try:
            response = urllib.request.urlopen(req)
            respdata = response.read()
            result = json.loads(str(respdata, 'utf-8'))
            result = get_prediction_data(result)
            return render_template(
                'result.html',
                title="This is the result from AzureML running our prediction:",
                result=result,
                bucket=s3_bucket)

        # An HTTP error
        except urllib.error.HTTPError as err:
            result = "The request failed with status code: " + str(err.code)
            return render_template('result.html',
                                   title='There was an error',
                                   result=result,
                                   bucket=s3_bucket)

    # Just serve up the input form
    return render_template(
        'form.html',
        form=form,
        title='Run App',
        message='Demonstrating a website using Azure ML Api',
        bucket=s3_bucket)
示例#5
0
def new_submission(request):
    if request.method == 'POST':
        form = SubmissionForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('artshow.views.submissions'))
    else:
        form = SubmissionForm()
    return render_to_response('artshow/new_submission.html', 
                              {'form' : form},
                              context_instance=RequestContext(request))
示例#6
0
def submit_problem(pid):
    form = SubmissionForm(pid = pid)
    if request.method == 'POST' and form.validate():
        submit = Submit(runid = Submit.query.count() + 1, userid = current_user.userid,pid = form.pid.data, language = form.language.data, src = form.src.data, submit_time = get_now_time())
        submit.save()
        print "submit successfully"
        return redirect(url_for('status'))
    error = get_error(form)
    if error:
        flash(error)
    return render_template('submit.html',form = form,pid = pid)
示例#7
0
def simulate_submission():
    form = SubmissionForm()

    if form.validate_on_submit():
        try:
            db.insert_submission(form.user.data, form.problem.data,
                                 form.language.data, form.status.data)
            flash(f'Envio realizado con exito!', 'success')
        except RuntimeError as err:
            flash("ERROR: {}".format(err.args[0]), 'danger')
        finally:
            return redirect(url_for('simulate_submission'))

    return render_template('submission.html', form=form)
示例#8
0
def submit(request, prob_id):
    session = Session()
    prob = session.query(Problem).get(int(prob_id))
    if request.method == "POST":
        form = SubmissionForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(problem=prob, user=request.user)
            return HttpResponseRedirect(reverse('status', kwargs={'page': 1}))
    else:
        form = SubmissionForm()
    res = render_to_response('problem/submit.html', {"prob": prob, "form": form},
                             context_instance=RequestContext(request))
    session.close()
    return res
示例#9
0
    def prepare_submission_forms(self):
        # forms = self.conf_assay['submission_forms']
        forms = self.conf_main.get_value('submission_forms')
        self.logger.info(
            'Start processing the following submission forms for the current request: {}'
            .format(forms))
        for form in forms:
            self.logger.info('Processing submission form "{}".'.format(form))
            try:
                # submission_form = None  # reset the submission form reference
                if form['assignment'] == 'aliquot':
                    # prepare an instance of the current form for each aliquot
                    for sa, a, smpl in zip(self.req_obj.sub_aliquots,
                                           self.req_obj.aliquots,
                                           self.req_obj.samples):
                        if not sa in self.req_obj.disqualified_sub_aliquots.keys(
                        ):
                            self.logger.info(
                                'Prepare submission form "{}" for sub_aliquot "{}".'
                                .format(form['name'], sa))
                            submission_form = SubmissionForm(
                                form['name'], self.req_obj, sa, a, smpl,
                                form['file_name_id'])
                            self.add_submission_form(
                                sa, form['assignment'],
                                submission_form)  # .json_form.json_data
                elif form['assignment'] == 'request':
                    #populate list of qualifed aliquots (removing all disqualified ones during attachment preps, etc.)
                    self.req_obj.populate_qualified_aliquots()

                    self.logger.info(
                        'Prepare submission form "{}" of the request level.'.
                        format(form['name']))
                    submission_form = SubmissionForm(form['name'],
                                                     self.req_obj, None, None,
                                                     None,
                                                     form['file_name_id'])
                    self.add_submission_form(form['assignment'],
                                             form['assignment'],
                                             submission_form)
                else:
                    _str = 'Submission form "{}" had an unexpected configuration "assignment" key "{}" ' \
                           'and was not created.'.format(form['name'], form['assignment'])
                    self.logger.error(_str)
                    self.error.add_error(_str)
            except Exception as ex:
                _str = 'Unexpected error "{}" occurred during processing submission form "{}". \n{} ' \
                    .format(ex, form, traceback.format_exc())
                self.logger.error(_str)
                self.error.add_error(_str)
示例#10
0
def index():
    form = SubmissionForm()
    if form.validate_on_submit():
        text = form.text.data
        radio = form.radio.data
        delimiters = form.delimiters.data
        session['text'] = text
        session['delimiters'] = delimiters
        if (radio == 'wc'):
            return redirect(url_for('wordcount'))
        elif (radio == 'cc'):
            return redirect(url_for('charactercount'))
        else:
            return redirect(url_for('frequent'))
    return render_template('index.html', form=form)
示例#11
0
def submit_problem(pid):
    form = SubmissionForm(pid=pid)
    if request.method == 'POST' and form.validate():
        submit = Submit(runid=Submit.query.count() + 1,
                        userid=current_user.userid,
                        pid=form.pid.data,
                        language=form.language.data,
                        src=form.src.data,
                        submit_time=get_now_time())
        submit.save()
        print "submit successfully"
        return redirect(url_for('status'))
    error = get_error(form)
    if error:
        flash(error)
    return render_template('submit.html', form=form, pid=pid)
示例#12
0
def convert_file(request):
    kwargs = {"most_recent_survey" : "surveys-v0.2.xls"}

    # here's a hack to avoid dealing with serving static files
    # I've passed the responsibility to settings.py
    readme = codecs.open(settings.PATH_TO_XLS2XFORM + "README.mkdn", mode="r", encoding="utf8")
    text = readme.read()
    kwargs["documentation"] = markdown.markdown(text)

    textdoc = pydoc.TextDoc()
    kwargs["api"] = pydoc.plain( textdoc.docmodule(xls2xform) )

    kwargs["form"] = SubmissionForm()

    if request.method != "POST":
        # if nothing's posted give them an empty form
        return render_to_response("upload.html", kwargs)
    else:
        # otherwise pull the data out of the request and process it
        populated_form = SubmissionForm(request.POST, request.FILES)
        if populated_form.is_valid():
            s = populated_form.save()
            try:
                # process the excel file
                surveys = write_xforms(s.file.path)
                for survey in surveys:
                    x = XForm(submission=s, file=survey)
                    x.save()
                # list the files created
                return render_to_response("list.html", {"list": XForm.objects.filter(submission=s)})
            except ConversionError, e:
                # record and display any error messages
                s.error_msg = e.__str__()
                s.save()
                kwargs["msg"] = s.error_msg
                return render_to_response("upload.html", kwargs)
            except XLRDError, e:
                if e.__str__().startswith("Unsupported format, or corrupt file"):
                    s.error_msg = "xls2xform only accepts Excel 97 - 2004 Workbooks (.xls)"
                    s.save()
                    kwargs["msg"] = s.error_msg
                    return render_to_response("upload.html", kwargs)
                else:
                    raise e                    
示例#13
0
def create_submission(request, template="create_project.html"):
    project_id = request.GET.get("project_id")
    print "create submission for project:{}".format(project_id)

    form = SubmissionForm(request.POST or None)
    if project_id is not None:
        project = get_object_or_404(Project, pk=project_id)
        form = SubmissionForm(request.POST or None, initial={"project": project})

    if request.method == "POST" and form.is_valid():
        new_submission = form.save()
        print new_submission
        if project_id is None:
            project_id = new_submission.project.id
        event = {"time": datetime.now(), "project_id": int(project_id), "message": _("Create Submission")}
        create_log(event)
        return redirect("enterprise.submissions")
    context = {"form": form, "title": _("Create Submission")}
    return render(request, template, context)
示例#14
0
def disclosure(request):
    # Validate all fields
    print "alive!"
    context = dict()

    if request.method == "POST":
        # Do something
        print "sending form"
        disclosure = SubmissionForm(request.POST)
        if disclosure:
            template = "disclosure_post.html"
            context['success_message'] = "Disclosure created"
            ################
            # REFACTOR
            #
            # Save it in some manner
            if disclosure.is_valid():
                new_disclosure = Disclosure()
                new_disclosure.title = disclosure.cleaned_data.get(
                    "title", None)
                new_disclosure.abstract = disclosure.cleaned_data.get(
                    "abstract", None)
                new_disclosure.abstract_file = disclosure.cleaned_data.get(
                    "abstract_file", None)
                new_disclosure.body = disclosure.cleaned_data.get("body", None)
                new_disclosure.body_file = disclosure.cleaned_data.get(
                    "body_file", None)
                new_disclosure.owner = User.objects.all()[0]

                new_disclosure.save()
                disclosure_id = new_disclosure.id
                #
                ################
            return HttpResponseRedirect(
                '/disclosure/{0}'.format(disclosure_id))

    else:
        template = "disclosure.html"
        context['error_message'] = "Invalid disclosure"
        form = SubmissionForm()
        print "getting form"
        return render(request, template, {'form': form})
示例#15
0
def submit():
    form= SubmissionForm()
    if form.validate_on_submit():
        # Defines new variables from the form fields
        musicbrainz_album_id = request.form['musicbrainz_album_id']
        source = request.form['source']

        entry = (musicbrainz_album_id, source)
        print(str(entry))

        # Commits entry to database
        db.session.add(entry)
        db.session.commit()
        
        flash(f'Submitted your files!')

        return redirect(url_for('home'))
    else: 
        print('error')
    return render_template("submit.html", title='Submit', form=form)
示例#16
0
def index():
	global result
	form = SubmissionForm()
	if form.validate_on_submit():
		try:
			test_op1=float(form.operand1.data)
		except ValueError:
			return redirect(url_for('input_error'))
		try:
			test_op2=float(form.operand2.data)
		except ValueError:
			return redirect(url_for('input_error'))
			
		op1=float(form.operand1.data)
		op2=float(form.operand2.data)
		operator=(form.operator.data)


		if operator=="add":
			result= op1+op2
			return redirect(url_for('add'))

		elif operator=="subtract":
			result= op1-op2
			return redirect(url_for('subtract'))

		elif operator=="multiply":
			result= op1*op2
			return redirect(url_for('multiply'))

		else:
			if op2 == float(0):
				return redirect(url_for('divide_by_zero'))
			result= op1/op2		
			return redirect(url_for('divide'))

	return render_template("index.html",title="Form", form=form)
示例#17
0
def disclosure(request):
    # Validate all fields
    print "alive!"
    context = dict()

    if request.method == "POST":
        # Do something
        print "sending form"
        disclosure = SubmissionForm(request.POST)
        if disclosure:
            template = "disclosure_post.html"
            context['success_message'] = "Disclosure created" 
            ################
            # REFACTOR
            #
            # Save it in some manner
            if disclosure.is_valid():
                new_disclosure = Disclosure()
                new_disclosure.title = disclosure.cleaned_data.get("title", None)
                new_disclosure.abstract = disclosure.cleaned_data.get("abstract", None)
                new_disclosure.abstract_file = disclosure.cleaned_data.get("abstract_file", None)
                new_disclosure.body = disclosure.cleaned_data.get("body", None)
                new_disclosure.body_file = disclosure.cleaned_data.get("body_file", None)
                new_disclosure.owner = User.objects.all()[0]
                
                new_disclosure.save()
                disclosure_id = new_disclosure.id
                # 
                ################
            return HttpResponseRedirect('/disclosure/{0}'.format(disclosure_id))

    else:            
        template = "disclosure.html"
        context['error_message'] = "Invalid disclosure" 
        form = SubmissionForm()
        print "getting form"
        return render(request, template, {'form': form})
示例#18
0
def hello_world():
    form = SubmissionForm()
    print('hello')
    if request.method == 'POST':
        flash('Text Submitted!')
        if form.radio1.data == 'wordcount':
            textform = request.form['text']
            wordCount = textform.replace('\r\n', ' ')
            wordCount = wordCount.strip()
            delims = request.form['delimtext']
            if delims is None or delims == '':
                words = wordCount.split(' ')
                return "Number of words: " + str(len(words))
            else:
                wordlist = re.split('[' + delims + ']', wordCount)
                return "Number of words: " + str(len(wordlist))
            # delimtosplit = " " + delims

        elif form.radio1.data == 'charactercount':
            textform = request.form['text']
            charCount = textform.replace('\r\n', '')
            return "Number of chars: " + str(len(charCount))
        elif form.radio1.data == '5mostfrequent':
            textform = request.form['text']
            wordCount = textform.replace('\r\n', ' ')
            wordCount = wordCount.strip()
            delims = request.form['delimtext']
            delimtosplit = " " + delims
            words = wordCount.split(delimtosplit)
            dict2 = {}
            for word in words:
                if word in dict2:
                    dict2[word] += 1
                else:
                    dict2[word] = 1
            count = 0
            strtoprint = ""
            for (key) in (sorted(dict2, key=dict2.__getitem__, reverse=True)):
                strtoprint += key
                strtoprint += " "
                count += 1
                if count == 5:
                    break

            return "5 Most frequent words: " + strtoprint
        return redirect(url_for('result', optionname=form.radio1.data))

    return render_template('submit.html', form=form)
示例#19
0
def index():
    form = SubmissionForm()
    val = False
    prob_disease = []
    if request.method == 'POST':
        user_symptoms = [0] * 132
        user_symptoms = get_symptoms(request, user_symptoms)
        if all(val == 0 for val in user_symptoms):
            flash("Provide Symptoms for Prediction!!")
            return redirect('/')
        prob_disease = disease(user_symptoms)
        val = True

    return render_template("index.html",
                           form=form,
                           val=val,
                           prob_disease=prob_disease)
示例#20
0
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)
示例#21
0
def index(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SubmissionForm(request.POST, request.FILES)
        # check whether it's valid:
        if form.is_valid():
            sub = form.save(commit=False)
            sub.user = request.user
            sub.save()

            return redirect(sub)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = SubmissionForm()

    return render(request, 'index.html', {'form': form})
示例#22
0
def process_submission(request):
    """
    Processes the submission and returns back to the browser.
        
    :Return: HttpResponse
    """
    
    data = {
        'error' : False,
    }
    
    submission = None
    email_form = None

    try:
        #force the request to be ajax.
        request.META['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
        
        if request.method == 'POST' and request.POST.has_key('type'):
            
            #if submission is of type email, process the email form
            if 'email' in request.POST['type']:
                form, email_form = SubmissionForm(request.POST), EmailForm(request.POST)

            #else if submission is of type link, process the submission form
            elif 'link' in request.POST['type']:
                form = SubmissionForm(request.POST)
                
            else:
                raise ValidationError('Incorrect Post type.')
                
            form.instance.submit_ip = request.META['REMOTE_ADDR'] 
            form.instance.browser_meta = "%s  %s" % (
				request.META['HTTP_USER_AGENT'], 
				request.POST['flash_meta']
			)

            if form.is_valid():
                #save form
                form.save()
                #save email form
                if email_form: 
                    #set the pk from the submission
                    email_form.instance.submission = form.instance
                    if email_form.is_valid():
                        email_form.save()
                    else:    
                        raise ValidationError(email_form.errors)
            else:
                raise ValidationError(form.errors)
                
            submission = form.instance
            data['submission_slug'] = submission.slug
            data['submission_url'] = reverse('files', args=[submission.slug])
            
            #process files if uploaded via html
            upload_html(request, form.instance)
            
        #if no request.POST, throw error        
        else:
            raise ValidationError('No Post or Post type.')
        
    except StopUpload:
        data['error'] = True
        data['messages'] = ['The file you uploaded exceeds the allowed limit!']

    except IOError:
        data['error'] = True
        data['messages'] = [
            'Your file upload has timed out.'
            '  This might be due to problems with your flash player.'
            'Please try your upload using the' 
            '<a href="%s">No Flash</a> version.' % reverse('noflash')
        ]

    except ValidationError, e:
        data['error'] = True
        data['messages'] = e.messages
示例#23
0
def process_submission(request):
    """
    Processes the submission and returns back to the browser.
        
    :Return: HttpResponse
    """

    data = {
        'error': False,
    }

    submission = None
    email_form = None

    try:
        #force the request to be ajax.
        request.META['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"

        if request.method == 'POST' and request.POST.has_key('type'):

            #if submission is of type email, process the email form
            if 'email' in request.POST['type']:
                form, email_form = SubmissionForm(request.POST), EmailForm(
                    request.POST)

            #else if submission is of type link, process the submission form
            elif 'link' in request.POST['type']:
                form = SubmissionForm(request.POST)

            else:
                raise ValidationError('Incorrect Post type.')

            form.instance.submit_ip = request.META['REMOTE_ADDR']
            form.instance.browser_meta = "%s  %s" % (
                request.META['HTTP_USER_AGENT'], request.POST['flash_meta'])

            if form.is_valid():
                #save form
                form.save()
                #save email form
                if email_form:
                    #set the pk from the submission
                    email_form.instance.submission = form.instance
                    if email_form.is_valid():
                        email_form.save()
                    else:
                        raise ValidationError(email_form.errors)
            else:
                raise ValidationError(form.errors)

            submission = form.instance
            data['submission_slug'] = submission.slug
            data['submission_url'] = reverse('files', args=[submission.slug])

            #process files if uploaded via html
            upload_html(request, form.instance)

        #if no request.POST, throw error
        else:
            raise ValidationError('No Post or Post type.')

    except StopUpload:
        data['error'] = True
        data['messages'] = ['The file you uploaded exceeds the allowed limit!']

    except IOError:
        data['error'] = True
        data['messages'] = [
            'Your file upload has timed out.'
            '  This might be due to problems with your flash player.'
            'Please try your upload using the'
            '<a href="%s">No Flash</a> version.' % reverse('noflash')
        ]

    except ValidationError, e:
        data['error'] = True
        data['messages'] = e.messages