Skip to content


How to create global variables in Titanium

The first and obvious way to create a global variable is to initialize it straight from the root in app.js. The usual

var myGlobalVar1 = 'this';

when it is placed out of any brackets.
I actually saw a seemingly official sample application with a comment in app.js saying something along the lines “define your global variables here”. It seems like it should work great, and for me it did… until I implemented notifications using gcm.js.
For some reason, when a gcm.js notification is clicked to open the application, if the application wasn’t already running in the background it will crash because all global variables defined in app.js will be defined locally only (see for instance this post on Appcelerator Q&A). I’m not sure what happens, but my best bet is that somehow gcm.js or the functions it uses launch app.js as some king of local object, so whatever is defined in it in this context is local and not global as expected.

Anyway, so I needed a more reliable way to create a global variable.
A number of options are suggested in the following posts:

Some involve adding includes at the beginning of every file, and then I wonder how a modification from one view might modify the value in another one. The method I found the most convincing is to attach your wanted global variable to an already existing, guaranteed global variable, for instance Ti.App. Apparently this isn’t a “recommended” way, but it’s a natural feature of JavaScript so should be fairly future-proof.

So, instead of

var myGlobalVar1 = 'this';

we’ll now use

Ti.App.myGlobalVar1 = 'this';

and voilà. The only problem now is that you variable names are quite longer. Personally I even use

Ti.App.myappGlobal={};
Ti.App.myappGlobal.myGlobalVar1 = 'this';

so that if by any chance Titanium decides to rename Ti.App I won’t have any issue to automatically replace all “Ti.App.myappGlobal” with something else.

Update (2014-12-16): sadly, apparently this trick doesn’t work to create global functions on iOS… FFFS

Posted in programming.

Tagged with .


[R] Solving “unused arguments (length = 4, lambda = 0.5)” error in kernlab

I recently got this puzzling error from the kernlab package, in a script that used to work really nice before:

Error in laplacedot(length = 4, lambda = 0.5) : 
  unused arguments (length = 4, lambda = 0.5)

Switching method didn’t help, for instance with a radial basis kernel instead of the laplacian one:

Error in rbfdot(length = 4, lambda = 0.5) : 
  unused arguments (length = 4, lambda = 0.5)

Apparently someone asked that on Inside-R and Stackoverflow, but didn’t care to share their solution beyond “I figured out that it’s all because of the format xtrain and ytrain”.

Well I eventually figured that out too, it turns out xtrain must be a matrix, so the fix is as simple as changing this:
svm.kernlab.mdl = ksvm(Xtrain, as.factor(ytrain),kernel="laplacedot");
into this:
svm.kernlab.mdl = ksvm(as.matrix(Xtrain), as.factor(ytrain),kernel="laplacedot");
Of course, package maintainers could do the conversion themselves, or at least provide meaningful error messages…

I use this code in a classifier wrapper in R package mc-r, currently under development and accessible at Google Code and Bitbucket:
https://code.google.com/p/mc-r/
https://bitbucket.org/patheticcockroach/mc-r/src

Posted in R (R-project).


Comment bloquer les pubs sur OVS…

…et (surtout) comment contourner les protections antipub

(NB: exceptionally, this article is written in French because it’s targeted at a French, non-English speaking audience – sorry for the inconvenience)

Je comprends bien que la pub soit nécessaire au financement de certains sites (quoique, comme certains le soulignent à juste titre, “ce qu’elle nous fait économiser on le repaie trois ou quatre fois dans nos courses”), néanmoins certains sites abusent carrément. Du coup, de plus en plus de gens bloquent les pubs (si vous êtes là vous en faites probablement partie… à moins que vous ne soyez au contraire un vendeur de temps de cerveau disponible :p ). Et du coup, de plus en plus de sites ajoutent une détection d’anti-pub à des fins plus ou moins nobles allant d’un simple rappel “yo, tu bloques mes pubs mais si tu m’aimes ça serait cool de désactiver ton AdBlock juste pour moi” plus ou moins discret ou intrusif (j’en profite pour glisser le mien, mes régies pubs sont très non-intrusives et marchent au Bitcoin – voilà c’est fait ^^) à un bien moins sympa blocage complet du site, aka prise en otage.

OVS est un cas intéressant car d’une part ils cumulent les défauts (plein de pubs partout, de régies intrusives genre Google, et un blocage du site en cas d’antipub) et d’autre part ils modifient _très_ souvent leur protection anti-anti-pub (ce qui est d’autant plus amusant qu’en contraste le site ne bénéficie à peu prêt jamais de mises à jour dignes de ce nom), faisant de son contournement un mini-challenge régulièrement rafraîchi :)

Bref, trève de blabla, voici ma première méthode, qui marche contre la contre-mesure du jour: installez Ghostery et désactivez AdBlock pour OVS. Ghostery est une extension relativement proche d’AdBlock, sauf qu’au lieu de bloquer les pubs à partir d’expressions régulières, elle bloque les trackers à partir d’une liste noire qui ratisse très large. Après l’installation de Ghostery, n’oubliez pas bien sûr de le configurer pour bloquer lesdits trackers.
NB: pour les fans de libre, ça pourrait valoir le coup d’essayer avec Disconnect.me ou autre équivalent (si vous en connaissez, n’hésitez pas à les mentionner en commentaire)

Bon, c’est un peu court, je vous avouerai que j’avais créé un script Greasemonkey pour éviter de désactiver AdBlock mais que lors de mes tests ultimes avant la rédaction de ce post je me suis rendu compte que la solution Ghostery seul marche (ce n’était pas le cas hier, d’où la création du script Greasemonkey). Si certains préfèrent vraiment Greasemonkey, voici le script (lien de téléchargement direct):

// ==UserScript==
// @name        	OVS anti anti-pub
// @namespace   	OVS_anti_anti_pub
// @description 	Kill anti-adblocker on OVS
// @include     	http*://*.onvasortir.com/*
// @version     	1
// @encoding		UTF-8
// @grant       	none
// @author		PatheticCockroach - http://www.patheticcockroach.com
// @license		MIT License
// @url			http://notepad.patheticcockroach.com/4120
// @updateURL		http://img.patheticcockroach.com/01/gms/OVS_anti_anti-pub.user.js
// ==/UserScript==

var dummyAdDiv = document.createElement('div');
dummyAdDiv.id = 'my-smartadserver';
document.body.appendChild(dummyAdDiv);

Pour mémoire vu que ça change vite, le code anti-anti-pub du jour est:

$(window).load(function(){
if (!(document.getElementById("my-smartadserver")))
document.location='ovsadblock.php';});

Tout ce que fait le script, c’est recréer un élément d’identifiant “my-smartadserver”, qui est un élément supprimé par AdBlock, et sans doute simplement vidé par Ghostery. Voilà voilà, amusez-vous bien… jusqu’au prochain blocage, mais sans inquiétude car on trouvera bien autre chose ;)

À propos d’autres choses, quelques billets ou posts intéressants sur le même sujet:

Posted in privacy, programming.


[Titanium] How to detect window orientation (portrait vs landscape) at start-up

Titanium provides a simple way to detect window orientation, Titanium.UI.Window.orientation, but it seems to initialize late. In an application I’m developing, I needed to check the window orientation right at start-up, more specifically I used this:
if(Titanium.UI.Window.orientation==Titanium.UI.PORTRAIT) {stuff}
but this didn’t seem to work.

Running a simple
console.log(Titanium.UI.Window.orientation)
revealed that the variable sadly is undefined at that stage (TBH, I didn’t check if it was defined later since that’s not where I need it).

So I made a custom function, based on window size, which turns out to be defined early enough for me. Here is the function, quite obvious, really:
var isPortrait = function(){
return (Ti.Platform.displayCaps.platformHeight > Ti.Platform.displayCaps.platformWidth);
};

Then just call it with isPortrait() to get a boolean with value true if the window is oriented in portrait and false if it’s oriented in landscape.

Note that I only needed to make the difference between portrait and landscape, I don’t really have an idea to make the difference between properly oriented and upside-down portrait, or between left of right landscape, as the Titanium.UI.Window.orientation property offers (its possible values are: Titanium.UI.LANDSCAPE_LEFT, Titanium.UI.LANDSCAPE_RIGHT, Titanium.UI.PORTRAIT and Titanium.UI.UPSIDE_PORTRAIT)

Posted in programming.

Tagged with .


How to import a SAS database into R (without SAS)

Info on this was unusually hard to find, mostly because of all the noise generated by tutorials to convert data from SAS to R while using SAS in the process (apparently SAS doesn’t make it that trivial to export a simple CSV file). This makes for an interesting read though, so if you feel like getting an interesting headache, be my guest.

If you just want to import a SAS file into R, without the need to own a copy of SAS, luckily someone eventually made a package for this, more specifically sas7bdat, by Matt Shotwell.

Very simple to use, syntax is just:
myDataFrame=read.sas7bdat(theDamnSasFile);

A life-saver, even though it reportedly doesn’t work with all SAS files: it still works with most (and it worked with mine ^^). Last but not least, it doesn’t even have dependencies, and is quite tiny (321 kB). Tested today on R 3.1.2. Note that it’s quite much slower than reading a CSV file, so maybe you’ll want to import your SAS file, and then save it as CSV if you plan to read it often in the future.

Posted in R (R-project), statistics.


[Titanium] How to detect if an application is running in simulator

Testing for a virtual device can be useful for a variety of features not or poorly working in those, for instance push notifications (last time I tried it just seemed to block the execution) or the camera (as mentioned in this post, on a virtual device you could replace the camera with a “fake” one by loading a picture from the disk).

The Ti.Platform.model variable should contain all you need to determine whether or not you’re running on a real device. On the iOS simulator it will return “Simulator”, on an Android emulator it will return something like “google_sdk”. So a way to test for it would be simply:

if (Ti.Platform.model === 'Simulator'
 || Ti.Platform.model.indexOf('sdk') !== -1 ){
    alert('This is a virtual device');
}

(sorry for the poor indentation, WordPress makes it pretty tough :s)

Sources:
https://developer.appcelerator.com/question/63871/way-to-detect-running-in-simulator
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Platform-property-model

Posted in programming.

Tagged with .


SAS syntax highlighting in Notepad++

I don’t really use SAS much, and when I do most of the time it’s just to read a SAS script and convert some stuff from it into R. So Notepad++ is more than enough to do that (and cheaper, too ;)), but it doesn’t feature SAS syntax highlighting by default. However you can easily add it, all you need (unless you want to implement it yourself), is a user-defined language file. Gladly, some people worked on this and this post at hafniumcity provides such a UserDefineLang.xml file (and just in case it went offline, I mirrored it here).

To use it:
– if you already have a UserDefineLang.xml file, you’ll need to edit it (for instance with Notepad++) so as to add the new “sas” language definition in it, along your already defined languages
– if you don’t already have a UserDefineLang.xml file, you should place the new one either in %appadata%\Notepad++ or right in the Notepad++ folder, if like me you configured Notepad++ in a portable settings (use a local folder instead of the %APPDATA% folder, this is a setting defined upon (re)installation)

Posted in programming.

Tagged with , .


Installing Titanium on Mac OS 10.10 Yosemite

Again, not a detailed step-by-step guide but mostly tips on the most annoying parts.
A brief overview of the setup process though: download the package from Appcelerator, launch it, and drag and drop the Titanium icon to the Applications folder in the window that pops up (that process never ceases to amaze me: why on Earth require such kind of user input ? Apple, eh….)

Now you can already run it as any other application, however you are likely to encounter an error telling you that you need Java 6, or maybe some more cryptic error message instead, like The JVM shared library “/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/bin/../jre/lib/server/libjvm.dylib” does not contain the JNI_CreateJavaVM symbol. The solution to this is to install Java for OS X 2014-001 (source).

The second issue I had was a fairly unspecific An internal error occurred during: “Computing SDK Info…”. java.lang.NullPointerException. A reported solution was to install Titanium CLI from the command line (sudo npm install titanium -g), however in my case, just running the update process a couple of times (and restarting Titanium in-between) did the trick.

Posted in programming.

Tagged with , .


Publishing a Titanium application to the Apple App Store

Due to a lack of redaction time every time I have to experience with that submission process, this isn’t a full, step-by-step guide but a brief compilation of the issues I ran into (and the solutions that worked for me).

I’ll skip the certificate and provisioning profile part because that’s something “intuitive” enough and if anything else fails you can just revoke the previous ones and create a brand new production signing certificate and a provisioning profile that matches. An important thing to note though is the keychain utility (not very sure how it’s exactly called), which allows you to export your keys, and also view which keys are installed (and whether or not you just have the public key or also the private one, which is of interest here).

Ok, so now you have a signing certificate (with the private key), and the provisioning profile, and you launch the package compilation targeting the App Store in Titanium. Titanium tries to do everything automatically, which includes a few steps of manipulating windows and auto-clicking some buttons. However, doing so requires some specific permissions, and you are likely to encounter, the first time you do it, an error message saying “UI element scripting is not enabled. Check “Enable access for assistive devices””. I think that error message tries to point you to the ad hoc settings window, however this window was move in Mac OS 10.9 (Mavericks), and Titanium still points to the old one. The new setting is located in System Preferences → Security & Privacy → Privacy → Accessibility. There you can check Titanium to allow it to “control your computer” (if the checkboxes aren’t clickable, unlock the settings by clicking on the lock at the bottom-left of the window) (source).

If you’re on Mavericks that should be enough. However, further changes were made in Mac OS 10.10 Yosemite, and when you run Titanium packaging again, as of Titanium 3.4.0 you should land onto a window listing your real and virtual devices: the compilation was done successfully, but the step to package and submit is left unfinished. The missing steps are however easy enough, provided that you know what has to be done.
First you should open the XCode Provisioning Organizer. For this, simply open XCode (Titanium should already have opened it for you), then in the menu: Window → Organizer (source).
Once in XCode Organizer, you should probably land on the right tab, but if you don’t, pick the “Archive” tab. I didn’t take a screenshot so here is one from someone else. Now click distribute, and make sure to uncheck “Include app symbols for your application to receive symbolicated crash logs from Apple” otherwise you will probably get an error saying “rsync failed” (source).

Well, hopefully that’s it now. This last step send your packaged application to your iTunes account, and now the package is ready to be added to your application submission/update form.

Posted in Apple, programming.

Tagged with , .


Getting started on debugging an Android app on Samsung Galaxy devices

I used that on a Galaxy S3, but probably this works with a lot more Galaxy devices. Also the first step is common to any Android device I think (at least where Android is recent enough).

Step 1: enable developer tools on your Android device:
Go to settings → More → About device (on the Galaxy S3, that’s at the bottom of the System subsection)
Tap 7 times on the build number (on the Galaxy S3, again that’s at the bottom of the section)
You should get a message that developer tools are now unlocked

Step 2: enable debugging:
After the previous step, go back to the menu screen where you previously found “About device”. You should have a new menu item (just above “About device” on a GS3) called “Developer option”.
Go there and enable USB debugging

Step 3: install Samsung USB drivers on your computer:
Grab the Samsung Android USB Driver for Windows there (or you can also use my mirror) and install them. That should work without a restart provided you didn’t have ADB running while performing the installation.

Now you’re ready to plug your GS3 and get compiling ;)

Sources:

Posted in programming.