Tag Archive for runtime

Python – Create a function in runtime

import types

def create_function(name, args):

def y(): pass

y_code = types.CodeType(args,
y.func_code.co_nlocals,
y.func_code.co_stacksize,
y.func_code.co_flags,
y.func_code.co_code,
y.func_code.co_consts,
y.func_code.co_names,
y.func_code.co_varnames,
y.func_code.co_filename,
name,
y.func_code.co_firstlineno,
y.func_code.co_lnotab)

return types.FunctionType(y_code, y.func_globals, name)

myfunc = create_function('myfunc', 3)

print repr(myfunc)
print myfunc.func_name
print myfunc.func_code.co_argcount

myfunc(1,2,3,4)
# TypeError: myfunc() takes exactly 3 arguments (4 given)

source

Object Runtime Fields Evaluator

/**
* Usage:
* var o={a:1, b:'!! 1+1', c:'!! alert('c')'};
* evalObj(o);
* //o.a===1
* //o.b===2
* //o.c() will display an alert
*
* Updated to keep the scope, usage:
* var o={a:1, b:'!! this.a+1', c:'!! alert(this.b+1)'};
* evalObj.call(o,o);
* //o.a===1
* //o.b===2
* //o.c() will display an alert with 3
*
*/

function evalObj(o,rec){
if (rec === undefined) {
rec=true;
}
for (var name in o){
var elem=o[name];
if (elem){
var telem=typeof elem;
if (telem==='string' && /^!!/.test(elem)){
o[name]=new Function('return '+elem.substr(2)).call(this);
}else if (rec && telem==='object'){
evalObj.call(this,elem,rec);
}
}
}
return o;
}

source

Track Pageviews only in Production Mode

var mc:MovieClip = new MovieClip();
mc.buttonMode = true;
mc.addEventListener( MouseEvent.CLICK, trackEventHandler, false, 0, true );

function isProductionMode():Boolean
{
var runtimeEvironment:String = Capabilities.playerType;

if (runtimeEvironment == "External" || runtimeEvironment == "StandAlone"){
return false;
} else {
return true;
}
}

function trackEventHandler( e:Event ):void
{
//If the Complied Flash Player is on the HTML page, give it a Page View
if( isProductionMode() ){
navigateToURL(new URLRequest("analytics._trackPageView()"), '_self');
}
}

source