Copying Arrays (and Objects) in Javascript

This is a bit of an amateur mistake, but I definitely wasn’t the first person to make it and I suspect I won’t be the last. I had a JavaScript array that I wanted to copy, then make some change to the copy, so that I could access the original and the modified copy. Therefore, being used to PHP, I did the following, assuming it would make a ‘proper’ copy of the original:

var original = [1,2,3];  //Define original array
var copy = original;     //Attempt to copy original
copy[2] = 4;             //Modify the copy
alert(original[2]);      //Hoped for 3, got 4

I’d created a reference to the original array, rather than a copy of it. As a result, updating the copy also updated the original.

So, how do I create a copy of an array, rather than a reference. Thankfully, the slice method makes this very easy:

var original = [1,2,3];        //Define original array
var copy = original.slice(0);  //Copy original using slice
copy[2] = 4;                   //Modify the copy
alert(original[2]);            //Got 3 this time

This works fine for simple, one-dimensional arrays, where the array contains only booleans, numbers or strings. If the array is multi-dimensional, i.e. it contains other arrays or objects, then only the top level array will be copied, the arrays/objects it contains will be referenced. Therefore, it is necessary to create a function to do this – this seems to be a good way to do: http://my.opera.com/GreyWyvern/blog/show.dml/1725165

Alternatively, use jQuery, and take advantage of the extend method:

var original = {team:"Arsenal"};               //Define original object
var copy = jQuery.extend(true, {}, original);  //Copy original using extend
copy.team = "Man Utd" ;                        //Modify the copy
alert(original.team);                          //Alerts Arsenal

The Basics of writing a Basic LTI Tool Provider

I hope this will be helpful for anyone just getting started with (Basic) LTI and wanting to create their first Tool Provider. Apologies for any abuse/misuse of the terminology – this is just how I understand it. To recap the two halves of an LTI launch:

Tool Consumer (TC) = An LTI-enabled VLE/LMS/other system that can make an LTI launch request. Generally (or at least the way we are using it), the TC manages user accounts/passwords, so that the Tool Provider doesn’t have to.
Tool Provider (TP) = an external tool that receives an LTI request from a TC and uses the launch data to work out what the user is able to see/do within the tool.

Useful links

I found the following useful when getting to grips with LTI and creating my first TP (in PHP):

Thanks of course to Dr Chuck and the rest of the LTI community for developing this specification and the above Classes, Tools and Tutorials.

Basic Implementation

The PHP Basic LTI class makes it very easy to do the LTI/OAuth bit of the TP. Here’s my pseudo-PHP code for the basic process:

//All of the LTI Launch data gets passed through in $_REQUEST
if(isset($_REQUEST['lti_message_type'])) {    //Is this an LTI Request?

    //We store oauth_consumer_key and secret pairs in our database, so we look the secret up here, but it can just be hard-coded (especially for testing)
    $secret = [secret];

    //Get BLTI class to do all the hard work (more explanation of these below)
    // - first parameter is the secret, which is required
    // - second parameter (defaults to true) tells BLTI whether to store the launch data is stored in the session ($_SESSION['_basic_lti_context'])
    // - third parameter (defaults to true) tells BLTI whether to redirect the user after successful validation
    $context = new BLTI($secret, true, false);

    //Deal with results from BLTI class 
    if($context->complete) exit(); //True if redirect was done by BLTI class
    if($context->valid) { //True if LTI request was verified
     //Let the user in
    }
}
else { //Not an LTI request, so either don't let this user in, or provide another way for them to authenticate, or show them only public content
}

Just to further explain the parameters passed when instantiating the BLTI class, the first argument is the secret, which is required and would usually be a string. Alternatively, you can pass through an associative array of database information (e.g. ‘table’ => ‘lti_keys’, ‘key_column’ => ‘oauth_consumer_key’), and the BLTI class will look up the secret from the database.

The second argument (true by default) tells the BLTI class whether to store the launch data in the session (from which it can be retrieved using $_SESSION[‘_basic_lti_context’]) and whether to try to automatically retrieve any stored LTI launch data if someone tries to access a tool without coming in through LTI. This means that if a user has initially come to a tool through LTI, then closes the browser tab containing the tool, and then goes directly back to the tool, without coming through LTI, as long as their session has not expired they will be allowed back into the tool, even though have not come through LTI. I would generally recommend keeping this as true, as I think this would usually be useful behaviour.

The third argument (true by default, but I generally set it to false) tells the BLTI class whether to do the redirect or not after validation of the request. Setting this to false will prevent it from doing the redirect.

I hope this is helpful. My understanding is pretty (cheap pun alert!) basic, so I would welcome any thoughts, queries, suggestions or corrections.

For further information/discussion of LTI, and how we have used it to allow access to our iCases system through WebLearn (our VLE), please see these posts:

Resetting the root password/privileges for MySQL/PHPMyAdmin (XAMPP 1.7.3, MySQL 5.1.41)

We use XAMPP for our local development (on Windows), and I have a habit of messing around with the database and doing bad things by mistake, because it’s only for local development, so it doesn’t matter that much. It’s still annoying when I lock myself out of all my databases though!

While setting up a wordpress site locally for testing, I managed to remove the global privileges of the root user in PHPMyAdmin, thinking it was the user for the wordpress database. I did the usual thing of searching for solutions online, and after trying a few different things involving the command line and MySQL Workbench, I came across this Apache Friends forum thread: http://www.apachefriends.org/f/viewtopic.php?f=16&t=46832. The instructions boil down to the following:

  • Open mysql/resetroot.bat in a text editor
  • Add “–datadir=c:/xampp/mysql/data” into the “mysql\bin\mysqld.exe…” line (line 18), after “–no-defaults”. Change the datadir parameter to the path to your data directory – the one shown is the default.
  • Run resetroot.bat – this should reset the MySQL root password and privileges. You can then login to MySQL/PHPMyAdmin using the username root and no password. For security, you should set a password for the MySQL admin user in the XAMPP Security panel: http://localhost/security/

CakePHP Session data being lost on redirect

Having successfully enabled access using LTI to a local version of iCases – see https://learntech.medsci.ox.ac.uk/wordpress-blog/?p=229 – I got it set up on a live server, assuming that it would work without any trouble. However, I was unable to login successfully through WebLearn, which is our Tool Consumer.

It turned out that this was due to the session data being lost when redirecting from the login page within the CakePHP app to the scenario page. Authentication using LTI relies on session data, as the LTI context information is saved to the session. Therefore, when the session data was lost, the app could no longer tell that the user had accessed it through a valid LTI request, and so the user was denied access.

I fixed this by changing Security.level in core.php to ‘low’ (it had previously been medium). From the CakePHP docs, this increases the multiplier for the ‘Session.timeout’ value (from 100 to 300) and disables (or, to be pedantic, does not enable) PHP’s session.referer_check. It seems to be the latter that was the problem. However, in the php.ini file we have ‘session.referer_check = ‘, which should mean that session.referer_check is not enabled anyway. So I am not sure why changing the security level had an effect, unless setting the Security.level to medium enables session.referer_check, even if it was not already enabled.

As far as I can tell from reading around, disabling session.referer_check should not cause any problems, as it is only possible to access the LTI-ed iCases through WebLearn. Checking that the LTI launch is valid includes checking that the launch request has come from a valid location.

Shock News (to me anyway): Windows Command Line is actually useful

Having used Windows since my earliest memories, I’ve only rarely used the command line. I never found it that useful and was always annoyed by the fact that I couldn’t click somewhere in my command to edit it, and instead had to use the arrow keys to move it forwards and backwards.

However, I’ve recently had to carry out quite a few batch tasks in Windows and have, to my surprise, found the command line to be pretty useful. So, as much to remind myself as anything, I thought I would note down the things that have helped me.

Changing File Extensions

This is easy using the REN command, e.g. REN *.svs *.tif

FOR Loops

As you would expect, this loops over a set of files/directories and carries out a command on each. The basic structure of a FOR command is as follows:

FOR %V IN (set) DO command [command-parameters]

The %V is a variable (it does not have to be ‘v’, but must be a single letter, and it is case sensitive, i.e. %v and %V are different) that can be used in the command parameters to refer to each of the files matched by set. As a spurious example, to echo all of the files in the current working directory, you would give the following command:

FOR %V IN (*) DO echo %V

Variable Modifiers

Variable modifiers can be used to output the variable in a variety of ways, e.g. for %V above:

  • %~fV outputs the full path name for the file
  • %~nV outputs the file name only
  • %~xV outputs the file extension

There are others apart from those mentioned above – see the FOR command help for more.

FOR /D

If the /D extension is used, the FOR command will match  directories rather than files.

For example, to separately zip up all of the subdirectories in the current working directory

FOR /D %D IN (*) DO C:\zip\zip.exe -r "%~fD.zip" "%~fD"

Using FOR in batch files

If you are using a FOR command in a batch file, it is necessary to use, for example, %%V, rather than %V for the variables.

START /WAIT

I was using the START command in a batch file to carry out a certain command on multiple files, but I needed it to wait until one command had finished executing before it called the next. Thankfully there is the /WAIT parameter, which means that the next command will not be called until the previous one has finished.

Phonegap for Android JSCallback error meaning OnDeviceReady not called

Struggled for hours last night while trying to migrate this great example app Sample App using the PhoneGap Database API to work on Android using Eclipse and an Android emulator. Everything was going well until I tried to link to a second page using a query string parameter to pass through the id of the the employee. This resulted in:

JSCallback Error: Request failed. at file:///android_asset/www/js/cordova.js:3698

Eventually stumbled across PhoneGap – migrating iOS applications to Android (Part 1) which pointed out that this is a documented Android issue and proposed the following workaround:

function loadEmployeeDetail(id) {
localStorage.setItem( “employeeId”, id );
navigator.app.loadUrl(“file:///android_asset/www/employeedirectory/employeedetails.html”);
}

And then reading this  in employeedetails.html using:

id = localStorage.getItem( “employeeId”);

However, I was still having problems calling OnDeviceReady() until I stumbled across deviceReady not working in PhoneGap application, how to? which suggested that adding brackets into the function name in the eventListener method might be the problem, giving:

 document.addEventListener(“deviceready”, onDeviceReady(), false);

Problem solved.

 

 

Preventing IE from caching Ajax requests

We are increasingly using AJAX (Asynchronous JavaScript and XML) to deliver content on our pages, but often have problems due to Internet Explorer, every web developers favourite browser, caching AJAX requests. This means that the results presented are not updated when a new request is made to the same URL, even if the data has changed.

This is annoying, but does not go against the HTTP specification, which states that GET requests are cacheable, whereas POST results are not. AJAX requests seem to generally default to GET (JQuery certainly does), so IE caches them.

Therefore, the solution is to make sure that AJAX requests use POST rather than GET. In jQuery, you can do this by setting:

type: 'POST'

For Prototype, you can set:

method: 'get'

In the jQuery.ajax() method, there is also a ‘cache’ setting, which is true by default, but can be set to false, which prevents caching. It does this by appending a TIMESTAMP to the URL, so that each request is made to a different URL, so a cached result cannot be returned. If not using jQuery, an alternative to ensuring that your request is a POST request rather a GET request is to add a ‘cache-busting’ parameter, e.g. a timestamp, to the end of the request URL, e.g.:

var cacheBuster = new Date().getTime();  //Get timestamp
var url  = 'http://www.example.com/getdata?cb=' + cacheBuster;  //Add timestamp to URL

Excel ‘helpfully’ converting numbers longer than 15 digits to scientific notation when importing from .csv

When you attempt to open or import .csv data into Excel, long numbers are helpfully converted into scientific notation. In most situations, this is fine – it make it easier to see the number in a cell and the original number can be seen in full if the cell number format is changed.

However, when numbers are longer than 15 digits, Excel silently rounds anything after the 15th digit – a real problem with GUIDs in general and QuestionMark Perception Question IDs in particular.

There are a number of potential solutions to this, any of which may work for you:

  1. Change the file’s .csv extension to .txt or  choose Data | Get External Data | From Text to bring up the Text Import Wizard and, in Step 3 of 3 where you set the data format, select the appropriate column (or columns with Shift held down), set the Column data format to Text. However, this appears to fail with very high numbers of columns (in this case >200), leading me to solution 2:
  2. Upload the .csv file into Google Docs, making sure that Convert documents, presentations, spreadsheets, and drawings to the corresponding Google Docs format is ticked. Then export as Excel by File | Download As | Microsoft Excel. Thanks to kpm for this. However, this still seems to randomly covert a few GUIDs into 15 significant figure sceintific numbers.
  3. The solution which worked for me was to open the .csv file in OpenOffice 3 Calc and, as with Excel, in the Text Import dialogue, select all the  columns in the Fields section and then change their Column type to Text. Unlike Excel, this did reliably import all >200 columns without converting any GUIDs.

 

 

Getting excited by maths handling in MathAssessEngine

Just been trying out some sample QTIv2.1 questions sent to me by Dr Sue Milne from ELandWeb Ltd which address some issues with maths in online assessment that we have been struggling with for some time:

  • How do we allow students to choose the units in which they answer a numeric question?
  • How do we allow students to answer an algebraic question with an algebraic answer?
  • How can we randomise the values presented whilst testing the same mathematical concept from student to student and from attempt to attempt (to allow students to retest themselves)?
The answer appears to be that what we need is MathAssessEngine from the University of Edinburgh and QTIv2.1 .
Answering questions with algebra
Answering a question with algebra in MathAssessEngine
We haven’t yet had time to look at this is any great detail but these two examples demonstrate that there is a whole new world of assessments out there waiting to be explored.
qtiv21_examples contains two examples:
Example 1  (SineRule-002-mathOpWithSol.xml): Demonstrates a question that ‘understands’ units and the impact they will have on the expected answer
Example 2 (mela012252.xml): Demonstrates answering a question with algebra – in this case ‘sqrt’.  As the participant types, the answer the computer will mark is displayed in MathML.
Both questions randomise the variables shown each time you retake the question. To give them a go yourself, unzip the file then visit MathAssessEngine. ‘Choose file’ under ‘Upload Assessment Items and Tests’ and click ‘Go’.