<commit_before>/** Hypermedia workflow execution engine.
 ** Author: Bartosz Balis (2013)
 */

/*
 * Uses workflow map retrieved from redis:
 *  - ins[i][j]     = data id mapped to j-th output port of i-th task
 *  - outs[i][j]    = data id mapped to j-th input port of i-th task
 *  - sources[i][1] = task id which produces data element with id=i (if none, sources[i]=[])
 *  - sources[i][2] = port id in this task the data element is mapped to
 *  - sinks[i][j]   = task id which consumes data element with id=i (if none, sinks[i]=[])
 *  - sinks[i][j+1] = port id in this task the data element is mapped to
 */

var fs = require('fs'),
    xml2js = require('xml2js'),
    fsm = require('./automata.js'),
    async = require('async'),
    eventServerFactory = require('../eventlog');

var ProcDataflowFSM = require('./ProcDataflowFSM.js');
var ProcChoiceFSM = require('./ProcChoiceFSM.js');
var ProcForeachFSM = require('./ProcForeachFSM.js');
var ProcJoinFSM = require('./ProcJoinFSM.js');
var ProcSplitterFSM = require('./ProcSplitterFSM.js');

// TODO: automatically import and register all task FSMs in the current directory
fsm.registerFSM(ProcDataflowFSM);
fsm.registerFSM(ProcChoiceFSM);
fsm.registerFSM(ProcForeachFSM);
fsm.registerFSM(ProcJoinFSM);
fsm.registerFSM(ProcSplitterFSM);

// Engine constructor
// @config: JSON object which contains Engine configuration:
// - config.emulate (true/false) = should engine work in the emulation mode?
var Engine = function(config, wflib, wfId, cb) {
    this.wflib = wflib;
    this.config = config;
    this.eventServer = eventServerFactory.createEventServer();
    this.wfId = wfId;
    this.tasks = [];      // array of task FSMs
    this.ins = [];
    this.outs = [];
    this.sources = [];
    this.sinks = [];
    this.wfOuts = [];
    this.trace = "";  // trace: list of task ids in the sequence they were finished
    this.nTasksLeft = 0;  // how many tasks left (not finished)?
    this.nWfOutsLeft = 0; // how many workflow outputs are still to be produced?
    this.syncCb = null; // callback invoked when wf instance finished execution  (passed to runInstanceSync)

    this.logProvenance = false;

    this.emulate = config.emulate == "true" ? true: false;

    this.startTime = (new Date()).getTime(); // the start time of this engine (workflow)

    var engine = this;
    engine.wflib.getWfMap(wfId, function(err, nTasks, nData, ins, outs, sources, sinks, types, cPortsInfo, fullInfo) {
        //onsole.log("cPortsInfo:"); onsole.log(cPortsInfo); // DEBUG
        engine.nTasksLeft = nTasks;
        engine.ins = ins;
        engine.outs = outs;
        engine.sources = sources;
        engine.sinks = sinks;
        engine.cPorts = cPortsInfo;

        // create processes of types other than default "dataflow" (e.g. "foreach", "splitter", etc.)
        for (var type in types) {
            //onsole.log("type: "+type+", "+types[type]); // DEBUG
            types[type].forEach(function(taskId) {
                engine.tasks[taskId] = fsm.createSession(type);
                engine.tasks[taskId].logic.init(engine, wfId, taskId, engine.tasks[taskId], fullInfo[taskId]);
            });
        }
        // create all other processes (assuming the default type "dataflow")
        for (var taskId=1; taskId<=nTasks; ++taskId) {
            if (!engine.tasks[taskId]) {
                engine.tasks[taskId] = fsm.createSession("dataflow");
                engine.tasks[taskId].logic.init(engine, wfId, taskId, engine.tasks[taskId], fullInfo[taskId]);
            }
        }

        engine.wflib.getWfOuts(engine.wfId, false, function(err, wfOuts) {
            engine.wfOuts = wfOuts;
            engine.nWfOutsLeft = wfOuts.length ? wfOuts.length: -1;
            cb(null);
        });
    });
}

    //////////////////////////////////////////////////////////////////////////
    ///////////////////////// public functions ///////////////////////////////
    //////////////////////////////////////////////////////////////////////////

Engine.prototype.runInstance = function (cb) {
    var engine = this;
    engine.wflib.setWfInstanceState(engine.wfId, { "status": "running" }, function(err, rep) {
        if (err) return cb(err);
        // send initial signals (if any) to the instance
        engine.wflib.getInitialSigs(engine.wfId, function(err, sigs) {
            if (sigs) {
                engine.emitSignals(sigs, function(err) {
                    if (err) console.log(err);
                    cb(err);
                });
            }
        });
    });

    // Emulate workflow execution: change state of all workflow inputs to "ready" and send
    // signal to all sink tasks; pretend task Functions are invoked and results computed.
    if (this.emulate) {
        (function(engine) {
            engine.wflib.getWfIns(engine.wfId, false, function(err, wfIns) {
                for (var i=0; i<wfIns.length; ++i) {
                    markDataReadyAndNotifySinks(engine.wfId, wfIns[i], engine.tasks, engine.wflib, function() { });
                }
            });
        })(this);
    }
}

// callback of this function is invoked only when the workflow instance running in this
// engine has finished execution.
Engine.prototype.runInstanceSync = function(callback) {
    (function(engine) {
        engine.runInstance(function(err) {
            engine.syncCb = callback;
        });
    })(this);
}

Engine.prototype.taskFinished = function(taskId) {
    this.trace += taskId;
    this.nTasksLeft--;
    //onsole.log("OUTS LEFT:", this.nWfOutsLeft);
    if (this.nWfOutsLeft == 0 || this.nTasksLeft == 0) {
        this.workflowFinished(); // all wf outputs produced ==> wf is finished (always?)
    } else {
        this.trace += ",";
    }
}

Engine.prototype.workflowFinished = function() {
    console.log("Workflow ["+this.wfId+"] finished. Exec trace:", this.trace+"." );
    //onsole.log(this.syncCb);
    if (this.syncCb) {
        this.syncCb();
    }
}

// Function used by processes to emit signals
// @sigs (array): ids of signals (data and control ones) to be emitted
//                format: [ { attr: value,
//                            ...
//                            "_id": sigId,
//                            "data": [ { ... }, ... { ... } ] => multiple instances of this signal
//                           },
//                           { attr: value,
//                                ...
//                            "_id": sigId,
//                            "data": [ { ... }, ... { ... } ] => multiple instances of this signal
//                           }
//                        ]
Engine.prototype.emitSignals = function(sigs, cb) {
    var timeStamp; // time stamp to be added to each signal (relative to workflow start time)
    var engine = this;

    var copySignal = function(sig) {
        var copy = {};
        if (null == sig || "object" != typeof sig) return sig;
        for (var attr in sig) {
            if (sig.hasOwnProperty(attr) && attr != "data")
                copy[attr] = sig[attr];
        }
        return copy;
    }

    timeStamp = (new Date()).getTime() - engine.startTime;

    // iterate over all signals to be sent
    async.each(sigs, function iterator(sig, doneIter) {
        var sigInstances = [];
        sig._ts = timeStamp;
        if (sig.data) { // there is a 'data' array which may contain multiple instances of this signal
            for (var i in sig.data) {
                var s = copySignal(sig);
                s.data = [sig.data[i]];
                sigInstances.push(s);
            }
        } else {
            sigInstances.push(sig);
        }

        // send all instances of a given signal
        async.each(sigInstances, function(s, doneIterInner) {
            var _sigId = s._id;
            engine.wflib.sendSignal(engine.wfId, s, function(err, sinks) {
                // at this point "s" contains unique 'sigIdx' set in 'sendSignal' => we can emit "write"
                // provenance events (for signals which have "source", i.e. were written by a process)
                if (s.source && engine.logProvenance) {
                    engine.eventServer.emit("prov", ["write", +engine.wfId, +s.source, +s.firingId, +s._id, +s.sigIdx]);
                }

                if (!err) {
                    // notify sinks that the signals have arrived
                    for (var j=0; j<sinks.length; j++) {
                        // send event that an input is ready
                        engine.tasks[sinks[j]].fireCustomEvent({
                            wfId: engine.wfId,
                            taskId: sinks[j],
                            sigId: _sigId,
                            sig: s
                        });
                        //onsole.log("sending signal", _sigId, "to task", sinks[j]);
                    }
                }
                doneIterInner(err);
            });
        }, function doneAllInner(err) {
            doneIter(err);
        });

    }, function doneAll(err) {
        if (cb) { cb(err); }
    });
}

module.exports = Engine;
<commit_msg>Function can now return null in 'outs' in which case no signals will be emitted.<commit_after>/** Hypermedia workflow execution engine.
 ** Author: Bartosz Balis (2013)
 */

/*
 * Uses workflow map retrieved from redis:
 *  - ins[i][j]     = data id mapped to j-th output port of i-th task
 *  - outs[i][j]    = data id mapped to j-th input port of i-th task
 *  - sources[i][1] = task id which produces data element with id=i (if none, sources[i]=[])
 *  - sources[i][2] = port id in this task the data element is mapped to
 *  - sinks[i][j]   = task id which consumes data element with id=i (if none, sinks[i]=[])
 *  - sinks[i][j+1] = port id in this task the data element is mapped to
 */

var fs = require('fs'),
    xml2js = require('xml2js'),
    fsm = require('./automata.js'),
    async = require('async'),
    eventServerFactory = require('../eventlog');

var ProcDataflowFSM = require('./ProcDataflowFSM.js');
var ProcChoiceFSM = require('./ProcChoiceFSM.js');
var ProcForeachFSM = require('./ProcForeachFSM.js');
var ProcJoinFSM = require('./ProcJoinFSM.js');
var ProcSplitterFSM = require('./ProcSplitterFSM.js');

// TODO: automatically import and register all task FSMs in the current directory
fsm.registerFSM(ProcDataflowFSM);
fsm.registerFSM(ProcChoiceFSM);
fsm.registerFSM(ProcForeachFSM);
fsm.registerFSM(ProcJoinFSM);
fsm.registerFSM(ProcSplitterFSM);

// Engine constructor
// @config: JSON object which contains Engine configuration:
// - config.emulate (true/false) = should engine work in the emulation mode?
var Engine = function(config, wflib, wfId, cb) {
    this.wflib = wflib;
    this.config = config;
    this.eventServer = eventServerFactory.createEventServer();
    this.wfId = wfId;
    this.tasks = [];      // array of task FSMs
    this.ins = [];
    this.outs = [];
    this.sources = [];
    this.sinks = [];
    this.wfOuts = [];
    this.trace = "";  // trace: list of task ids in the sequence they were finished
    this.nTasksLeft = 0;  // how many tasks left (not finished)?
    this.nWfOutsLeft = 0; // how many workflow outputs are still to be produced?
    this.syncCb = null; // callback invoked when wf instance finished execution  (passed to runInstanceSync)

    this.logProvenance = false;

    this.emulate = config.emulate == "true" ? true: false;

    this.startTime = (new Date()).getTime(); // the start time of this engine (workflow)

    var engine = this;
    engine.wflib.getWfMap(wfId, function(err, nTasks, nData, ins, outs, sources, sinks, types, cPortsInfo, fullInfo) {
        //onsole.log("cPortsInfo:"); onsole.log(cPortsInfo); // DEBUG
        engine.nTasksLeft = nTasks;
        engine.ins = ins;
        engine.outs = outs;
        engine.sources = sources;
        engine.sinks = sinks;
        engine.cPorts = cPortsInfo;

        // create processes of types other than default "dataflow" (e.g. "foreach", "splitter", etc.)
        for (var type in types) {
            //onsole.log("type: "+type+", "+types[type]); // DEBUG
            types[type].forEach(function(taskId) {
                engine.tasks[taskId] = fsm.createSession(type);
                engine.tasks[taskId].logic.init(engine, wfId, taskId, engine.tasks[taskId], fullInfo[taskId]);
            });
        }
        // create all other processes (assuming the default type "dataflow")
        for (var taskId=1; taskId<=nTasks; ++taskId) {
            if (!engine.tasks[taskId]) {
                engine.tasks[taskId] = fsm.createSession("dataflow");
                engine.tasks[taskId].logic.init(engine, wfId, taskId, engine.tasks[taskId], fullInfo[taskId]);
            }
        }

        engine.wflib.getWfOuts(engine.wfId, false, function(err, wfOuts) {
            engine.wfOuts = wfOuts;
            engine.nWfOutsLeft = wfOuts.length ? wfOuts.length: -1;
            cb(null);
        });
    });
}

    //////////////////////////////////////////////////////////////////////////
    ///////////////////////// public functions ///////////////////////////////
    //////////////////////////////////////////////////////////////////////////

Engine.prototype.runInstance = function (cb) {
    var engine = this;
    engine.wflib.setWfInstanceState(engine.wfId, { "status": "running" }, function(err, rep) {
        if (err) return cb(err);
        // send initial signals (if any) to the instance
        engine.wflib.getInitialSigs(engine.wfId, function(err, sigs) {
            if (sigs) {
                engine.emitSignals(sigs, function(err) {
                    if (err) console.log(err);
                    cb(err);
                });
            }
        });
    });

    // Emulate workflow execution: change state of all workflow inputs to "ready" and send
    // signal to all sink tasks; pretend task Functions are invoked and results computed.
    if (this.emulate) {
        (function(engine) {
            engine.wflib.getWfIns(engine.wfId, false, function(err, wfIns) {
                for (var i=0; i<wfIns.length; ++i) {
                    markDataReadyAndNotifySinks(engine.wfId, wfIns[i], engine.tasks, engine.wflib, function() { });
                }
            });
        })(this);
    }
}

// callback of this function is invoked only when the workflow instance running in this
// engine has finished execution.
Engine.prototype.runInstanceSync = function(callback) {
    (function(engine) {
        engine.runInstance(function(err) {
            engine.syncCb = callback;
        });
    })(this);
}

Engine.prototype.taskFinished = function(taskId) {
    this.trace += taskId;
    this.nTasksLeft--;
    //onsole.log("OUTS LEFT:", this.nWfOutsLeft);
    if (this.nWfOutsLeft == 0 || this.nTasksLeft == 0) {
        this.workflowFinished(); // all wf outputs produced ==> wf is finished (always?)
    } else {
        this.trace += ",";
    }
}

Engine.prototype.workflowFinished = function() {
    console.log("Workflow ["+this.wfId+"] finished. Exec trace:", this.trace+"." );
    //onsole.log(this.syncCb);
    if (this.syncCb) {
        this.syncCb();
    }
}

// Function used by processes to emit signals
// @sigs (array): ids of signals (data and control ones) to be emitted
//                format: [ { attr: value,
//                            ...
//                            "_id": sigId,
//                            "data": [ { ... }, ... { ... } ] => multiple instances of this signal
//                           },
//                           { attr: value,
//                                ...
//                            "_id": sigId,
//                            "data": [ { ... }, ... { ... } ] => multiple instances of this signal
//                           }
//                        ]
Engine.prototype.emitSignals = function(sigs, cb) {
    var timeStamp; // time stamp to be added to each signal (relative to workflow start time)
    var engine = this;

    var copySignal = function(sig) {
        var copy = {};
        if (null == sig || "object" != typeof sig) return sig;
        for (var attr in sig) {
            if (sig.hasOwnProperty(attr) && attr != "data")
                copy[attr] = sig[attr];
        }
        return copy;
    }

    timeStamp = (new Date()).getTime() - engine.startTime;

    // iterate over all signals to be sent
    async.each(sigs, function iterator(sig, doneIter) {
        var sigInstances = [];
        sig._ts = timeStamp;
        if (sig.data) { // there is a 'data' array which may contain multiple instances of this signal
            for (var i in sig.data) {
                var s = copySignal(sig);
                s.data = [sig.data[i]];
                sigInstances.push(s);
            }
        } else {
            sigInstances.push(sig);
        }

        // send all instances of a given signal
        async.each(sigInstances, function(s, doneIterInner) {
            var _sigId = s._id;
            engine.wflib.sendSignal(engine.wfId, s, function(err, sinks) {
                // at this point "s" contains unique 'sigIdx' set in 'sendSignal' => we can emit "write"
                // provenance events (for signals which have "source", i.e. were written by a process)
                // FIXME: remove "sig" at the end of event (for debugging only)
                if (s.source && engine.logProvenance) {
                    engine.eventServer.emit("prov", ["write", +engine.wfId, +s.source, +s.firingId, +s._id, +s.sigIdx, sig]);
                }

                // log signal payload in the provenance log
                if (engine.logProvenance) {
                    engine.eventServer.emit("prov", ["sig", s]);
                }

                if (!err) {
                    // notify sinks that the signals have arrived
                    for (var j=0; j<sinks.length; j++) {
                        // send event that an input is ready
                        engine.tasks[sinks[j]].fireCustomEvent({
                            wfId: engine.wfId,
                            taskId: sinks[j],
                            sigId: _sigId,
                            sig: s
                        });
                        //onsole.log("sending signal", _sigId, "to task", sinks[j]);
                    }
                }
                doneIterInner(err);
            });
        }, function doneAllInner(err) {
            doneIter(err);
        });

    }, function doneAll(err) {
        if (cb) { cb(err); }
    });
}

module.exports = Engine;
<|endoftext|>


<commit_before>(function (cm, L) {
    'use strict';

    var icons = {
        'Einbruch': L.AwesomeMarkers.icon({
            icon: 'home',
            prefix: 'icon',
            extraClasses: 'icon',
            markerColor: 'darkblue'
        }),
        'Autoaufbruch': L.AwesomeMarkers.icon({
            icon: 'cab',
            prefix: 'icon',
            extraClasses: 'icon',
            markerColor: 'blue'
        })
    };

    var generateAddress = function (crime) {
        var address = crime.city;
        if (crime.district) {
            address += ', ' + crime.district;
        }
        if (crime.street) {
            address += ', ' + crime.street;
        }
        return address;
    };

    cm.map.markers = function (mapInstance) {
        var cluster = new L.MarkerClusterGroup({
            maxClusterRadius: 50,
            animateAddingMarkers: false
        });
        mapInstance.addLayer(cluster);

        this.update = function (crimes) {
            cluster.clearLayers();
            var markers = [];
            crimes.forEach(function (crime) {
                var marker = new L.Marker([crime.lat, crime.lon], {icon: icons[crime.type]});
                marker.bindPopup('
' + crime.type + ' am ' + crime.date + '

' + generateAddress(crime) + '

Polizeimeldung: ' + crime.description + '
');
                markers.push(marker);
            });
            cluster.addLayers(markers);
        };

        return this;
    };
})(cm, L);
<commit_msg>hide street numbers<commit_after>(function (cm, L) {
    'use strict';

    var icons = {
        'Einbruch': L.AwesomeMarkers.icon({
            icon: 'home',
            prefix: 'icon',
            extraClasses: 'icon',
            markerColor: 'darkblue'
        }),
        'Autoaufbruch': L.AwesomeMarkers.icon({
            icon: 'cab',
            prefix: 'icon',
            extraClasses: 'icon',
            markerColor: 'blue'
        })
    };

    var generateAddress = function (crime) {
        var address = crime.city;
        if (crime.district) {
            address += ', ' + crime.district;
        }
        if (crime.street) {
            var street = crime.street.trim()
            if (!isNaN(street.slice(-1))) {
                street = street.substring(0, street.lastIndexOf(" ")).trim();
            }
            address += ', ' + street;
        }
        return address;
    };

    cm.map.markers = function (mapInstance) {
        var cluster = new L.MarkerClusterGroup({
            maxClusterRadius: 50,
            animateAddingMarkers: false
        });
        mapInstance.addLayer(cluster);

        this.update = function (crimes) {
            cluster.clearLayers();
            var markers = [];
            crimes.forEach(function (crime) {
                var marker = new L.Marker([crime.lat, crime.lon], {icon: icons[crime.type]});
                marker.bindPopup('
' + crime.type + ' am ' + crime.date + '

' + generateAddress(crime) + '

Polizeimeldung: ' + crime.description + '
');
                markers.push(marker);
            });
            cluster.addLayers(markers);
        };

        return this;
    };
})(cm, L);
<|endoftext|>


<commit_before>'use strict';

var EPSILON = 1e-4;

function Spring( k, b ) {
  this.k = k;
  this.b = b;

  this.x = 0;
  this.v = 0;
  this.to = 0;
}

Spring.prototype.update = function( dt ) {
  var a = this.k * ( this.to - this.x ) - this.b * this.v;

  var v = this.v + a * dt;
  var x = this.x + v * dt;

  if ( Math.abs( v - this.v ) < EPSILON &&
       Math.abs( x - this.x ) < EPSILON ) {
    this.x = this.to;
    this.v = 0;
  }

  this.x = x;
  this.v = v;
};

module.exports = Spring;
<commit_msg>Simplify Spring methods.<commit_after>'use strict';

var EPSILON = 1e-4;

function update( dt, x, v, to, k, b ) {
  var a = k * ( to - x ) - b * v;

  var vf = v + a  * dt;
  var xf = x + vf * dt;

  if ( Math.abs( vf - v ) < EPSILON &&
       Math.abs( xf - x ) < EPSILON ) {
    return [ to, 0 ];
  }

  return [ xf, vf ];
}

// Spring for shallow objects.
function Spring( k, b ) {
  this.k = k;
  this.b = b;

  this.state = {};
  this.to = {};
}

Spring.prototype.update = function( dt ) {
  Object.keys( this.state ).map(function( key ) {
    if ( this.to[ key ] !== undefined ) {
      this.state[ key ] = update(
        dt,
        this.state[ key ][ 0 ],
        this.state[ key ][ 1 ],
        this.to[ key ],
        this.k,
        this.b
      );
    }
  }, this );
};

Spring.prototype.set = function( source ) {
  this.state = Object.keys( source ).reduce(function( object, key ) {
    var value = source[ key ];
    if ( isFinite( value ) ) {
      object[ key ] = [ value, 0 ];
    }

    return object;
  }, {} );

  return this;
};

Spring.prototype.getValues = function() {
  var state = this.state;

  return Object.keys( this.to ).reduce(function( object, key ) {
    if ( state[ key ] ) {
      object[ key ] = state[ key ][ 0 ];
    }

    return object;
  }, {} );
};

module.exports = Spring;
<|endoftext|>


<commit_before>var _ = require('lodash')
var inherits = require('inherits')
var mouse = require('../geometry/mouse.js')
var Collision = require('../util/collision.js')
var Fixmove = require('../movement/fixmove.js')
var Automove = require('../movement/automove.js')
var Entity = require('crtrdg-entity')

module.exports = Player
inherits(Player, Entity)

function Player (opts) {
  this.opts = opts || {}
  var translation = [
    50 * 3 / 2 * opts.translation[0],
    50 * Math.sqrt(3) * (opts.translation[1] + opts.translation[0] / 2)
  ]
  if (opts.character === 'mouse') {
    this.geometry = mouse({
      translation: translation,
      rotation: opts.rotation,
      fill: opts.fill,
      stroke: opts.stroke,
      scale: opts.scale,
      thickness: opts.thickness
    })
  }
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W', '<left>', '<right>', '<up>'],
    heading: [-60, 60, 0, -60, 60, 0],
    shift: [0, 0, 8, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: [],
    heading: [],
    shift: [],
    speed: opts.speed
  })
  this.movement.deadend = new Automove({
    keymap: [],
    heading: [],
    shift: [],
    speed: {translation: -opts.speed.translation, rotation: opts.speed.rotation}
  })
  this.collision = new Collision()
  this.waiting = true
  this.reversing = false
  this.inside = false
  this.moving = true
}

Player.prototype.moveto = function (transform) {
  rotation = transform.rotation || 0
  var translation = [
    50 * 3 / 2 * transform.translation[0],
    50 * Math.sqrt(3) * (transform.translation[1] + transform.translation[0] / 2)
  ]
  this.geometry.unstage()
  this.geometry.transform.rotation = rotation
  this.geometry.transform.translation = translation
  this.geometry.stage()
}

Player.prototype.move = function (keyboard, world) {
  var self = this

  var tile = world.gettile(this.coordinates())
  var current = self.geometry.transform

  var trigger = _.find(tile.children, function (child) { return child.props.trigger })
  var inside = trigger.contains(current.translation)
  var keys = keyboard.keysDown

  if (inside && !self.inside) {
    self.emit('enter', { tile: self.coordinates(), position: self.geometry.transform })
    self.inside = true
  } else if (!inside && self.inside) {
    self.emit('exit', { tile: self.coordinates(), position: self.geometry.transform })
    self.inside = false
  }

  var delta
  var correction

  if (inside) {
    self.moving = false
    self.movement.deadend.reset()
    self.reversing = false

    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        translation: tile.transform.translation
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }

    self.geometry.update(delta)
    correction = self.collision.handle(world, self.geometry, delta)

    if (correction) {
      self.geometry.update(correction)
      self.waiting = true
      self.movement.tile.reset()
    }
  } else {
    self.waiting = true
    self.moving = true
    self.movement.tile.reset()

    delta = self.movement.path.compute(keys, current)
    correction = self.collision.handle(world, self.geometry, delta)

    if (correction && !self.reversing) {
      self.reversing = true
      self.geometry.update(correction)
    }

    if (self.reversing) {
      delta = self.movement.deadend.compute(keys, current)
      self.geometry.update(delta)
    } else {
      self.geometry.update(delta)
    }
  }
}

Player.prototype.draw = function (context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function () {
  return this.geometry.transform.translation
}

Player.prototype.coordinates = function () {
  var position = this.position()
  var tileScale = 50
  var x = position[0] / 3 / tileScale * 2
  var y = (position[1] - tileScale * Math.sqrt(3) * x / 2) / (tileScale * Math.sqrt(3))
  return [Math.round(x), Math.round(y)]
}

Player.prototype.angle = function () {
  return this.geometry.transform.rotation
}
<commit_msg>Fix rotation updating<commit_after>var _ = require('lodash')
var inherits = require('inherits')
var mouse = require('../geometry/mouse.js')
var Collision = require('../util/collision.js')
var Fixmove = require('../movement/fixmove.js')
var Automove = require('../movement/automove.js')
var Entity = require('crtrdg-entity')

module.exports = Player
inherits(Player, Entity)

function Player (opts) {
  this.opts = opts || {}
  var translation = [
    50 * 3 / 2 * opts.translation[0],
    50 * Math.sqrt(3) * (opts.translation[1] + opts.translation[0] / 2)
  ]
  if (opts.character === 'mouse') {
    this.geometry = mouse({
      translation: translation,
      rotation: opts.rotation,
      fill: opts.fill,
      stroke: opts.stroke,
      scale: opts.scale,
      thickness: opts.thickness
    })
  }
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'W', '<left>', '<right>', '<up>'],
    heading: [-60, 60, 0, -60, 60, 0],
    shift: [0, 0, 8, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: [],
    heading: [],
    shift: [],
    speed: opts.speed
  })
  this.movement.deadend = new Automove({
    keymap: [],
    heading: [],
    shift: [],
    speed: {translation: -opts.speed.translation, rotation: opts.speed.rotation}
  })
  this.collision = new Collision()
  this.waiting = true
  this.reversing = false
  this.inside = false
  this.moving = true
}

Player.prototype.moveto = function (transform) {
  rotation = transform.rotation || 0
  var translation = [
    50 * 3 / 2 * transform.translation[0],
    50 * Math.sqrt(3) * (transform.translation[1] + transform.translation[0] / 2)
  ]
  this.geometry.unstage()
  this.geometry.transform.translation = translation
  this.geometry.transform.rotation = 0
  this.geometry.stage()
  this.geometry.update({rotation: rotation})
}

Player.prototype.move = function (keyboard, world) {
  var self = this

  var tile = world.gettile(this.coordinates())
  var current = self.geometry.transform

  var trigger = _.find(tile.children, function (child) { return child.props.trigger })
  var inside = trigger.contains(current.translation)
  var keys = keyboard.keysDown

  if (inside && !self.inside) {
    self.emit('enter', { tile: self.coordinates(), position: self.geometry.transform })
    self.inside = true
  } else if (!inside && self.inside) {
    self.emit('exit', { tile: self.coordinates(), position: self.geometry.transform })
    self.inside = false
  }

  var delta
  var correction

  if (inside) {
    self.moving = false
    self.movement.deadend.reset()
    self.reversing = false

    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        translation: tile.transform.translation
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }

    self.geometry.update(delta)
    correction = self.collision.handle(world, self.geometry, delta)

    if (correction) {
      self.geometry.update(correction)
      self.waiting = true
      self.movement.tile.reset()
    }
  } else {
    self.waiting = true
    self.moving = true
    self.movement.tile.reset()

    delta = self.movement.path.compute(keys, current)
    correction = self.collision.handle(world, self.geometry, delta)

    if (correction && !self.reversing) {
      self.reversing = true
      self.geometry.update(correction)
    }

    if (self.reversing) {
      delta = self.movement.deadend.compute(keys, current)
      self.geometry.update(delta)
    } else {
      self.geometry.update(delta)
    }
  }
}

Player.prototype.draw = function (context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function () {
  return this.geometry.transform.translation
}

Player.prototype.coordinates = function () {
  var position = this.position()
  var tileScale = 50
  var x = position[0] / 3 / tileScale * 2
  var y = (position[1] - tileScale * Math.sqrt(3) * x / 2) / (tileScale * Math.sqrt(3))
  return [Math.round(x), Math.round(y)]
}

Player.prototype.angle = function () {
  return this.geometry.transform.rotation
}
<|endoftext|>


<commit_before>/*

    Module to serve up directory listings, typically for content hosted with the "static" router.  See the
    documentation for more details:

    https://github.com/GPII/gpii-express/blob/master/docs/router.md

 */
"use strict";
var fluid      = require("infusion");
var gpii       = fluid.registerNamespace("gpii");
var serveIndex = require("serve-index");

require("./static");

fluid.registerNamespace("gpii.express.router.serveIndex");
gpii.express.router.serveIndex.init = function (that) {
    var allPaths = gpii.express.expandPaths(that.options.content);
    if (allPaths.length > 1) {
        fluid.log("WARN: Multiple content paths found.  Only content from the first content directory will be used in generating the directory index.");
    }

    that.router.use(serveIndex(allPaths[0], that.options.serveIndexMiddlewareOptions));
};

gpii.express.router.serveIndex.defaultOptions = { icons: true};

fluid.defaults("gpii.express.router.serveIndex", {
    gradeNames: ["gpii.express.router"],
    namespace: "serveIndex",
    content: null,
    serveIndexMiddlewareOptions: gpii.express.router.serveIndex.defaultOptions,
    listeners: {
        "onCreate.init": {
            funcName: "gpii.express.router.serveIndex.init",
            args:     ["{that}"]
        }
    }
});

fluid.defaults("gpii.express.router.serveContentAndIndex", {
    gradeNames: ["gpii.express.router"],
    content: "%my-package/src/content",
    serveIndexMiddlewareOptions: gpii.express.router.serveIndex.defaultOptions,
    staticMiddlewareOptions: {},
    components: {
        serveIndex: {
            type: "gpii.express.router.serveIndex",
            options: {
                content: "{gpii.express.router.serveContentAndIndex}.options.content",
                serveIndexMiddlewareOptions: "{gpii.express.router.serveContentAndIndex}.options.serveIndexMiddlewareOptions"
            }
        },
        static: {
            type: "gpii.express.router.static",
            options: {
                priority: "after:serveIndex",
                content: "{gpii.express.router.serveContentAndIndex}.options.content",
                staticMiddlewareOptions: "{gpii.express.router.serveContentAndIndex}.options.staticMiddlewareOptions"
            }
        }
    }
});
<commit_msg>GPII-2753:  Changed order of index/static middleware within combined router so that index.html will be used if present.<commit_after>/*

    Module to serve up directory listings, typically for content hosted with the "static" router.  See the
    documentation for more details:

    https://github.com/GPII/gpii-express/blob/master/docs/router.md

 */
"use strict";
var fluid      = require("infusion");
var gpii       = fluid.registerNamespace("gpii");
var serveIndex = require("serve-index");

require("./static");

fluid.registerNamespace("gpii.express.router.serveIndex");
gpii.express.router.serveIndex.init = function (that) {
    var allPaths = gpii.express.expandPaths(that.options.content);
    if (allPaths.length > 1) {
        fluid.log("WARN: Multiple content paths found.  Only content from the first content directory will be used in generating the directory index.");
    }

    that.router.use(serveIndex(allPaths[0], that.options.serveIndexMiddlewareOptions));
};

gpii.express.router.serveIndex.defaultOptions = { icons: true};

fluid.defaults("gpii.express.router.serveIndex", {
    gradeNames: ["gpii.express.router"],
    namespace: "serveIndex",
    content: null,
    serveIndexMiddlewareOptions: gpii.express.router.serveIndex.defaultOptions,
    listeners: {
        "onCreate.init": {
            funcName: "gpii.express.router.serveIndex.init",
            args:     ["{that}"]
        }
    }
});

fluid.defaults("gpii.express.router.serveContentAndIndex", {
    gradeNames: ["gpii.express.router"],
    content: "%my-package/src/content",
    serveIndexMiddlewareOptions: gpii.express.router.serveIndex.defaultOptions,
    staticMiddlewareOptions: {},
    components: {
        // This comes first so that index.html will win out if it's present.
        static: {
            type: "gpii.express.router.static",
            options: {
                priority: "before:serveIndex",
                content: "{gpii.express.router.serveContentAndIndex}.options.content",
                staticMiddlewareOptions: "{gpii.express.router.serveContentAndIndex}.options.staticMiddlewareOptions"
            }
        },
        serveIndex: {
            type: "gpii.express.router.serveIndex",
            options: {
                content: "{gpii.express.router.serveContentAndIndex}.options.content",
                serveIndexMiddlewareOptions: "{gpii.express.router.serveContentAndIndex}.options.serveIndexMiddlewareOptions"
            }
        }
    }
});
<|endoftext|>


<commit_before>;(function(Planner, Utils){ 'use strict';

    Planner.Model = Planner.Model || {};

    // Card class definition with prototype methods
    // --------------------------------------------

    var Card = function(args) {
        this.id = args.id;
        this.title = args.title;
        this.content = args.content;
        this.start = args.start;
        this.end = args.end;
        this.assignees = args.assignees;

        // Generate DOM if all required arguments are defined
        if(typeof this.start !== 'undefined' && typeof this.end !== 'undefined' && typeof this.assignees !== 'undefined') {
            this.generateDOM();
        }
    };

    // Card class definition with prototype methods
    // --------------------------------------------

    Card.prototype.generateTitle = function() {
        var self = this;
        var title;

        if (typeof self.start.getHours === 'function' && typeof self.start.getMinutes === 'function' && typeof self.end.getHours === 'function' && typeof self.end.getMinutes === 'function') {
            title = Utils.pad(self.start.getHours()) + ':' + Utils.pad(self.start.getMinutes()) + ' - ' + Utils.pad(self.end.getHours()) + ':' + Utils.pad(self.end.getMinutes());
        } else if (self.start === self.end) {
            title = self.start;
        } else {
            title = self.start + '-' + self.end;
        }

        return title;
    };

    Card.prototype.generateDOM = function() {
        var options = Planner.options;
        var self = this;
        self.titleHeader = self.generateTitle();

        // Generate a standard Card DOM object
        var generatedElements = [];
        var cardDOM = $(Planner.Templates.card(self));
        var element;

        // Generate DOM element for each assignees
        this.assignees.forEach(function(assignee) {
            element = cardDOM.clone();

            // Convert Card attributes to DOM attributes
            var start = Planner.Helpers.attributeToIndex(self.start);
            var end = Planner.Helpers.attributeToIndex(self.end);
            var cardLength = (end - start) * options.timeslotHeight - options.cardTitleMargin;

            // Set DOM values
            element.data('column', assignee);
            element.data('start', start);
            element.data('end', end);
            element.height(cardLength);

            generatedElements.push(element);
        });

        self.$element = generatedElements;
    };

    // Methods that should be overridden by your
    // application to enable persistence
    // -----------------------------------------

    Card.prototype.save = function() {};
    Card.prototype.delete = function() {};

    Planner.Model.Card = Card;

})(Planner, Planner.Utils);
<commit_msg>Event propagation on card click. Closes #8<commit_after>;(function(Planner, Utils){ 'use strict';

    Planner.Model = Planner.Model || {};

    // Card class definition with prototype methods
    // --------------------------------------------

    var Card = function(args) {
        this.id = args.id;
        this.title = args.title;
        this.content = args.content;
        this.start = args.start;
        this.end = args.end;
        this.assignees = args.assignees;

        // Generate DOM if all required arguments are defined
        if(typeof this.start !== 'undefined' && typeof this.end !== 'undefined' && typeof this.assignees !== 'undefined') {
            this.generateDOM();
        }
    };

    // Card class definition with prototype methods
    // --------------------------------------------

    Card.prototype.generateTitle = function() {
        var self = this;
        var title;

        if (typeof self.start.getHours === 'function' && typeof self.start.getMinutes === 'function' && typeof self.end.getHours === 'function' && typeof self.end.getMinutes === 'function') {
            title = Utils.pad(self.start.getHours()) + ':' + Utils.pad(self.start.getMinutes()) + ' - ' + Utils.pad(self.end.getHours()) + ':' + Utils.pad(self.end.getMinutes());
        } else if (self.start === self.end) {
            title = self.start;
        } else {
            title = self.start + '-' + self.end;
        }

        return title;
    };

    Card.prototype.generateDOM = function() {
        var options = Planner.options;
        var self = this;
        self.titleHeader = self.generateTitle();

        // Generate a standard Card DOM object
        var generatedElements = [];
        var cardDOM = $(Planner.Templates.card(self));
        var element;

        // Generate DOM element for each assignees
        this.assignees.forEach(function(assignee) {
            element = cardDOM.clone();

            // Convert Card attributes to DOM attributes
            var start = Planner.Helpers.attributeToIndex(self.start);
            var end = Planner.Helpers.attributeToIndex(self.end);
            var cardLength = (end - start) * options.timeslotHeight - options.cardTitleMargin;

            // Set DOM values
            element.data('column', assignee);
            element.data('start', start);
            element.data('end', end);
            element.height(cardLength);

            element.on('click', function() {
                Planner.Events.publish('cardClicked', [self, element]);
            });

            generatedElements.push(element);
        });

        self.$element = generatedElements;
    };

    // Methods that should be overridden by your
    // application to enable persistence
    // -----------------------------------------

    Card.prototype.save = function() {};
    Card.prototype.delete = function() {};

    Planner.Model.Card = Card;

})(Planner, Planner.Utils);
<|endoftext|>


<commit_before>var util = require('util');
var Tab = require('../client/tab').Tab;

var SignupTab = function() {
  Tab.call(this);
};

util.inherits(SignupTab, Tab);

SignupTab.prototype.pageMode = 'single';
SignupTab.prototype.parent = 'main';

SignupTab.prototype.generateHtml = function() {
  return require('../../jade/tabs/signup.jade')();
};

SignupTab.prototype.angular = function(module) {
  var app = this.app;

  module.controller('SignupCtrl', ['$scope', '$location', 'rpId', 'rpGiveaway', '$routeParams',

  function($scope, $location, $id, $giveaway, $routeParams) {

    if ($routeParams.errors) {
      $scope.step = 'errors';
      $scope.errors = $routeParams.errors;
    } else if ($routeParams.register) {
      // if already confirmed redirect to register page
      if ($routeParams.error == 'already_confirmed')
        $location.path('/register');
      // if an address is already associated redirect to login
      else if ($routeParams.errors == 'address_associated')
        $location.path('/login');

      $scope.step = 'two';
      $scope.name = $routeParams.name;
      $scope.email = $routeParams.email;
    } else {
      $scope.step = 'one';
    }

    $scope.oauth = function() {
      $scope.sending = false;
      window.location = Options.giveawayServer + Options.githubOauth;
    };

    $scope.step_two = function() {
      $.post(Options.giveawayServer + '/user/' + $routeParams.id, {
          action: 'confirm',
          register: $routeParams.register,
          name: $scope.name,
          email: $scope.email
      }, function(data){
        $scope.step = 'three';
      });
    };

    $scope.step_three = function() {
      $scope.mode = 'welcome';
    };

    // hook into popup service
    $scope.developerProgram = function() {

    };

    $scope.getRipple = function() {
      $location.path('/getripple');
    };

  }]);
};

module.exports = SignupTab;<commit_msg>refactoring error checking<commit_after>var util = require('util');
var Tab = require('../client/tab').Tab;

var SignupTab = function() {
  Tab.call(this);
};

util.inherits(SignupTab, Tab);

SignupTab.prototype.pageMode = 'single';
SignupTab.prototype.parent = 'main';

SignupTab.prototype.generateHtml = function() {
  return require('../../jade/tabs/signup.jade')();
};

SignupTab.prototype.angular = function(module) {
  var app = this.app;

  module.controller('SignupCtrl', ['$scope', '$location', 'rpId', 'rpGiveaway', '$routeParams',

  function($scope, $location, $id, $giveaway, $routeParams) {
    // set errors
    $scope.errors = $routeParams.errors.split(',');
    // handle register
    if (_.contains($scope.errors, 'cutoff')) {
      $scope.step = 'errors';
    } else if ($routeParams.register) {
      // if already confirmed redirect to register page
      if (_.contains($scope.errors, 'already_confirmed')) $location.path('/register');
      // if an address is already associated redirect to login
      else if (_.contains($scope.errors, 'address_associated')) $location.path('/login');

      $scope.step = 'two';
      $scope.name = $routeParams.name;
      $scope.email = $routeParams.email;
    } else {
      $scope.step = 'one';
    }

    $scope.oauth = function() {
      $scope.sending = false;
      window.location = Options.giveawayServer + Options.githubOauth;
    };

    $scope.step_two = function() {
      $.post(Options.giveawayServer + '/user/' + $routeParams.id, {
        action: 'confirm',
        register: $routeParams.register,
        name: $scope.name,
        email: $scope.email
      }, function(data) {
        $scope.step = 'three';
      });
    };

    $scope.step_three = function() {
      $scope.mode = 'welcome';
    };

    // hook into popup service
    $scope.developerProgram = function() {

    };

    $scope.getRipple = function() {
      $location.path('/getripple');
    };

  }]);
};

module.exports = SignupTab;<|endoftext|>


<commit_before>// ToolArea.js v3.4.0
/* global ui:false, getEL:false */

// メニュー描画/取得/html表示系
// toolareaオブジェクト
ui.toolarea = {
	items : null,		// ツールパネルのエレメント等を保持する
	captions : [],		// 言語指定を切り替えた際のキャプションを保持する

	//---------------------------------------------------------------------------
	// toolarea.reset()  ツールパネル・ボタン領域の初期設定を行う
	//---------------------------------------------------------------------------
	reset : function(){
		if(this.items===null){
			this.items = {};
			this.walkElement(getEL("usepanel"));
			this.walkElement(getEL("checkpanel"));
			this.walkElement(getEL('btnarea'));
		}
		ui.misc.displayByPid(getEL("checkpanel"));
		ui.misc.displayByPid(getEL("btnarea"));

		this.display();
	},

	//---------------------------------------------------------------------------
	// toolarea.walkElement()  エレメントを探索して領域の初期設定を行う
	//---------------------------------------------------------------------------
	walkElement : function(parent){
		var toolarea = this;
		ui.misc.walker(parent, function(el){
			if(el.nodeType===1){
				/* ツールパネル領域 */
				if(el.className==="config"){
					toolarea.items[ui.customAttr(el,"config")] = {el:el};
				}
				else if(el.className.match(/child/)){
					var parent = el.parentNode.parentNode, idname = ui.customAttr(parent,"config");
					var item = toolarea.items[idname];
					if(!item.children){ item.children=[];}
					item.children.push(el);

					pzpr.util.addEvent(el, "mousedown", toolarea, toolarea.toolclick);
				}
				else if(el.nodeName==="INPUT" && el.type==="checkbox"){
					var parent = el.parentNode, idname = ui.customAttr(parent,"config");
					if(!idname){ return;}
					toolarea.items[idname].checkbox=el;

					pzpr.util.addEvent(el, "click", toolarea, toolarea.toolclick);
				}

				/* ボタン領域 */
				var role = ui.customAttr(el,"buttonExec");
				if(!!role){
					pzpr.util.addEvent(el, (!pzpr.env.API.touchevent ? "click" : "mousedown"), toolarea, toolarea[role]);
				}
				role = ui.customAttr(el,"pressExec");
				if(!!role){
					var roles = role.split(/,/);
					pzpr.util.addEvent(el, "mousedown", toolarea, toolarea[roles[0]]);
					if(!!role[1]){
						pzpr.util.addEvent(el, "mouseup", toolarea, toolarea[roles[1]]);
						pzpr.util.addEvent(el, "mouseleave", toolarea, toolarea[roles[1]]);
						pzpr.util.addEvent(el, "touchcancel", toolarea, toolarea[roles[1]]);
					}
				}
			}
			else if(el.nodeType===3){
				if(el.data.match(/^__(.+)__(.+)__$/)){
					toolarea.captions.push({textnode:el, str_jp:RegExp.$1, str_en:RegExp.$2});
				}
			}
		});
	},

	//---------------------------------------------------------------------------
	// toolarea.display()    全てのラベルに対して文字列を設定する
	// toolarea.setdisplay() 管理パネルに表示する文字列を個別に設定する
	//---------------------------------------------------------------------------
	display : function(){
		/* ツールパネル領域 */
		/* -------------- */
		var mandisp  = (ui.menuconfig.get("toolarea") ? 'block' : 'none');
		getEL('usepanel').style.display = mandisp;
		getEL('checkpanel').style.display = mandisp;
		/* 経過時間の表示/非表示設定 */
		getEL('separator2').style.display = (ui.puzzle.playeronly ? "" : "none");
		getEL('timerpanel').style.display = (ui.puzzle.playeronly ? "block" : "none");

		for(var idname in this.items){ this.setdisplay(idname);}

		/* ボタン領域 */
		/* --------- */
		getEL('btnarea').style.display = "";
		pzpr.util.unselectable(getEL('btnarea'));

		this.setdisplay("operation");
		getEL('btnclear2').style.display  = (!ui.puzzle.board.disable_subclear ? "" : "none");
		getEL('btncircle').style.display  = (ui.puzzle.pid==='pipelinkr' ? "" : "none");
		getEL('btncolor').style.display   = (ui.puzzle.pid==='tentaisho' ? "" : "none");
		/* ボタンエリアの色分けボタンは、ツールパネル領域が消えている時に表示 */
		getEL('btnirowake').style.display = ((ui.puzzle.painter.irowake && !ui.menuconfig.get("toolarea")) ? "" : "none");
		getEL('btnirowakeblk').style.display = ((ui.puzzle.painter.irowakeblk && !ui.menuconfig.get("toolarea")) ? "" : "none");
		this.setdisplay("trialmode");

		/* 共通：キャプションの設定 */
		/* --------------------- */
		for(var i=0;i<this.captions.length;i++){
			var obj = this.captions[i];
			obj.textnode.data = ui.selectStr(obj.str_jp, obj.str_en);
		}
	},
	setdisplay : function(idname){
		if(idname==="operation"){
			var opemgr = ui.puzzle.opemgr;
			getEL('btnundo').style.color = (!opemgr.enableUndo ? 'silver' : '');
			getEL('btnredo').style.color = (!opemgr.enableRedo ? 'silver' : '');
		}
		else if(idname==="trialmode"){
			var trialstage = ui.puzzle.board.trialstage;
			getEL('btntrial').style.color       = ((trialstage>0) ? 'silver' : '');
			getEL('btntrialarea').style.display = ((trialstage>0) ? 'block' : 'none');

			getEL('btntrialr').style.display  = ((trialstage<=1) ? '' : 'none');
			getEL('btntrialr2').style.display = ((trialstage>1)  ? '' : 'none');
			getEL('btntrialra').style.display = ((trialstage>1)  ? '' : 'none');
		}
		else if(this.items===null || !this.items[idname]){
			/* DO NOTHING */
		}
		else if(ui.menuconfig.valid(idname)){
			var toolitem = this.items[idname];
			toolitem.el.style.display = "";

			/* 子要素の設定を行う */
			if(!!toolitem.children){
				var children = toolitem.children;
				var validval = (idname==='inputmode' ? ui.puzzle.mouse.getInputModeList() : null);
				for(var i=0;i<children.length;i++){
					var child = children[i], value = ui.customAttr(child,"value"), selected = (value===""+ui.menuconfig.get(idname));
					child.className = (selected ? "child childsel" : "child");
					child.style.display = ((validval===null || validval.indexOf(value)>=0) ? '' : 'none');
				}

				var disabled = null;
				if(idname==="inputmode"){ disabled = (validval.length===1);}
				if(disabled!==null){ toolitem.el.className = (!disabled ? "" : "disabled");}
			}
			/* チェックボックスの表記の設定 */
			else if(!!toolitem.checkbox){
				var check = toolitem.checkbox;
				if(!!check){ check.checked = ui.menuconfig.get(idname);}

				var disabled = null;
				if(idname==="keypopup"){ disabled = !ui.keypopup.paneltype[ui.puzzle.editmode?1:3];}
				if(idname==="bgcolor") { disabled = ui.puzzle.editmode;}
				if(idname==="passallcell"){ disabled = !ui.puzzle.editmode;}
				if(disabled!==null){ toolitem.checkbox.disabled = (!disabled ? "" : "true");}
			}

			if((idname==="disptype_pipelinkr") && !!getEL('btncircle')){
				getEL('btncircle').innerHTML = ((ui.menuconfig.get(idname)===1)?"○":"■");
			}
		}
		else if(!!this.items[idname]){
			this.items[idname].el.style.display = "none";
		}
	},

	//---------------------------------------------------------------------------
	// toolarea.toolclick()   ツールパネルの入力があった時、設定を変更する
	//---------------------------------------------------------------------------
	toolclick : function(e){
		var el = e.target, parent = el.parentNode;
		var idname = ui.customAttr(parent,"config")||ui.customAttr(parent.parentNode,"config"), value;
		if(!!this.items[idname].checkbox){ value = !!el.checked;}
		else                             { value = ui.customAttr(el,"value");}
		ui.menuconfig.set(idname, value);
	},

	//---------------------------------------------------------------------------
	// Canvas下にあるボタンが押された/放された時の動作
	//---------------------------------------------------------------------------
	answercheck : function(){ ui.menuarea.answercheck();},
	undo     : function(){ ui.undotimer.startButtonUndo();},
	undostop : function(){ ui.undotimer.stopButtonUndo();},
	redo     : function(){ ui.undotimer.startButtonRedo();},
	redostop : function(){ ui.undotimer.stopButtonRedo();},
	ansclear : function(){ ui.menuarea.ACconfirm();},
	subclear : function(){ ui.menuarea.ASconfirm();},
	irowake  : function(){ ui.puzzle.irowake();},
	encolorall : function(){ ui.puzzle.board.encolorall();}, /* 天体ショーのボタン */
	dropblocks : function(){ ui.puzzle.board.operate('drop');},
	resetblocks: function(){ ui.puzzle.board.operate('resetpos');},
	showgatenum: function(){ ui.puzzle.board.operate('showgatenumber');},
	hidegatenum: function(){ ui.puzzle.board.operate('hidegatenumber');},
	enterTrial : function(){ if(ui.puzzle.board.trialstage===0){ ui.puzzle.enterTrial();}},
	enterFurtherTrial : function(){ ui.puzzle.enterTrial();},
	acceptTrial : function(){ ui.puzzle.acceptTrial();},
	rejectTrial : function(){ ui.puzzle.rejectTrial();},
	rejectCurrentTrial : function(){ ui.puzzle.rejectCurrentTrial();},

	//---------------------------------------------------------------------------
	// toolarea.toggledisp()   帰ってきたパイプリンクでアイスと○などの表示切り替え時の処理を行う
	//---------------------------------------------------------------------------
	toggledisp : function(){
		var current = ui.menuconfig.get('disptype_pipelinkr');
		ui.menuconfig.set('disptype_pipelinkr', (current===1?2:1));
	}
};
<commit_msg>toolarea: Stop propagation to prevent search suggestion for Android Chrome<commit_after>// ToolArea.js v3.4.0
/* global ui:false, getEL:false */

// メニュー描画/取得/html表示系
// toolareaオブジェクト
ui.toolarea = {
	items : null,		// ツールパネルのエレメント等を保持する
	captions : [],		// 言語指定を切り替えた際のキャプションを保持する

	//---------------------------------------------------------------------------
	// toolarea.reset()  ツールパネル・ボタン領域の初期設定を行う
	//---------------------------------------------------------------------------
	reset : function(){
		if(this.items===null){
			this.items = {};
			this.walkElement(getEL("usepanel"));
			this.walkElement(getEL("checkpanel"));
			this.walkElement(getEL('btnarea'));
		}
		ui.misc.displayByPid(getEL("checkpanel"));
		ui.misc.displayByPid(getEL("btnarea"));

		this.display();
	},

	//---------------------------------------------------------------------------
	// toolarea.walkElement()  エレメントを探索して領域の初期設定を行う
	//---------------------------------------------------------------------------
	walkElement : function(parent){
		var toolarea = this;
		ui.misc.walker(parent, function(el){
			if(el.nodeType===1){
				/* ツールパネル領域 */
				if(el.className==="config"){
					toolarea.items[ui.customAttr(el,"config")] = {el:el};
				}
				else if(el.className.match(/child/)){
					var parent = el.parentNode.parentNode, idname = ui.customAttr(parent,"config");
					var item = toolarea.items[idname];
					if(!item.children){ item.children=[];}
					item.children.push(el);

					pzpr.util.addEvent(el, "mousedown", toolarea, toolarea.toolclick);
				}
				else if(el.nodeName==="INPUT" && el.type==="checkbox"){
					var parent = el.parentNode, idname = ui.customAttr(parent,"config");
					if(!idname){ return;}
					toolarea.items[idname].checkbox=el;

					pzpr.util.addEvent(el, "click", toolarea, toolarea.toolclick);
				}

				/* ボタン領域 */
				var role = ui.customAttr(el,"buttonExec");
				if(!!role){
					pzpr.util.addEvent(el, (!pzpr.env.API.touchevent ? "click" : "mousedown"), toolarea, toolarea[role]);
				}
				role = ui.customAttr(el,"pressExec");
				if(!!role){
					var roles = role.split(/,/);
					pzpr.util.addEvent(el, "mousedown", toolarea, toolarea[roles[0]]);
					if(!!role[1]){
						pzpr.util.addEvent(el, "mouseup", toolarea, toolarea[roles[1]]);
						pzpr.util.addEvent(el, "mouseleave", toolarea, toolarea[roles[1]]);
						pzpr.util.addEvent(el, "touchcancel", toolarea, toolarea[roles[1]]);
					}
				}
			}
			else if(el.nodeType===3){
				if(el.data.match(/^__(.+)__(.+)__$/)){
					toolarea.captions.push({textnode:el, str_jp:RegExp.$1, str_en:RegExp.$2});
				}
			}
		});
	},

	//---------------------------------------------------------------------------
	// toolarea.display()    全てのラベルに対して文字列を設定する
	// toolarea.setdisplay() 管理パネルに表示する文字列を個別に設定する
	//---------------------------------------------------------------------------
	display : function(){
		/* ツールパネル領域 */
		/* -------------- */
		var mandisp  = (ui.menuconfig.get("toolarea") ? 'block' : 'none');
		getEL('usepanel').style.display = mandisp;
		getEL('checkpanel').style.display = mandisp;
		/* 経過時間の表示/非表示設定 */
		getEL('separator2').style.display = (ui.puzzle.playeronly ? "" : "none");
		getEL('timerpanel').style.display = (ui.puzzle.playeronly ? "block" : "none");

		for(var idname in this.items){ this.setdisplay(idname);}

		/* ボタン領域 */
		/* --------- */
		getEL('btnarea').style.display = "";
		pzpr.util.unselectable(getEL('btnarea'));

		this.setdisplay("operation");
		getEL('btnclear2').style.display  = (!ui.puzzle.board.disable_subclear ? "" : "none");
		getEL('btncircle').style.display  = (ui.puzzle.pid==='pipelinkr' ? "" : "none");
		getEL('btncolor').style.display   = (ui.puzzle.pid==='tentaisho' ? "" : "none");
		/* ボタンエリアの色分けボタンは、ツールパネル領域が消えている時に表示 */
		getEL('btnirowake').style.display = ((ui.puzzle.painter.irowake && !ui.menuconfig.get("toolarea")) ? "" : "none");
		getEL('btnirowakeblk').style.display = ((ui.puzzle.painter.irowakeblk && !ui.menuconfig.get("toolarea")) ? "" : "none");
		this.setdisplay("trialmode");

		/* 共通：キャプションの設定 */
		/* --------------------- */
		for(var i=0;i<this.captions.length;i++){
			var obj = this.captions[i];
			obj.textnode.data = ui.selectStr(obj.str_jp, obj.str_en);
		}
	},
	setdisplay : function(idname){
		if(idname==="operation"){
			var opemgr = ui.puzzle.opemgr;
			getEL('btnundo').style.color = (!opemgr.enableUndo ? 'silver' : '');
			getEL('btnredo').style.color = (!opemgr.enableRedo ? 'silver' : '');
		}
		else if(idname==="trialmode"){
			var trialstage = ui.puzzle.board.trialstage;
			getEL('btntrial').style.color       = ((trialstage>0) ? 'silver' : '');
			getEL('btntrialarea').style.display = ((trialstage>0) ? 'block' : 'none');

			getEL('btntrialr').style.display  = ((trialstage<=1) ? '' : 'none');
			getEL('btntrialr2').style.display = ((trialstage>1)  ? '' : 'none');
			getEL('btntrialra').style.display = ((trialstage>1)  ? '' : 'none');
		}
		else if(this.items===null || !this.items[idname]){
			/* DO NOTHING */
		}
		else if(ui.menuconfig.valid(idname)){
			var toolitem = this.items[idname];
			toolitem.el.style.display = "";

			/* 子要素の設定を行う */
			if(!!toolitem.children){
				var children = toolitem.children;
				var validval = (idname==='inputmode' ? ui.puzzle.mouse.getInputModeList() : null);
				for(var i=0;i<children.length;i++){
					var child = children[i], value = ui.customAttr(child,"value"), selected = (value===""+ui.menuconfig.get(idname));
					child.className = (selected ? "child childsel" : "child");
					child.style.display = ((validval===null || validval.indexOf(value)>=0) ? '' : 'none');
				}

				var disabled = null;
				if(idname==="inputmode"){ disabled = (validval.length===1);}
				if(disabled!==null){ toolitem.el.className = (!disabled ? "" : "disabled");}
			}
			/* チェックボックスの表記の設定 */
			else if(!!toolitem.checkbox){
				var check = toolitem.checkbox;
				if(!!check){ check.checked = ui.menuconfig.get(idname);}

				var disabled = null;
				if(idname==="keypopup"){ disabled = !ui.keypopup.paneltype[ui.puzzle.editmode?1:3];}
				if(idname==="bgcolor") { disabled = ui.puzzle.editmode;}
				if(idname==="passallcell"){ disabled = !ui.puzzle.editmode;}
				if(disabled!==null){ toolitem.checkbox.disabled = (!disabled ? "" : "true");}
			}

			if((idname==="disptype_pipelinkr") && !!getEL('btncircle')){
				getEL('btncircle').innerHTML = ((ui.menuconfig.get(idname)===1)?"○":"■");
			}
		}
		else if(!!this.items[idname]){
			this.items[idname].el.style.display = "none";
		}
	},

	//---------------------------------------------------------------------------
	// toolarea.toolclick()   ツールパネルの入力があった時、設定を変更する
	//---------------------------------------------------------------------------
	toolclick : function(e){
		var el = e.target, parent = el.parentNode;
		var idname = ui.customAttr(parent,"config")||ui.customAttr(parent.parentNode,"config"), value;
		if(!!this.items[idname].checkbox){ value = !!el.checked;}
		else                             { value = ui.customAttr(el,"value");}
		ui.menuconfig.set(idname, value);
		e.preventDefault();
		e.stopPropagation();
	},

	//---------------------------------------------------------------------------
	// Canvas下にあるボタンが押された/放された時の動作
	//---------------------------------------------------------------------------
	answercheck : function(){ ui.menuarea.answercheck();},
	undo     : function(){ ui.undotimer.startButtonUndo();},
	undostop : function(){ ui.undotimer.stopButtonUndo();},
	redo     : function(){ ui.undotimer.startButtonRedo();},
	redostop : function(){ ui.undotimer.stopButtonRedo();},
	ansclear : function(){ ui.menuarea.ACconfirm();},
	subclear : function(){ ui.menuarea.ASconfirm();},
	irowake  : function(){ ui.puzzle.irowake();},
	encolorall : function(){ ui.puzzle.board.encolorall();}, /* 天体ショーのボタン */
	dropblocks : function(){ ui.puzzle.board.operate('drop');},
	resetblocks: function(){ ui.puzzle.board.operate('resetpos');},
	showgatenum: function(){ ui.puzzle.board.operate('showgatenumber');},
	hidegatenum: function(){ ui.puzzle.board.operate('hidegatenumber');},
	enterTrial : function(){ if(ui.puzzle.board.trialstage===0){ ui.puzzle.enterTrial();}},
	enterFurtherTrial : function(){ ui.puzzle.enterTrial();},
	acceptTrial : function(){ ui.puzzle.acceptTrial();},
	rejectTrial : function(){ ui.puzzle.rejectTrial();},
	rejectCurrentTrial : function(){ ui.puzzle.rejectCurrentTrial();},

	//---------------------------------------------------------------------------
	// toolarea.toggledisp()   帰ってきたパイプリンクでアイスと○などの表示切り替え時の処理を行う
	//---------------------------------------------------------------------------
	toggledisp : function(){
		var current = ui.menuconfig.get('disptype_pipelinkr');
		ui.menuconfig.set('disptype_pipelinkr', (current===1?2:1));
	}
};
<|endoftext|>


<commit_before>"use strict";

function setupMarkdownEditor()
{
    $( html.inputStoryCode ).markdown({
        autofocus: false,
        savable: false,
        fullscreen: false,
        hiddenButtons: ["cmdPreview", "cmdUrl", "cmdHeading"],
        additionalButtons: [[
            {
                name: "groupChapterPage",
                data: [
                    createMarkdownEditorButton(
                        "cmdChapter",
                        "New Chapter",
                        "glyphicon glyphicon-book",
                        "\n# ", "\n",
                        "Chapter Title" ),

                    createMarkdownEditorButton(
                        "cmdPage",
                        "New Page",
                        "glyphicon glyphicon-file",
                        "\n## ", "\n",
                        "Time: Location" ),
                ]
            },
            {
                name: "groupChoices",
                data: [
                    createMarkdownEditorButton(
                        "cmdChoiceLink",
                        "Choice Link",
                        "glyphicon glyphicon-share-alt",
                        "\n[identifier:", "](page)\n",
                        "link text" ),

                    createMarkdownEditorButton(
                        "cmdChoiceText",
                        "Choice-Dependent Text",
                        "glyphicon glyphicon-record",
                        "\n### Chose \"identifier\" on page\n", "\n###\n",
                        "This only shows when the given choice was made." ),
                ]
            }]]});
}

function createMarkdownEditorButton( name, title, icon, beforeSelection, afterSelection, defaultValue )
{
    return {
        name: name,
        toggle: false,
        title: title,
        icon: icon,
        callback: function(e){

            var chunk, cursor;
            var selected = e.getSelection();
            var content = e.getContent();

            // Prepend the chapter header.
            if ( selected.text ) {
                chunk = beforeSelection + selected.text + afterSelection;
            } else {
                chunk = beforeSelection + defaultValue + afterSelection;
            }

            // transform selection and set the cursor into chunked text
            e.replaceSelection(chunk);
            cursor = selected.start;

            // Set the cursor
            e.setSelection(cursor, cursor+chunk.length);
        }
    }
}
<commit_msg>Edited logic improved.<commit_after>"use strict";

function setupMarkdownEditor()
{
    $( html.inputStoryCode ).markdown({
        autofocus: false,
        savable: false,
        fullscreen: false,
        hiddenButtons: ["cmdPreview", "cmdUrl", "cmdHeading"],
        additionalButtons: [[
            {
                name: "groupChapterPage",
                data: [
                    createMarkdownEditorButton(
                        "cmdChapter",
                        "New Chapter",
                        "glyphicon glyphicon-book",
                        "# ", "\n",
                        "Chapter Title" ),

                    createMarkdownEditorButton(
                        "cmdPage",
                        "New Page",
                        "glyphicon glyphicon-file",
                        "## ", "\n",
                        "Time: Location" ),
                ]
            },
            {
                name: "groupChoices",
                data: [
                    createMarkdownEditorButton(
                        "cmdChoiceLink",
                        "Choice Link",
                        "glyphicon glyphicon-share-alt",
                        "[identifier:", "](page)\n",
                        "link text" ),

                    createMarkdownEditorButton(
                        "cmdChoiceText",
                        "Choice-Dependent Text",
                        "glyphicon glyphicon-record",
                        "### Chose \"identifier\" on page\n", "\n###\n",
                        "This only shows when the given choice was made." ),
                ]
            }]]});
}

function createMarkdownEditorButton( name, title, icon, beforeSelection, afterSelection, defaultValue )
{
    return {
        name: name,
        toggle: false,
        title: title,
        icon: icon,
        callback: function(e){

            var chunk, cursor;
            var selected = e.getSelection();
            var content = e.getContent();

            // If the first character in the selection is:
            //   - The first character in the text
            //   - Preceded by a newline
            //
            // Then it shouldn't have a newline prepended to it.
            // Otherwise it should.
            //
            var prependNewline = (
                selected.start === 0 || (
                    selected.start - 1 >= 0 &&
                    content[ selected.start - 1 ] === '\n' ) ) ?
                        "" : "\n";

            // Prepend the chapter header.
            if ( selected.text ) {
                chunk = prependNewline + beforeSelection +
                        selected.text + afterSelection;
            } else {
                chunk = prependNewline + beforeSelection +
                        defaultValue + afterSelection;
            }

            // transform selection and set the cursor into chunked text
            e.replaceSelection(chunk);
            cursor = selected.start;

            // Set the cursor
            e.setSelection(cursor, cursor+chunk.length);
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    /**
     * Search for a deep property in an object guided by a path. For example:
     *
     * obj = { a: { b: { c: 1 } } }
     * getPath(obj, "a")
     * > { b: { c: 1 } }
     * getPath(obj, "a.b")
     * > { c: 1 }
     * getPath(obj, "a.b.c")
     * > 1
     * getPath(obj, "a.d")
     * > null
     *
     * @param {object} obj
     * @param {string} path
     * @return {*} Returns the value found at the path, or null.
     */
    var getPath = function (obj, path) {
        if (typeof obj !== "object") {
            return null;
        }

        path.split(".").some(function (part) {
            if (obj.hasOwnProperty(part)) {
                obj = obj[part];
            } else {
                obj = null;
                return true;
            }
        });

        return obj;
    };

    exports.getPath = getPath;
});
<commit_msg>Return undefined on lookup failure as a sentinel<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    /**
     * Search for a deep property in an object guided by a path. For example:
     *
     * obj = { a: { b: { c: 1 } } }
     * getPath(obj, "a")
     * > { b: { c: 1 } }
     * getPath(obj, "a.b")
     * > { c: 1 }
     * getPath(obj, "a.b.c")
     * > 1
     * getPath(obj, "a.d")
     * > null
     *
     * @param {object} obj
     * @param {string} path
     * @return {*} Returns the value found at the path, or undefined.
     */
    var getPath = function (obj, path) {
        if (typeof obj !== "object") {
            return undefined;
        }

        path.split(".").some(function (part) {
            if (obj.hasOwnProperty(part)) {
                obj = obj[part];
            } else {
                obj = undefined;
                return true;
            }
        });

        return obj;
    };

    exports.getPath = getPath;
});
<|endoftext|>


<commit_before>var util = require('util'),
    Tab = require('../client/tab').Tab,
    rewriter = require('../util/jsonrewriter');

var CashinTab = function ()
{
  Tab.call(this);
};

util.inherits(CashinTab, Tab);

CashinTab.prototype.tabName = 'cashin';
CashinTab.prototype.mainMenu = 'wallet';

CashinTab.prototype.generateHtml = function ()
{
  return require('../../jade/tabs/cashin.jade')();
};

CashinTab.prototype.angular = function (module)
{
  module.controller('CashinCtrl', ['$scope', '$rootScope', 'rpId', 'rpNetwork', 'rpZipzap', 'rpTracker',
  function ($scope, $rootScope, $id, $network, $zipzap, $rpTracker)
  {
    if (!$id.loginStatus) return $id.goId();

    $scope.form = {};

    // TODO request results should be stored in blob
    $scope.$watch('address',function(address){
      if (!$rootScope.zipzap && address) {
        var account = $network.remote.account(address);

        // Get ZipZap account
        if ($scope.userBlob.data.zipzap && !$.isEmptyObject($scope.userBlob.data.zipzap)) {
          account.line('USD','rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q',function(err,line){
            $scope.$apply(function () {
              $scope.mode = line && line.limit > 0 ? 'details' : 'step2';
              $scope.zipzap = $scope.userBlob.data.zipzap;
              $scope.loading = false;
            })
          });
        }
        else {
          $scope.mode = 'step1';
        }
      }
    });

    // TODO ability to edit account details
    $scope.signup = function() {
      $scope.signupProgress = 'loading';

      // Create zipzap account, fund the ripple wallet
      $zipzap.register($id.account,$scope.form);
      $zipzap.request(function(response){
        var account = $network.remote.account($scope.address);

        $scope.signupProgress = false;
        if (response.ZipZapAcctNum) {
          // Add ZipZap account to user blob
          $scope.userBlob.data.zipzap = response;

          // Check trust to SnapSwap
          account.line('USD','rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q',function(err,line){
            $scope.$apply(function () {
              $scope.displaySignupForm = false;
              $scope.mode = line && line.limit > 0 ? 'details' : 'step2';
              $scope.zipzap = response;
              $scope.loading = false;
            })
          });

          $rpTracker.track('ZipZap register', {
            'Status': 'success'
          });
        } else {
          $scope.$apply(function () {
            if (response && response.Message) {
              $scope.error = {
                'code': response.Code,
                'message': response.Message,
                'verboseMessage': response.VerboseMessage
              };

              $rpTracker.track('ZipZap register', {
                'Status': 'error',
                'Message': response.VerboseMessage
              });
            } else {
              $scope.error = {
                'code': null,
                'message': 'Invalid form',
                'verboseMessage': 'Form is invalid, please make sure entered information is correct'
              };

              $rpTracker.track('ZipZap register', {
                'Status': 'error',
                'Message': 'Form is invalid'
              });
            }
          });
        }
      });
    };

    // Locate ZipZap payment centers
    $scope.locate = function() {
      $scope.locateStatus = 'loading';

      $zipzap.locate($scope.query);
      $zipzap.request(function(response){
        $scope.$apply(function () {
          $scope.locations = response;
          $scope.locateStatus = false;

          if (!response.PayCenters || (response.PayCenters && !response.PayCenters.length)) {
            $scope.locateStatus = 'notfound';

            $rpTracker.track('ZipZap locate payment center', {
              'Status': 'success'
            });
          } else {
            $rpTracker.track('ZipZap locate payment center', {
              'Status': 'notfound'
            });
          }
        });
      })
    }
  }]);

  module.directive('rpDob', function () {
    return {
      restrict: 'A',
      require: '?ngModel',
      link: function (scope, elm, attr, ctrl) {
        if (!ctrl) return;

        var pattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;

        var validator = function(value) {
          ctrl.$setValidity('rpDob', pattern.test(value));
          return value;
        };

        ctrl.$formatters.push(validator);
        ctrl.$parsers.unshift(validator);

        attr.$observe('rpDob', function() {
          validator(ctrl.$viewValue);
        });
      }
    };
  });
};

module.exports = CashinTab;
<commit_msg>Cashin: Show loading when checking for trust.<commit_after>var util = require('util'),
    Tab = require('../client/tab').Tab,
    rewriter = require('../util/jsonrewriter');

var CashinTab = function ()
{
  Tab.call(this);
};

util.inherits(CashinTab, Tab);

CashinTab.prototype.tabName = 'cashin';
CashinTab.prototype.mainMenu = 'wallet';

CashinTab.prototype.generateHtml = function ()
{
  return require('../../jade/tabs/cashin.jade')();
};

CashinTab.prototype.angular = function (module)
{
  module.controller('CashinCtrl', ['$scope', '$rootScope', 'rpId', 'rpNetwork', 'rpZipzap', 'rpTracker',
  function ($scope, $rootScope, $id, $network, $zipzap, $rpTracker)
  {
    if (!$id.loginStatus) return $id.goId();

    $scope.form = {};

    // TODO request results should be stored in blob
    $scope.$watch('address',function(address){
      if (!$rootScope.zipzap && address) {
        var account = $network.remote.account(address);

        $scope.loading = true;

        // Get ZipZap account
        if ($scope.userBlob.data.zipzap && !$.isEmptyObject($scope.userBlob.data.zipzap)) {
          account.line('USD','rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q',function(err,line){
            $scope.$apply(function () {
              $scope.mode = line && line.limit > 0 ? 'details' : 'step2';
              $scope.zipzap = $scope.userBlob.data.zipzap;
              $scope.loading = false;
            })
          });
        }
        else {
          $scope.mode = 'step1';
          $scope.loading = false;
        }
      }
    });

    // TODO ability to edit account details
    $scope.signup = function() {
      $scope.signupProgress = 'loading';

      // Create zipzap account, fund the ripple wallet
      $zipzap.register($id.account,$scope.form);
      $zipzap.request(function(response){
        var account = $network.remote.account($scope.address);

        $scope.signupProgress = false;
        if (response.ZipZapAcctNum) {
          // Add ZipZap account to user blob
          $scope.userBlob.data.zipzap = response;

          // Check trust to SnapSwap
          account.line('USD','rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q',function(err,line){
            $scope.$apply(function () {
              $scope.displaySignupForm = false;
              $scope.mode = line && line.limit > 0 ? 'details' : 'step2';
              $scope.zipzap = response;
              $scope.loading = false;
            })
          });

          $rpTracker.track('ZipZap register', {
            'Status': 'success'
          });
        } else {
          $scope.$apply(function () {
            if (response && response.Message) {
              $scope.error = {
                'code': response.Code,
                'message': response.Message,
                'verboseMessage': response.VerboseMessage
              };

              $rpTracker.track('ZipZap register', {
                'Status': 'error',
                'Message': response.VerboseMessage
              });
            } else {
              $scope.error = {
                'code': null,
                'message': 'Invalid form',
                'verboseMessage': 'Form is invalid, please make sure entered information is correct'
              };

              $rpTracker.track('ZipZap register', {
                'Status': 'error',
                'Message': 'Form is invalid'
              });
            }
          });
        }
      });
    };

    // Locate ZipZap payment centers
    $scope.locate = function() {
      $scope.locateStatus = 'loading';

      $zipzap.locate($scope.query);
      $zipzap.request(function(response){
        $scope.$apply(function () {
          $scope.locations = response;
          $scope.locateStatus = false;

          if (!response.PayCenters || (response.PayCenters && !response.PayCenters.length)) {
            $scope.locateStatus = 'notfound';

            $rpTracker.track('ZipZap locate payment center', {
              'Status': 'success'
            });
          } else {
            $rpTracker.track('ZipZap locate payment center', {
              'Status': 'notfound'
            });
          }
        });
      })
    }
  }]);

  module.directive('rpDob', function () {
    return {
      restrict: 'A',
      require: '?ngModel',
      link: function (scope, elm, attr, ctrl) {
        if (!ctrl) return;

        var pattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;

        var validator = function(value) {
          ctrl.$setValidity('rpDob', pattern.test(value));
          return value;
        };

        ctrl.$formatters.push(validator);
        ctrl.$parsers.unshift(validator);

        attr.$observe('rpDob', function() {
          validator(ctrl.$viewValue);
        });
      }
    };
  });
};

module.exports = CashinTab;
<|endoftext|>


<commit_before>import { isElement, isString, startsWith, toNode, toNodes } from './lang';

const voidElements = {
    area: true,
    base: true,
    br: true,
    col: true,
    embed: true,
    hr: true,
    img: true,
    input: true,
    keygen: true,
    link: true,
    menuitem: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true,
};
export function isVoidElement(element) {
    return toNodes(element).some((element) => voidElements[element.tagName.toLowerCase()]);
}

export function isVisible(element) {
    return toNodes(element).some(
        (element) => element.offsetWidth || element.offsetHeight || element.getClientRects().length
    );
}

export const selInput = 'input,select,textarea,button';
export function isInput(element) {
    return toNodes(element).some((element) => matches(element, selInput));
}

export const selFocusable = `${selInput},a[href],[tabindex]`;
export function isFocusable(element) {
    return matches(element, selFocusable);
}

export function parent(element) {
    element = toNode(element);
    return element && isElement(element.parentNode) && element.parentNode;
}

export function filter(element, selector) {
    return toNodes(element).filter((element) => matches(element, selector));
}

export function matches(element, selector) {
    return toNodes(element).some((element) => element.matches(selector));
}

export function closest(element, selector) {
    if (startsWith(selector, '>')) {
        selector = selector.slice(1);
    }

    return isElement(element)
        ? element.closest(selector)
        : toNodes(element)
              .map((element) => closest(element, selector))
              .filter(Boolean);
}

export function within(element, selector) {
    return isString(selector)
        ? matches(element, selector) || !!closest(element, selector)
        : element === selector || toNode(selector).contains(toNode(element));
}

export function parents(element, selector) {
    const elements = [];

    while ((element = parent(element))) {
        if (!selector || matches(element, selector)) {
            elements.push(element);
        }
    }

    return elements;
}

export function children(element, selector) {
    element = toNode(element);
    const children = element ? toNodes(element.children) : [];
    return selector ? filter(children, selector) : children;
}

export function index(element, ref) {
    return ref ? toNodes(element).indexOf(toNode(ref)) : children(parent(element)).indexOf(element);
}
<commit_msg>fix: parent() returns null if no parentElement is found<commit_after>import { isElement, isString, startsWith, toNode, toNodes } from './lang';

const voidElements = {
    area: true,
    base: true,
    br: true,
    col: true,
    embed: true,
    hr: true,
    img: true,
    input: true,
    keygen: true,
    link: true,
    menuitem: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true,
};
export function isVoidElement(element) {
    return toNodes(element).some((element) => voidElements[element.tagName.toLowerCase()]);
}

export function isVisible(element) {
    return toNodes(element).some(
        (element) => element.offsetWidth || element.offsetHeight || element.getClientRects().length
    );
}

export const selInput = 'input,select,textarea,button';
export function isInput(element) {
    return toNodes(element).some((element) => matches(element, selInput));
}

export const selFocusable = `${selInput},a[href],[tabindex]`;
export function isFocusable(element) {
    return matches(element, selFocusable);
}

export function parent(element) {
    return toNode(element)?.parentElement;
}

export function filter(element, selector) {
    return toNodes(element).filter((element) => matches(element, selector));
}

export function matches(element, selector) {
    return toNodes(element).some((element) => element.matches(selector));
}

export function closest(element, selector) {
    if (startsWith(selector, '>')) {
        selector = selector.slice(1);
    }

    return isElement(element)
        ? element.closest(selector)
        : toNodes(element)
              .map((element) => closest(element, selector))
              .filter(Boolean);
}

export function within(element, selector) {
    return isString(selector)
        ? matches(element, selector) || !!closest(element, selector)
        : element === selector || toNode(selector).contains(toNode(element));
}

export function parents(element, selector) {
    const elements = [];

    while ((element = parent(element))) {
        if (!selector || matches(element, selector)) {
            elements.push(element);
        }
    }

    return elements;
}

export function children(element, selector) {
    element = toNode(element);
    const children = element ? toNodes(element.children) : [];
    return selector ? filter(children, selector) : children;
}

export function index(element, ref) {
    return ref ? toNodes(element).indexOf(toNode(ref)) : children(parent(element)).indexOf(element);
}
<|endoftext|>


<commit_before>'use strict';

// exports

module.exports = {

  extends: [
    './2015.js',
  ],

  rules: {

    /**
     * Best Practices
     */

    'no-param-reassign': 0,
    'prefer-rest-params': 0,
    'prefer-spread': 1,

  },

};
<commit_msg>fix prefer-spread in node4<commit_after>'use strict';

// exports

module.exports = {

  extends: [
    './2015.js',
  ],

  rules: {

    /**
     * Best Practices
     */

    'no-param-reassign': 0,
    'prefer-rest-params': 0,
    'prefer-spread': 0,

  },

};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import classnames from 'classnames';
import _ from 'lodash';

export default class ContactTile extends Component {

  render() {
    const { props } = this;

    return (

            Contacts

    );
  }

}

window['contact-viewTile'] = ContactTile;
<commit_msg>contacts: add dark mode styles to tile<commit_after>import React, { Component } from 'react';
import classnames from 'classnames';
import _ from 'lodash';

export default class ContactTile extends Component {

  render() {
    const { props } = this;

    return (

            Contacts

    );
  }

}

window['contact-viewTile'] = ContactTile;
<|endoftext|>


<commit_before>/*
 Language: N1QL
 Contributors: Andres Täht <andres.taht@gmail.com>, Rene Saarsoo <nene@triin.net>
 Description: Couchbase query language
 */

function(hljs) {
  return {
    case_insensitive: true,
    illegal: /[]/,
    contains: [
      {
        beginKeywords:
          'build create index delete drop explain infer|10 insert merge prepare select update upsert|10',
        end: /;/, endsWithParent: true,
        keywords: {
          // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html
          keyword:
            'all alter analyze and any array as asc begin between binary boolean break bucket build by call ' +
            'case cast cluster collate collection commit connect continue correlate cover create database ' +
            'dataset datastore declare decrement delete derived desc describe distinct do drop each element ' +
            'else end every except exclude execute exists explain fetch first flatten for force from ' +
            'function grant group gsi having if ignore ilike in include increment index infer inline inner ' +
            'insert intersect into is join key keys keyspace known last left let letting like limit lsm map ' +
            'mapping matched materialized merge minus namespace nest not number object offset on ' +
            'option or order outer over parse partition password path pool prepare primary private privilege ' +
            'procedure public raw realm reduce rename return returning revoke right role rollback satisfies ' +
            'schema select self semi set show some start statistics string system then to transaction trigger ' +
            'truncate under union unique unknown unnest unset update upsert use user using validate value ' +
            'valued values via view when where while with within work xor',
          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html
          literal:
            'true false null missing|5',
          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html
          built_in:
            'array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length ' +
            'array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace ' +
            'array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull ' +
            'missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis ' +
            'date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str ' +
            'duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str ' +
            'str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode ' +
            'base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random ' +
            'round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values ' +
            'object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position ' +
            'regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper ' +
            'isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring'
        },
        contains: [
          {
            className: 'string',
            begin: '\'', end: '\'',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 0
          },
          {
            className: 'string',
            begin: '"', end: '"',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 0
          },
          {
            className: 'symbol',
            begin: '`', end: '`',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 2
          },
          hljs.C_NUMBER_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
}
<commit_msg>Remove empty illegal regex<commit_after>/*
 Language: N1QL
 Contributors: Andres Täht <andres.taht@gmail.com>, Rene Saarsoo <nene@triin.net>
 Description: Couchbase query language
 */

function(hljs) {
  return {
    case_insensitive: true,
    contains: [
      {
        beginKeywords:
          'build create index delete drop explain infer|10 insert merge prepare select update upsert|10',
        end: /;/, endsWithParent: true,
        keywords: {
          // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html
          keyword:
            'all alter analyze and any array as asc begin between binary boolean break bucket build by call ' +
            'case cast cluster collate collection commit connect continue correlate cover create database ' +
            'dataset datastore declare decrement delete derived desc describe distinct do drop each element ' +
            'else end every except exclude execute exists explain fetch first flatten for force from ' +
            'function grant group gsi having if ignore ilike in include increment index infer inline inner ' +
            'insert intersect into is join key keys keyspace known last left let letting like limit lsm map ' +
            'mapping matched materialized merge minus namespace nest not number object offset on ' +
            'option or order outer over parse partition password path pool prepare primary private privilege ' +
            'procedure public raw realm reduce rename return returning revoke right role rollback satisfies ' +
            'schema select self semi set show some start statistics string system then to transaction trigger ' +
            'truncate under union unique unknown unnest unset update upsert use user using validate value ' +
            'valued values via view when where while with within work xor',
          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html
          literal:
            'true false null missing|5',
          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html
          built_in:
            'array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length ' +
            'array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace ' +
            'array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull ' +
            'missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis ' +
            'date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str ' +
            'duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str ' +
            'str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode ' +
            'base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random ' +
            'round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values ' +
            'object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position ' +
            'regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper ' +
            'isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring'
        },
        contains: [
          {
            className: 'string',
            begin: '\'', end: '\'',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 0
          },
          {
            className: 'string',
            begin: '"', end: '"',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 0
          },
          {
            className: 'symbol',
            begin: '`', end: '`',
            contains: [hljs.BACKSLASH_ESCAPE],
            relevance: 2
          },
          hljs.C_NUMBER_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
}
<|endoftext|>