Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Created February 5, 2013 07:07
Show Gist options
  • Save yeukhon/4712776 to your computer and use it in GitHub Desktop.
Save yeukhon/4712776 to your computer and use it in GitHub Desktop.
function response_ok(x) {
return x >= 200 && x < 300;
};
function getUsername()
{
var username = doLMSGetValue( "cmi.core.student_id");
console.log(username);
console.log(doLMSGetValue( "cmi.core.student_name"));
return username;
};
function printToSTD(text)
{
console.dir(text);
console.log(text);
return text.replace(/(\r\n|\n|\r)/gm, "<br>");
}
function format_score_table(data)
{
$("#SCORETABLE").html("");
$("#SCORETABLE").append("<table><tbody></tbody></table>");
for (i=0;i<data.length;i++){
row = data[i];
if (row.score != row.full_score ){
$("#SCORETABLE > table > tbody").append(
"<tr class=\"failrow\"></tr>");
} else {
$("#SCORETABLE > table > tbody").append(
"<tr class=\"successrow\"></tr>");
};
if(row.name != "Total Score"){
$("#SCORETABLE > table > tbody > tr").filter(":last").append(
"<td> Test "+i+"</td>"+
"<td> "+row.message+" </td>"+
"<td> "+row.name+" </td>" +
"<td> "+row.description+" </td>" +
"<td> <pre> " + row.error_text+" </pre> </td>");
} else {
$("#SCORETABLE > table > tbody > tr").filter(":last").append(
"<td></td><td></td><td>"+ row.name+ "</td><td></td><td></td>");
}
$("#SCORETABLE > table > tbody > tr").filter(":last").append(
"<td> "+ row.score+ " out of "+ row.full_score + "</td>");
};
};
function format_file_table(data){
$("#gallery").html("");
var html_str = "";
for (i=0;i<data.length;i++){
console.log('looping');
console.log(data[i]);
//var remain = data[i].file_loc.substr(data[i].file_loc.substr(10).indexOf("/") + 11);
//var file_loc = 'https://' + remain;
/* e.g. https://192.168.1.198/aurum/.../
url is the full url
path contains "/aurum"
hostname comes from config.js
``path`` is extracted by learning that / have to occur multiple times,
and ``path`` is the first / occurs after the first dot.
method ``substr`` finds the first occurence of the first input parameter,
starting the search at position given by the optional second parameter.
*/
var url = data[i].file_loc;
var path = url.substr(url.indexOf("/", url.indexOf(".")))
var file_loc = hostname + path;
//var file_loc = data[i].file_loc.replace('http', 'https');
html_str += "<img src=\""+file_loc+"\"";
html_str += "alt=\""+data[i].orig_name+"\"/>";
};
$("#gallery").append(html_str);
$("#gallery").galleria({
width:500,
height:500});
}
var totalScore = 0;
var rawScore = 0;
var actualScore = 0;
var question0;
var question1;
var key0 = 0;
var key1 = 0;
var score_data = null;
function initialize_problem_cmi(num,prob_id){
doLMSSetValue("cmi.interactions."+num+".id",prob_id);
doLMSSetValue("cmi.interactions."+num+".type","numeric");
doLMSSetValue("cmi.interactions."+num+".correct_responses.0.pattern", "0");
};
function calcRawScore(data){
var totalS = 0;
var rawS = 0;
var actualS = 0;
var score_d = null;
for (i=0;i<data.length;i++) {
row = data[i];
prob_id = "key"+i+"b8";
initialize_problem_cmi(i,prob_id);
doLMSSetValue("cmi.interactions."+i+".student_response",row.score+"");
if (row.score == row.full_score) {
doLMSSetValue("cmi.interactions."+i+".result","correct");
} else {
doLMSSetValue("cmi.interactions."+i+".result","wrong");
}
rawS=rawS+row.score;
totalS=totalS+row.full_score;
};
return [rawS,totalS];
};
function calcScore2(data, finished)
{
computeTime(); // the student has stopped here.
result = calcRawScore(data);
var totalS = 0;
var rawS = 0;
var actualS = 0;
var score_d = null;
rawS = result[0];
totalS = result[1];
actualS = Math.round((rawS / totalS) * 100); // normalize to 100%
//doLMSSetValue("cmi.core.score.max", maxScore.toString());
doLMSSetValue( "cmi.core.score.raw", actualS.toString() );
if ( rawS < min_passing_score )
{
doLMSSetValue( "cmi.core.lesson_status", "failed" );
doLMSSetValue( "cmi.core.exit", "suspend" );
}
else
{
doLMSSetValue( "cmi.core.lesson_status", "passed" );
doLMSSetValue( "cmi.core.exit", "logout" );
}
exitPageStatus = true;
doLMSCommit();
if (finished == true) {
doLMSFinish();
}
};
function get_user_previous_soln(student_id, problem_id, shared_key)
{ console.log('get user previous code.');
xhr.request({
url: ["/aurum/solution", student_id, problem_id, shared_key].join("/"),
method: "GET",
data: {}
}, function(response) {
myCodeMirror.setValue(jQuery.parseJSON(response.data).code);
myCodeMirror.setOption("readOnly",false);
$("#RunButton").removeAttr("disabled");
}, function(response) {
myCodeMirror.setValue("");
myCodeMirror.setOption("readOnly",false);
$("#RunButton").removeAttr("disabled");
ajaxLoader('error');
});
};
function loadResult(data, flag, finished)
{
score_data = data;
console.dir(data.stdout);
console.dir(data.stderr);
$("#STDOUT").html("<pre>"+printToSTD(data.stdout.test_stdout)+"</pre>");
$("#STDERR").html("<pre>"+printToSTD(data.stdout.test_stderr)+"</pre>");
if(data.file_table.length>0){
console.log('here inside calling file table.');
format_file_table(data.file_table);
};
if(data.score_table.length>0){
format_score_table(data.score_table);
$("#SubmitGrade").removeAttr("disabled");
};
$('table').css('border','3px');
$('.successrow > td').css('background-color','#CCFF99');
$('.failrow > td').css('background-color','#FFCCFF');
if (score_data === null || flag == false){
console.log('nothing...');
} else if (flag == true) {
calcScore2(score_data.score_table, finished);
};
};
function get_user_previous_result(student_id, problem_id, shared_key)
{
console.log('get user previous result');
console.log(access_code);
xhr.request({
url: ["/aurum/result", student_id, problem_id].join("/"),
method: "GET",
data: {}
}, function(response) {
loadResult(jQuery.parseJSON(response.data), false);
}, function(response) {
console.log("failed to get previous result");
ajaxLoader('error');
});
};
function reqErrorHandler(jqXHR, textStatus, errorThrown){
console.log('Request was aborted.')
console.log(jqXHR.responseText);
$('#STDERR').html(jqXHR.responseText);
}
function clearBoard(shared_key){
$("#SCORETABLE").html("");
$("#STDOUT").html("");
$("#STDERR").html("");
$("#gallery").html("");
// now fire off PUT solution code
ajaxLoader('on');
putLatestSolnCode(shared_key);
};
function ajaxLoader(x){
if (x == 'on') {
$("#ajaxloader").show();
$("#ajaxloader").html('<center><img src="css/loader.gif" /> <br/> <p>Running....</p></center>');
$("#RunButton").attr("disabled", "disabled");
$("#SubmitGrade").attr("disabled", "disabled");
} else if (x == 'off') {
$("#ajaxloader").html('');
$("#ajaxloader").hide();
$("#RunButton").removeAttr("disabled");
$("#SubmitGrade").removeAttr("disabled");
} else if (x == 'error') {
$("#ajaxloader").html('');
$("#ajaxloader").hide();
$("#RunButton").removeAttr("disabled");
}
};
function putLatestSolnCode(shared_key){
student_id = getUsername();
xhr.request({
url: ["/aurum/solution", student_id, problem_id, shared_key].join("/"),
method: "POST",
data: { src_code: myCodeMirror.getValue() }
}, function(response) {
postCreateResult(response, shared_key);
}, function(response) {
console.log("Error putting code");
console.log(xhr.request);
console.log(response.json);
ajaxLoader('error');
$("#STDERR").html('<p><span style="color:red">We tried saving your code, but something has gone wrong. Try again. If not, contact support.</span></p><br/>');
});
};
function getGenerateResult(shared_key){
xhr.request({
url: ["/aurum/report", shared_key].join("/"),
method: "GET",
data: {}
}, function(response) {
status = response.status;
json = jQuery.parseJSON(response.data);
if ( response_ok(status) ) {
loadResult(json.report, true, false);
ajaxLoader('off');
} else {
console.log("response is not 2xx");
console.log(json);
console.log(status);
ajaxLoader('error');
$("#STDERR").html('<p><span style="color:red">Unable to get back your result. Try again. If not, contact support.</span></p><br/>');
}
}, function(response) {
console.log("So close..");
console.log(response.json);
ajaxLoader('error');
$("#STDERR").html('<p><span style="color:red">We tried getting result back, but something has gone wrong. Try again. If not, contact support.</span></p><br/>');
});
};
function pollForRunStatus(shared_key){
xhr.request({
url: ["/aurum/status/run", shared_key].join("/"),
method: "GET",
data: {}
}, function(response) {
status = response.status;
json = jQuery.parseJSON(response.data);
if ( response_ok(status) ) {
if (json.status == 'Complete') {
getGenerateResult(shared_key);
} else if (json.status == 'Running') {
setTimeout(function(){pollForRunStatus(shared_key);}, 5000);
} else {
$("#STDERR").html(printToSTD(json.error.stderr));
$("#STDOUT").html(printToSTD(json.error.stdout));
ajaxLoader('error');
}
} else {
$("#STDERR").html('<p><span style="color:red">Timeout</span></p><br/>');
console.log("response is not 2xx")
ajaxLoader('error');
}
}, function(response) {
console.log("EegaD");
console.log(response.json);
ajaxLoader('error');
$("#STDERR").html('<p><span style="color:red">We tried running the code, but something has gone wrong. Try again. If not, contact support.</span></p><br/>');
});
};
function pollForBuildStatus(shared_key){
xhr.request({
url: ["/aurum/status/build", shared_key].join("/"),
method: "GET",
data: {}
}, function(response) {
status = response.status;
json = jQuery.parseJSON(response.data);
if ( response_ok(status) ) {
if (json.status == 'Complete') {
pollForRunStatus(shared_key);
} else if (json.status == 'Running') {
setTimeout(function(){pollForBuildStatus(shared_key);}, 3000);
} else if (json.status == 'Error') {
$("#STDERR").html('<p><span style="color:red"><strong>Compile Error</strong></span></p><br/>' + printToSTD(json.error.stderr));
$("#STDOUT").html(printToSTD(json.error.stdout));
console.log("build stderr");
console.log(json.error.stderr);
ajaxLoader('error');
}
} else {
$("#STDERR").html('<p><span style="color:red">Timeout</span></p><br/>');
console.log("response is not 2xx")
ajaxLoader('error');
}
}, function(response) {
console.log("Error!");
console.log(response.json);
console.log(response.status);
ajaxLoader('error');
$("#STDERR").html('<p><span style="color:red">We tried building your solution, but something has gone wrong. Try again. If not, contact support.</span></p><br/>');
});
};
function postCreateResult(data, shared_key){
xhr.request({
url: ["/aurum/result", student_id, problem_id, shared_key].join("/"),
method: "POST",
data: {}
}, function(response) {
status = response.status;
if ( response_ok(status) ) {
pollForBuildStatus(shared_key);
} else {
console.log("response is not 2xx")
ajaxLoader('error');
$('#STDERR').html('<p><span style="color:red">Cannot create a result.</span> Try again. If not, contact support.</p>');
}
}, function(response) {
console.log("Build error!");
console.log(response);
ajaxLoader('error');
$('#STDERR').html('<p><span style="color:red">We tried creating solution, but something has gone wrong. Try again. If not, contact support.</span></p>');
});
};
var ajax_msg = ""
var xhr = new easyXDM.Rpc({ remote: url }, { remote: { request: {} } });
var ged_main = function (host, problem_id, shared_key) {
//ajaxLoader('off');
console.log("Initializing");
if (LMSIsInitialized() === true)
{
student_id = getUsername(); // student_id is student_name
// invoke two ajax calls asyncly
get_user_previous_soln(student_id, problem_id, shared_key);
get_user_previous_result(student_id, problem_id, shared_key);
//doLMSSetValue("cmi.core.lesson_status", "incomplete");
//doLMSCommit();
$("#RunButton").click(function (){
clearBoard(shared_key);
});
$("#SubmitGrade").click(function () {
if (score_data===null){
alert("You need to run the tests first.");
} else {
calcScore2(score_data.score_table, true);
myCodeMirror.setOption("readOnly","nocursor");
$("#RunButton").remove();
$("#SubmitGrade").remove();
}
});
} else {
setTimeout(function() {ged_main(url, problem_id, shared_key);}, 50);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment