I would like to Create a Mechanical Turk Hit by using the MTurK Package in R.
The R code I am using is the following:
filecontent <- GenerateHTMLQuestion(file="file.html")
print(filecontent)
#filestring <- filecontent [["string"]]
#filestring <- filecontent [["xml.parsed"]]
#filestring <- filecontent [["url.encoded"]]
filecontentForQuestion <- filecontent$string
filecontentForQuestion <- filecontent$xml
filecontentForQuestion <- filecontent$url
print(filecontentForQuestion)
testhit<-CreateHIT(question=filecontentForQuestion,
title="Title",
description="Description",
keywords="Keyword",
reward="0.05",
assignments="3",
duration="3600",
expiration="20000",
auto.approval.delay="2590000",
qual.req=GenerateQualificationRequirement("Approved",">","5"),
browser = F,
sandbox=T)
I have tried every different filecontent, but I always get an error when I use this command. Unfortunately, I always get the following error:
Error (AWS.MechanicalTurk.HTML5ParseError): There was an error parsing the
HTML5 data in your request. Please make sure the data is
well-formed and validates as HTML5
However, the html file I am using is the one from the MTurk API Manual and is the following:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/ex
ternalHIT_v1.js'></script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='ht
tps://www.mturk.com/mturk/externalSubmit'>
<input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<h1>What's up?</h1>
<p><textarea name='comment' cols='80' rows='3'></textarea></p>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body>
</html>
I get the same error if I use a complete empty html5 doc with only the necessary placeholders. Has anyone an idea, why this does not work?
Using the hitlayoutid parameters or ExternalQuestion commands work, so I would like to explicitly use the GenerateHTMLQuestion command.
Related
to demonstrate what im trying to do using a simple example:
<html>
<head>
<base target="_top">
</head>
<body>
<form id="uploaderForm" action="https://script.google.com/macros/.......exec Method="POST">
<input type="text" name="applicantName" id="applicantName">
<input type="text" name="applicantEmail" id="applicantEmail">
<input type="button" value="Submit">
</form>
<script>
.
.
.
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
</script>
so this is an example of the html and js page that is in my pc, not in the google app, i just called the google app in the form, and in the javascript part im calling a function called uploadFile, which is located in the google script, but obviously i get an error in the console , it says :
Uncaught ReferenceError: google is not defined
at uploadFiles (6166bff606ac6fee1994e592:67)
at HTMLInputElement.onclick
is it possible to call a GAS function inside JS that is not in the GAS html.
is what im trying to do even possible, the whoel reason im doing this is so that i can pass the username and email automatically from the database to the app, the app works if the html part is hosted in the google app script, but then i cant figure out how to pass the email and username to it because in this case i call the app using , so is it possible to pass the username and email through the iframe call, i dunno im very new to this i have so many questions, honestly the documentation wasn't helpful to me. please feel free to comment anything, everythign is helpful
Since you're just posting the form data, you can name the function you want to call as doPost()(instead of uploadFile) and it will receive the posted data. You have to republish the webapp as a new version after the modification.
I just ran it as a dialog. I returned the data back into the success handler and loaded by into the html to insure it was working.
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<body>
<form>
<input type="text" name="applicantName" id="applicantName"/>
<input type="text" name="applicantEmail" id="applicantEmail"/>
<input type="button" value="Submit" onclick="uploadfile(this.parentNode);" />
</form>
<div id="msg"></div>
<script>
function uploadfile(form) {
google.script.run
.withSuccessHandler((m) => document.getElementById("msg").innerHTML = m)
.uploadMyFile(form);
}
</script>
</body>
</html>
gs:
function uploadMyFile(obj) {
return `Applicant Name: ${obj.applicantName}<br />Applicant Email: ${obj.applicantEmail}`;
}
function launchFormDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah2'),'Test Dialog');
}
Dialog:
I am trying to create a form and getting the data entered by user into my script using python-cgi but I am getting this error message "End of script output before headers: processname.cgi". I have followed various blogs and tutorials but couldn't make it work.
Here is my form and cgi script. I am using python3 and xampp server on my local machine(MAC OSX)
form.html
<DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Get name from User</title>
</head>
<body>
<form method="post" action="processname.cgi">
Please Enter Your name: <input type="text" name="username" placeholder="e.g. John" autofocus
required="required"/>
<br>
<input type="submit" name="submitname" value="Submit"/>
</form>
</body>
</html>
And this is my cgi-script: processname.cgi
#!/usr/local/bin/python3
import cgi
import cgitb
cgitb.enable()
def htmlTop():
print('''Content-type:text/html\n\n
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My Server Side template</title>
</head>
<body>''')
def htmlTail():
print('''</body>
</html>''')
def getData():
formData = cgi.FieldStorage()
firstname = formData.getvalue("username")
return firstname
if __name__ == '__main__':
try:
htmlTop()
firstname = getData()
print("Hello {0}".format(firstname))
htmlTail()
except:
cgi.print_exception()
I figured it out.You have to make your script executable and then restart the server.
chmod 705 .../folders/scriptname.cgi
will make the script executable.
I am new to JSON. I ran the code below and got an error
import urllib2
import json
urllib2.urlopen('https://ciapipreprod.cityindextest9.co.uk/TradingApi')
print json.load(urllib2.open(`https://ciapipreprod.cityindextest9.co.uk/TradingApi'))
ValueError: No JSON object could be decoded
But when I ran it without json as below, I could see what was inside.
import urllib2
data=urllib2.urlopen('https://ciapipreprod.cityindextest9.co.uk/TradingApi')
html = data.read()
print html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Ajax Test Harness</title>
<link href="/TradingAPI/Content/css?v=oI5uNwN5NWmYrn8EXEybCIbINNBbTM_DnIdXDUL5RwE1" rel="stylesheet" type="text/css" />
<link href="/TradingAPI/Content/themes/base/css?v=M29VGAPKJl__Ya5hV5ngguUfY8uNXwB076bG-JmFavY1" rel="stylesheet" type="text/css" />
<script src="/TradingAPI/Scripts/js?v=lYEohN8Pq3__VMPgz6C4ZXSyFUc0d6gVJQ28Wflqo3E1"></script>
</head>
<body>
<div style="width: 100%; margin: 0px;">
<img alt="CityIndex Logo" src="/TradingAPI/Images/ci_white_logo.jpg"/>
</div>
<h2>Ajax Test Harness</h2>
<script src="/TradingAPI/Scripts/tradingApi.js" language="javascript" type="text/javascript"></script>
<script src="/TradingAPI/Scripts/corsTest.js" language="javascript" type="text/javascript"></script>
<script src="/TradingAPI/Scripts/json2.js" language="javascript" type="text/javascript"></script>
<div id="apitest">
<form id="form1" runat="server"></form>
<hr />
<h2>Test Harness</h2>
<button onclick=" eval($('#code').val()); ">Execute</button><br />
<textarea id="code" cols="120" rows="15">
var userName = "DM631479";
doPost('/session',{ "UserName": userName, "Password": "password"}, function (data, textCode) {
// Smoke Test
doGet('/smoketest');
setRequestHeader("UserName", userName);
setRequestHeader("Session", data.Session);
// Authentication Test
doGet('/smoketest/authenticated');
// Account Information Tests
doGet('/useraccount/DM631479/ChartingEnabled');
doGet('/useraccount/ClientAndTradingAccount');
// Need Valid Test Data doPost('/useraccount/Save', {"PersonalEmailAddress":"not#realaddress.com","PersonalEmailAddressIsDirty":true})
// Cfd Markets Test
doGet('/cfd/markets?marketname=uk&maxresults=10&usemobileshortname=true');
//Logoff
doPost('/session/deleteSession?userName='+userName+'&session='+data.Session);
});
/* var userName = "DM631479";
cityindex.corsTesting.doPost('/session',{ "UserName": userName, "Password": "password"}, function (data, textCode) {
});*/
</textarea>
<br />
<select id="result" style="background-color: #e4e4e4; min-height: 300px;" multiple="multiple"></select>
<hr />
</div>
</body>
</html>
My understanding was that if there were '{}' within my var 'Data' they were "dictionaries" and I could then call them using the JSON module.
Perhaps I have misread the contents of my variable and maybe there actually isn't anything for JSON to 'load'
Sorry if any of the tagging here is wrong or ineligible.
Looks to me like that url returns html, and not json at all. Also, from the print statement, results it doesn't look like there is any json embedded in the page at all.
json.load will only work with input that looks exactly like json, something that looks like a dictionary. It won't pull this out of the surrounding html.
If there were json somewhere on that page, say, in a script tag, the you'd first have to parse the html to extract it. You could use beautiful soup or scrapy for that.
JSON has a particular specified shape which that response does not conform to. What you have there is JavaScript (and some JavaScript is valid JSON) embedded in HTML. It's similar to this example:
<pre><code>print("Hello World")</code></pre>
which contains Python code, but is not, in total, valid Python code. In order to extract the data you will need to find a different endpoint to hit that produces valid JSON (or else you will have to extract the JSON-like parts of the JavaScript on the page that you are interested in by using the html.parser built into the standard library, a library like bs4, or regular expressions). Then you can feed the valid JSON text to json.loads and work with it.
I keep on getting this error message when I go to open the upload page of my Grails application:
No signature of method: org.apache.catalina.core.ApplicationHttpRequest.getFile()
is applicable for argument types: (java.lang.String) values: [file]
Possible solutions: getXML(), getPart(java.lang.String), getAt(java.lang.String),
getAt(java.lang.String), getLocale(), getInfo()
Here's my html code :
<html>
<head>
<meta name="layout" content="main"/>
<title></title>
<style type="text/css">
label{
float:left;
width:65px;
}
</style>
</head>
<body>
<g:uploadForm action="upload">
<input type="file" name="file">
<g:submitButton name="upload" value="Upload"/>
</g:uploadForm>
</body>
</html>
And the corresponding controller class
package org.example.test
class AdminAccessController {
def upload() {
def f = request.getFile('file')
def allLines= f.inputStream.toCsvReader().readAll()
}
}
I've tried importing quite a ton of various libraries to fix the problem, but I haven't figured out what is going on. As you can probably tell, I will end up writing this file into a csv reader. I followed this document on the official Grails GitHub exactly: http://grails.github.io/grails-doc/latest/guide/theWebLayer.html#uploadingFiles, but nothing seems to be working.
Can anyone help me out?
Thanks.
The instance of the request arriving to your controller is an ApplicationHttpRequest which has no getFile method.
You need to change the type of your request to DefaultMultipartHttpServletRequest.
That can be done by changing the enctype in your uploadForm to multipart/form-data like this:
<g:uploadForm action="upload" enctype='multipart/form-data'>
<input type="file" name="file">
<g:submitButton name="upload" value="Upload"/>
</g:uploadForm>
Forgot about getFile(). You receive it how parameter with type MultiPartFile, so you can use its implementations:
params.file.getInputStream().toCsvReader().readAll()
I have two seperate perl documents:
mailcheck.pl
loggingpage.pl
Mailcheck prints out a form in html where the user can put in her/his email and checks if the input is a valid email address. Then it calls upon the loggingpage.pl which saves the email in a logfile and gives out information to the user if the email address was successfully stored.
These are the two documents:
mailcheck.pl:
#!/usr/bin/perl
use strict;
use warnings;
print "Content-type: text/html\n\n";
print <<HTML;
<html>
<head>
<title>Mailcheck</title>
</head>
<body>
<form name="ec" action ="./loggingfiles.pl" method="get">
Email: <input type="text" name="email"> <br>
<input type="button" value="Pruefen" onclick="javascript:emailcheck();">
</form>
<script language="javascript" type="text/javascript">
function emailcheck()
{
var emailoutline = /^[a-z0-9._%+-]+\#[a-z0-9.-]+\.[a-z]{2,4}\$\/\;
var x = document.ec.email.value;
if (emailoutline.test(x))
{
open("./loggingpage.pl);
}
else
{
alert("Dies ist keine richtige eMailadresse!");
}
}
</script>
</body>
</html>
HTML
exit;
loggingpage.pl:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standart);
#reads the input of the form called "email"
$emailinput = param('email');
#saves the email in the logfile
open(my $ml, ">", "./../logs/maillog.txt") or die "Fehlermeldung";
print $ml scalar(localtime()), " Email: ", $emailinput;
close($ml);
#gives out information about the saving process
if (...) #saving the email in the logfile succeeded
{
print <<HTML;
<html>
<head></head>
<body>
<script language="javascript" type="text/javascript">
alert("Your input has been saved under the following email: " + $emailinput);
</script>
</body>
</html>
HTML
exit;
}
else #gives out warning if information was not stored right
{
print <<HTML;
<html>
<head></head>
<body>
<script language="javascript" type="text/javascript">
alert("Error while saving your input.");
</script>
</body>
</html>
HTML
exit;
}
(I know that the <<HTML (..) HTML blocks cannot have spaces in front of them - in my actual document I have edited the block the right way)
My questions are now:
a. How can I write the if-conditions when I want to see if the email got saved in the logfile?
b. I am not quite sure if the part $emailinput = param('email'); works since I was not able to try it, is it the right way to get the input of the form in mailcheck.pl or do I need to write the code differently?
For you information:
- mailcheck.pl works correctly.
- the saving of the email in the logfile also works fine (i tried it through defining a variable as an email and saving that into the logfile together with the current date...)
So I have solved question a) like this (it seems to be working):
open(my $ml, ">", "./../logs/maillog.txt") or die "Saving Error";
print $ml scalar(localtime()), " Email: ", $emailinput;
close($ml);
#print "\nYour eMail was successfully logged!", $emailinput, "\n\n";
print "Content-type: text/html\n\n";
print <<HTML;
<html>
<head>
<title>Mailcheck2</title>
</head>
<body>
<p>Es wurde die folgende eMail erfolgreich gelogged:</p>
</body>
</html>
HTML
exit;
Now I only need help with question b).
After performing the validation, submit the form using:
document.ec.submit(); // 'ec' is the name of your form
This will send the form data to the page defined in the action attribute of your form.
Better yet, use the onsubmit attribute of the form tag to perform the validation:
<form name="ec" action ="./loggingfiles.pl" method="get" onsubmit="return emailcheck()">
Then modify the validation method to return false on failure:
function emailcheck()
{
var emailoutline = /^[a-z0-9._%+-]+\#[a-z0-9.-]+\.[a-z]{2,4}\$\/\;
var x = document.ec.email.value;
if (!emailoutline.test(x))
{
alert("Dies ist keine richtige eMailadresse!");
return false;
}
}
Do not rely on JavaScript in this way. JS is useful an additional sanity check for your form, but it should not be the only nor the primary means of validating your data.
Instead, put all your data into a single page, and for initial development, remove any JS. Make your form a POST request, and detect when the form is posted to determine if you need to do the validation. You'll need to use your JS validation regex in your perl instead, although eventually you should upgrade to Email::Valid.
After your form and post is working without JavaScript, you can add an onSubmit method if you want to do some clientside verification to duplicate what you've done in perl.