<commit_before>var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    /**
     * merge the properties of 2 objects
     */
    mixin = function (target, source) {
        Object.keys(source).forEach(function (key) {
            target[key] = source[key];
        });

        return target;
    },
    /**
     * shorthand for
     * Array.prototype.slice.call(object, ...)
     */
    slice = (function (slice) {
        return function (object) {
            return slice.apply(object, slice.call(arguments, 1));
        };
    }([].slice)),
    /**
     * A helper function to tell the world we are done flushing
     */
    tell = function (toEvent, accumulation, error, cares) {
        //if we have buffers send the array, otherwise be nice and .join('')
        accumulation = typeof accumulation[0] === 'string' ?
            accumulation.join('') :
            accumulation;

        //tell whoever cares
        (!error                                  ?
            typeof cares === 'function'     ?
            cares(null, accumulation)       :
            cares.emit(toEvent, accumulation)   :
            typeof cares === 'function'     ?
            cares(error, accumulation)      :
            cares.emit('error', error, accumulation));
    },
    /**
     * the main working function
     */
    engine = function (
        flushAccumulator,   //custom accumulator function (optional)
        flushEvent,         //the event to flush e.g. 'data'
        endEvent,           //the event that tells me I'm done flushing
        tellEvent,          //the event to notify with the accumulation
        waiting,            //things waiting for accumulation
        toEmpty             //the source of data
    ) {
        //strings are faster to accumulate with +=, but we don't know if we
        //have a buffer or a string at this point.  So we push to an array,
        //this way we can have only one isBuffer check at the end in tell()
        var accumulation         = [],
            //if we were passed an accumulator, use it
            _flushAccumulator    = typeof flushAccumulator === 'function' ?
                function () {
                    accumulation.push(flushAccumulator.apply(arguments));
                } :
                function (chunk) {
                    accumulation.push(chunk);
                };

//        console.dir({
//            'flushAccumulator' : flushAccumulator,   //custom accumulator function (optional)
//            'flushEvent'       : flushEvent,         //the event to flush e.g. 'data'
//            'endEvent'         : endEvent,           //the event that tells me I'm done flushing e.g. 'end'
//            'tellEvent'        : tellEvent,          //the event to notify with the accumulation e.g. 'success'
//            'waiting'          : waiting,            //things waiting for accumulation
//            'toEmpty'          : toEmpty             //things needing to be flushed
//        })

        //empty the "stream" and tell whoever cares
        if (toEmpty instanceof EventEmitter) {
            toEmpty.
                on(flushEvent, _flushAccumulator).
                on(endEvent, function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, null));
                    accumulation = [];
                }).
                on('error', function (ex) {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, ex));
                    accumulation = [];
                });
        } else if (typeof toEmpty === 'function') {
            try {
                _flushAccumulator(toEmpty());
                process.nextTick(function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, null));
                    accumulation = [];
                });
            } catch (ex) {
                process.nextTick(function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, ex));
                    accumulation = [];
                });
            }
        } else if (Array.isArray(toEmpty)) {
            //TODO nested accumulation?
        }
    },
    /**
     * the function to define our object (the things we are going to flush to)
     */
    to = function (
        flushEvent,         //curried from flush
        flushAccumulator,   //curried from flush
        endEvent,           //curried from "from"
        emptyFrom,          //curried from "from"
        event /*, destinationEmitter || callback, ...*/
    ) {

        var tellEvent = typeof event === 'string' ? event : 'success',
            waiting = slice(arguments, typeof event === 'string' ? 5 : 4),
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //we now know everything, pass it to the engine
        emptyFrom.forEach(
            engine.bind(
                null,
                flushAccumulator,
                flushEvent,
                endEvent,
                tellEvent,
                waiting
            )
        );

        //remove the helper functions to avoid strange situations (hopefully)
        delete self.from;
        delete self.to;
        delete self.toMe;

        //chain on
        return self;
    },
    /**
     * syntactic sugar for self.to(event, self)
     */
    toMe = function (
        flushEvent,         //curried from flush
        flushAccumulator,   //curried from flush
        endEvent,           //curried from "from"
        emptyFrom,          //curried from "from"
        event
    ) {

        var tellEvent = typeof event === 'string' ? event : 'success',
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //now we know everything, let to() do the work
        return to.call(
            self,
            flushEvent,
            flushAccumulator,
            endEvent,
            emptyFrom,
            tellEvent,
            self
        );
    },
    /**
     * function to define our subject (the things from whence we will flush)
     */
    from = function (
        flushEvent,       //curried from flush
        flushAccumulator, //curried from flush
        event /*,sourceEmitter || callback, ...*/
    ) {
        var endEvent = typeof event === 'string' ? event : 'end',
            emptyFrom = slice(arguments, typeof event === 'string' ? 3 : 2),
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //if I have nothing to empty, I can at least empty myself
        if (!emptyFrom.length) {
            emptyFrom[0] = self;
        }

        //TODO how to append multiple from's e.g. this.flush().from().from().from().to();
        //bind the additional information an let the user call to() when they are ready
        return mixin(self, {
            'to'    : to.bind(self, flushEvent, flushAccumulator, endEvent, emptyFrom),
            'toMe'  : toMe.bind(self, flushEvent, flushAccumulator, endEvent, emptyFrom)
        });
    },
    /**
     * primary entry point
     * The function to define our verb (the event and how we wish to accumulate)
     */
    flush = function (event, accumulator) {
        var flushEvent = typeof event === 'string' ? event : 'data',
            flushAccumulator =
                typeof accumulator === 'function' ?
                    accumulator :
                    typeof event === 'function' ?
                        event : null,
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //decorate the emitter and bind what we know
        return mixin(self, {
            'flush' : flush,
            'from'  : from.bind(self, flushEvent, flushAccumulator),
            'to'    : to.bind(self, flushEvent, flushAccumulator, 'end', [self]),
            'toMe'  : toMe.bind(self, flushEvent, flushAccumulator, 'end', [self])
        });
    };

//Expose
mixin(exports, {
    /**
     * Primary entry point
     * if the first parameter is an EventEmitter, I will decorate it
     * otherwise I'm looking for a String that will be the flush event
     * and an optional function to accumulate (if you want to do something
     * more complicated then pushing chunk onto an array)
     */
    'flush' : function (eventEmitter, event, accumulator) {
        if (eventEmitter instanceof EventEmitter) {
            return flush.call(eventEmitter, event, accumulator);
        } else {
            return flush(eventEmitter, event);
        }
    },
    /**
     * a function to decorate EventEmitter
     */
    'shine' : function (
        /*emitter, emitter, ...*/
    ) {
        slice(arguments).forEach(function (me) {
            if (me instanceof EventEmitter) {
                me.flush = flush;
            }
        });
    },
    /**
     * a function to add flush to EventEmitter.prototype
     */
    'shineAllEventEmitters' : function () {
        EventEmitter.prototype.flush = flush;
    }
});

<commit_msg>why do you have to call to and from with .apply if you only have an array?<commit_after>var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    /**
     * merge the properties of 2 objects
     */
    mixin = function (target, source) {
        Object.keys(source).forEach(function (key) {
            target[key] = source[key];
        });

        return target;
    },
    /**
     * shorthand for
     * Array.prototype.slice.call(object, ...)
     */
    slice = (function (slice) {
        return function (object) {
            return slice.apply(object, slice.call(arguments, 1));
        };
    }([].slice)),
    /**
     * A helper function to tell the world we are done flushing
     */
    tell = function (toEvent, accumulation, error, cares) {
        //if we have buffers send the array, otherwise be nice and .join('')
        accumulation = typeof accumulation[0] === 'string' ?
            accumulation.join('') :
            accumulation;

        //tell whoever cares
        (!error                                  ?
            typeof cares === 'function'     ?
            cares(null, accumulation)       :
            cares.emit(toEvent, accumulation)   :
            typeof cares === 'function'     ?
            cares(error, accumulation)      :
            cares.emit('error', error, accumulation));
    },
    /**
     * the main working function
     */
    engine = function (
        flushAccumulator,   //custom accumulator function (optional)
        flushEvent,         //the event to flush e.g. 'data'
        endEvent,           //the event that tells me I'm done flushing
        tellEvent,          //the event to notify with the accumulation
        waiting,            //things waiting for accumulation
        toEmpty             //the source of data
    ) {
        //strings are faster to accumulate with +=, but we don't know if we
        //have a buffer or a string at this point.  So we push to an array,
        //this way we can have only one isBuffer check at the end in tell()
        var accumulation         = [],
            //if we were passed an accumulator, use it
            _flushAccumulator    = typeof flushAccumulator === 'function' ?
                function () {
                    accumulation.push(flushAccumulator.apply(arguments));
                } :
                function (chunk) {
                    accumulation.push(chunk);
                };

//        console.dir({
//            'flushAccumulator' : flushAccumulator,   //custom accumulator function (optional)
//            'flushEvent'       : flushEvent,         //the event to flush e.g. 'data'
//            'endEvent'         : endEvent,           //the event that tells me I'm done flushing e.g. 'end'
//            'tellEvent'        : tellEvent,          //the event to notify with the accumulation e.g. 'success'
//            'waiting'          : waiting,            //things waiting for accumulation
//            'toEmpty'          : toEmpty             //things needing to be flushed
//        })

        //empty the "stream" and tell whoever cares
        if (toEmpty instanceof EventEmitter) {
            toEmpty.
                on(flushEvent, _flushAccumulator).
                on(endEvent, function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, null));
                    accumulation = [];
                }).
                on('error', function (ex) {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, ex));
                    accumulation = [];
                });
        } else if (typeof toEmpty === 'function') {
            try {
                _flushAccumulator(toEmpty());
                process.nextTick(function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, null));
                    accumulation = [];
                });
            } catch (ex) {
                process.nextTick(function () {
                    waiting.forEach(tell.bind(null, tellEvent, accumulation, ex));
                    accumulation = [];
                });
            }
        } else if (Array.isArray(toEmpty)) {
            //TODO nested accumulation?
        }
    },
    /**
     * the function to define our object (the things we are going to flush to)
     */
    to = function (
        flushEvent,         //curried from flush
        flushAccumulator,   //curried from flush
        endEvent,           //curried from "from"
        emptyFrom,          //curried from "from"
        event /*, destinationEmitter || callback, ...*/
    ) {

        var tellEvent = typeof event === 'string' ? event : 'success',
            waiting = slice(arguments, typeof event === 'string' ? 5 : 4),
            self = this instanceof EventEmitter ? this : new EventEmitter();

        if (waiting.length === 1 && Array.isArray(waiting[0])) {
            //if someone just passed an array, don't make then use .apply(
            waiting = waiting[0];
        }

        //we now know everything, pass it to the engine
        emptyFrom.forEach(
            engine.bind(
                null,
                flushAccumulator,
                flushEvent,
                endEvent,
                tellEvent,
                waiting
            )
        );

        //remove the helper functions to avoid strange situations (hopefully)
        delete self.from;
        delete self.to;
        delete self.toMe;

        //chain on
        return self;
    },
    /**
     * syntactic sugar for self.to(event, self)
     */
    toMe = function (
        flushEvent,         //curried from flush
        flushAccumulator,   //curried from flush
        endEvent,           //curried from "from"
        emptyFrom,          //curried from "from"
        event
    ) {

        var tellEvent = typeof event === 'string' ? event : 'success',
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //now we know everything, let to() do the work
        return to.call(
            self,
            flushEvent,
            flushAccumulator,
            endEvent,
            emptyFrom,
            tellEvent,
            self
        );
    },
    /**
     * function to define our subject (the things from whence we will flush)
     */
    from = function (
        flushEvent,       //curried from flush
        flushAccumulator, //curried from flush
        event /*,sourceEmitter || callback, ...*/
    ) {
        var endEvent = typeof event === 'string' ? event : 'end',
            emptyFrom = slice(arguments, typeof event === 'string' ? 3 : 2),
            self = this instanceof EventEmitter ? this : new EventEmitter();

        if (!emptyFrom.length) {
            //if I have nothing to empty, I can at least empty myself
            emptyFrom[0] = self;
        } else if (emptyFrom.length === 1 && Array.isArray(emptyFrom[0])) {
            //if someone just passed an array, don't make then use .apply(
            emptyFrom = emptyFrom[0];
        }

        //TODO how to append multiple from's e.g. this.flush().from().from().from().to();
        //bind the additional information an let the user call to() when they are ready
        return mixin(self, {
            'to'    : to.bind(self, flushEvent, flushAccumulator, endEvent, emptyFrom),
            'toMe'  : toMe.bind(self, flushEvent, flushAccumulator, endEvent, emptyFrom)
        });
    },
    /**
     * primary entry point
     * The function to define our verb (the event and how we wish to accumulate)
     */
    flush = function (event, accumulator) {
        var flushEvent = typeof event === 'string' ? event : 'data',
            flushAccumulator =
                typeof accumulator === 'function' ?
                    accumulator :
                    typeof event === 'function' ?
                        event : null,
            self = this instanceof EventEmitter ? this : new EventEmitter();

        //decorate the emitter and bind what we know
        return mixin(self, {
            'flush' : flush,
            'from'  : from.bind(self, flushEvent, flushAccumulator),
            'to'    : to.bind(self, flushEvent, flushAccumulator, 'end', [self]),
            'toMe'  : toMe.bind(self, flushEvent, flushAccumulator, 'end', [self])
        });
    };

//Expose
mixin(exports, {
    /**
     * Primary entry point
     * if the first parameter is an EventEmitter, I will decorate it
     * otherwise I'm looking for a String that will be the flush event
     * and an optional function to accumulate (if you want to do something
     * more complicated then pushing chunk onto an array)
     */
    'flush' : function (eventEmitter, event, accumulator) {
        if (eventEmitter instanceof EventEmitter) {
            return flush.call(eventEmitter, event, accumulator);
        } else {
            return flush(eventEmitter, event);
        }
    },
    /**
     * a function to decorate EventEmitter
     */
    'shine' : function (
        /*emitter, emitter, ...*/
    ) {
        slice(arguments).forEach(function (me) {
            if (me instanceof EventEmitter) {
                me.flush = flush;
            }
        });
    },
    /**
     * a function to add flush to EventEmitter.prototype
     */
    'shineAllEventEmitters' : function () {
        EventEmitter.prototype.flush = flush;
    }
});

<|endoftext|>


<commit_before>var fs = require('fs');

var error = require('./error');

var dscriptLibrary = {};

function initDScriptLibrary() {
    var dscriptFileNames = fs.readdirSync('./dscript');

    for (var i = 0; i < dscriptFileNames.length; i++) {
        var fileName = dscriptFileNames[i];

        if (fileName.match(/.+\.ds/)) {
            var script = fs.readFileSync('./dscript/' + fileName, 'utf-8');
            dscriptLibrary[fileName.replace(/\.ds/, "")] = script;
        }
    }
    console.log(dscriptLibrary);
}
initDScriptLibrary();

function getDScript(params, userId, callback) {
    function validate(params) {
        var checks = [];
        if (!params)
            checks.push('Parameter is required.');
        if (params && !params.funcName)
            checks.push('Function name is required.');
        if (checks.length > 0) {
            callback.onFailure(new error.InvalidParamsError(checks, null));
        }
        return true;
    }
    if (!validate(params))
        return;

    if (params.funcName in dscriptLibrary) {
        callback.onSuccess({ script: dscriptLibrary[params.funcName] });
    } else {
        callback.onFailure(new error.NotFoundError('Effective DScript does not exist'));
    }
}
exports.getDScript = getDScript;

<commit_msg>add js file<commit_after>var fs = require('fs');

var error = require('./error');

var dscriptLibrary = {};

function initDScriptLibrary() {
    var dscriptFileNames = fs.readdirSync('./dscript');

    for (var i = 0; i < dscriptFileNames.length; i++) {
        var fileName = dscriptFileNames[i];

        if (fileName.match(/.+\.ds/)) {
            var script = fs.readFileSync('./dscript/' + fileName, 'utf-8');
            dscriptLibrary[fileName.replace(/\.ds/, "")] = script;
        }
    }
}
initDScriptLibrary();

function getDScript(params, userId, callback) {
    function validate(params) {
        var checks = [];
        if (!params)
            checks.push('Parameter is required.');
        if (params && !params.funcName)
            checks.push('Function name is required.');
        if (checks.length > 0) {
            callback.onFailure(new error.InvalidParamsError(checks, null));
        }
        return true;
    }
    if (!validate(params))
        return;

    if (params.funcName in dscriptLibrary) {
        callback.onSuccess({ script: dscriptLibrary[params.funcName] });
    } else {
        callback.onFailure(new error.NotFoundError('Effective DScript does not exist'));
    }
}
exports.getDScript = getDScript;

<|endoftext|>


<commit_before>t.put('@FILENAME@', '<div>@CONTENTS@</div>');
<commit_msg>re-delete _all.js<commit_after><|endoftext|>


<commit_before>(function(window, $, app) {
    function Credits() {
        var getCreditsHolder = function() {
            return app.Page.get().find('[class*="creditsHolder"]');
        };

        var getCreditsWhole = function() {
            return app.Page.get().find('[class*="creditsWhole"]');
        };

        this.detectVisibility = function() {
            $('#creditsVisibility').prop('checked', ! getCreditsHolder().is('.creditsNone'));
        };

        this.detectContent = function() {
            var $editor = $('#creditsEditor');
            var text = getCreditsWhole().find('p').html();

            text = text.replace(/
/g, '\n');
            $editor.val(text);
        };

        this.getCredits = function() {
            return getCreditsWhole();
        };

        this.show = function() {
            this.getCredits().fadeIn(300);
        };

        this.hide = function() {
            this.getCredits().fadeOut(300);
        };

        this.togglePosition = function() {
            var $creditsHolder = getCreditsHolder();
            var $creditsWhole = getCreditsWhole();

            if ($creditsHolder.is('.creditsHolderRight')) {
                $creditsHolder.addClass('creditsHolderLeft').removeClass('creditsHolderRight');
                $creditsWhole.addClass('creditsWholeLeft').removeClass('creditsWholeRight');
            } else {
                $creditsHolder.addClass('creditsHolderRight').removeClass('creditsHolderLeft');
                $creditsWhole.addClass('creditsWholeRight').removeClass('creditsWholeLeft');
            }
        };

        this.toggleColor = function() {
            getCreditsHolder().toggleClass('white');
        };

        this.setVisibility = function(visible) {
            var $creditsHolder = getCreditsHolder();
            var $creditsWhole = getCreditsWhole();
            var $content = $creditsWhole.find('p');
            var content;

            if (visible) {
                $creditsHolder.removeClass('creditsNone');
                $creditsWhole.removeClass('creditsNone');

                if (! $content.html()) {
                    content = $content.data('content');
                    content = content ? content : 'Credits';

                    $content.html(content);
                }
            } else {
                $creditsHolder.addClass('creditsNone');
                $creditsWhole.addClass('creditsNone');

                content = $content.html();
                $content.html('').data('content', content);
            }
        };

        this.update = function(text) {
            text = text.replace(/\n/g, '
');
            text = text.replace(/\s{2,}/g, ' ');

            getCreditsWhole().find('p').html(text);
        };

        this.resizeCreditSpan = function (option){
             var $creditsWhole = getCreditsWhole();
            if (option = 'addSpan'){

            }

        }
    }

    app.registerModule('Credits', Credits);
})(window, jQuery, MagTool);
<commit_msg>credit text<commit_after>(function(window, $, app) {
    function Credits() {
        var getCreditsHolder = function() {
            return app.Page.get().find('[class*="creditsHolder"]');
        };

        var getCreditsWhole = function() {
            return app.Page.get().find('[class*="creditsWhole"]');
        };

        this.detectVisibility = function() {
            $('#creditsVisibility').prop('checked', ! getCreditsHolder().is('.creditsNone'));
        };

        this.detectContent = function() {
            var $editor = $('#creditsEditor');
            var text = getCreditsWhole().find('p').html();

            text = text.replace(/
/g, '\n');
            $editor.val(text);
        };

        this.getCredits = function() {
            return getCreditsWhole();
        };

        this.show = function() {
            this.getCredits().fadeIn(300);
        };

        this.hide = function() {
            this.getCredits().fadeOut(300);
        };

        this.togglePosition = function() {
            var $creditsHolder = getCreditsHolder();
            var $creditsWhole = getCreditsWhole();

            if ($creditsHolder.is('.creditsHolderRight')) {
                $creditsHolder.addClass('creditsHolderLeft').removeClass('creditsHolderRight');
                $creditsWhole.addClass('creditsWholeLeft').removeClass('creditsWholeRight');
            } else {
                $creditsHolder.addClass('creditsHolderRight').removeClass('creditsHolderLeft');
                $creditsWhole.addClass('creditsWholeRight').removeClass('creditsWholeLeft');
            }
        };

        this.toggleColor = function() {
            getCreditsHolder().toggleClass('white');
        };

        this.setVisibility = function(visible) {
            var $creditsHolder = getCreditsHolder();
            var $creditsWhole = getCreditsWhole();
            var $content = $creditsWhole.find('p');
            var content;

            if (visible) {
                $creditsHolder.removeClass('creditsNone');
                $creditsWhole.removeClass('creditsNone');

                if (! $content.html()) {
                    content = $content.data('content');
                    content = content ? content : 'Credits';

                    $content.html(content);
                }
            } else {
                $creditsHolder.addClass('creditsNone');
                $creditsWhole.addClass('creditsNone');

                content = $content.html();
                $content.html('').data('content', content);
            }
        };

        this.update = function(text) {
            text = text.replace(/\n/g, '
');
            text = text.replace(/\s{2,}/g, ' ');

            getCreditsWhole().find('p').html(text);
        };

        //        this.resizeCreditSpan = function(option) {
        //            var $creditsWhole = getCreditsWhole();
        //
        //            if (option == 'addSpan') {
        //            }
        //        };
    }

    app.registerModule('Credits', Credits);
})(window, jQuery, MagTool);
<|endoftext|>


<commit_before>exports.definition = {
	config: {

		adapter: {
			type: "sql",
			collection_name: "coordinates",
			db_file : "/dbKostervandring.sqlite"
		}
	},
	extendModel: function(Model) {
		_.extend(Model.prototype, {
			// extended functions and properties go here
		});

		return Model;
	},
	extendCollection: function(Collection) {
		_.extend(Collection.prototype, {
			// extended functions and properties go here
		});

		return Collection;
	}
};<commit_msg>fghjk<commit_after><|endoftext|>


<commit_before>(function(addon) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit-markdownarea", ["uikit"], function(){
            return jQuery.UIkit.markdownarea || addon(window, window.jQuery, window.jQuery.UIkit);
        });
    }

    if(window && window.jQuery && window.jQuery.UIkit) {
        addon(window, window.jQuery, window.jQuery.UIkit);
    }

})(function(global, $, UI){

    var Markdownarea = function(element, options){

        var $element = $(element);

        if($element.data("markdownarea")) return;

        this.element = $element;
        this.options = $.extend({}, Markdownarea.defaults, options);

        this.marked     = this.options.marked || marked;
        this.CodeMirror = this.options.CodeMirror || CodeMirror;

        this.marked.setOptions({
          gfm: true,
          tables: true,
          breaks: true,
          pedantic: false,
          sanitize: false,
          smartLists: true,
          smartypants: false,
          langPrefix: 'lang-'
        });

        this.init();

        this.element.data("markdownarea", this);
    };

    $.extend(Markdownarea.prototype, {

        init: function(){

            var $this = this, tpl = Markdownarea.template;

            tpl = tpl.replace(/\{\:lblPreview\}/g, this.options.lblPreview);
            tpl = tpl.replace(/\{\:lblCodeview\}/g, this.options.lblCodeview);

            this.markdownarea = $(tpl);
            this.content      = this.markdownarea.find(".uk-markdownarea-content");
            this.toolbar      = this.markdownarea.find(".uk-markdownarea-toolbar");
            this.preview      = this.markdownarea.find(".uk-markdownarea-preview").children().eq(0);
            this.code         = this.markdownarea.find(".uk-markdownarea-code");

            this.element.before(this.markdownarea).appendTo(this.code);

            this.editor = this.CodeMirror.fromTextArea(this.element[0], this.options.codemirror);

            this.editor.markdownarea = this;

            this.editor.on("change", (function(){
                var render = function(){

                    var value   = $this.editor.getValue();

                    $this.currentvalue  = String(value);

                    $this.element.trigger("markdownarea-before", [$this]);

                    $this.applyPlugins();

                    $this.marked($this.currentvalue, function (err, markdown) {

                      if (err) throw err;

                      $this.preview.html(markdown);
                      $this.element.val($this.editor.getValue()).trigger("markdownarea-update", [$this]);
                    });
                };
                render();
                return UI.Utils.debounce(render, 150);
            })());

            this.code.find(".CodeMirror").css("height", this.options.height);

            this._buildtoolbar();
            this.fit();

            $(window).on("resize", UI.Utils.debounce(function(){
                $this.fit();
            }, 200));

            var previewContainer = $this.preview.parent(),
                codeContent      = this.code.find('.CodeMirror-sizer'),
                codeScroll       = this.code.find('.CodeMirror-scroll').on('scroll',UI.Utils.debounce(function() {

                    if($this.markdownarea.attr("data-mode")=="tab") return;

                    // calc position
                    var codeHeight       = codeContent.height()   - codeScroll.height(),
                        previewHeight    = previewContainer[0].scrollHeight - previewContainer.height(),
                        ratio            = previewHeight / codeHeight,
                        previewPostition = codeScroll.scrollTop() * ratio;

                    // apply new scroll
                    previewContainer.scrollTop(previewPostition);
            }, 10));

            this.markdownarea.on("click", ".uk-markdown-button-markdown, .uk-markdown-button-preview", function(e){

                e.preventDefault();

                if($this.markdownarea.attr("data-mode")=="tab") {

                    $this.markdownarea.find(".uk-markdown-button-markdown, .uk-markdown-button-preview").removeClass("uk-active").filter(this).addClass("uk-active");

                    $this.activetab = $(this).hasClass("uk-markdown-button-markdown") ? "code":"preview";
                    $this.markdownarea.attr("data-active-tab", $this.activetab);
                }
            });

            this.preview.parent().css("height", this.code.height());
        },

        applyPlugins: function(){

            var $this   = this,
                plugins = Object.keys(Markdownarea.plugins),
                plgs    = Markdownarea.plugins;

            this.markers = {};

            if(plugins.length) {

                var lines = this.currentvalue.split("\n");

                plugins.forEach(function(name){
                    this.markers[name] = [];
                }, this);

                for(var line=0,max=lines.length;line<max;line++) {

                    (function(line){
                        plugins.forEach(function(name){

                            var i = 0;

                            lines[line] = lines[line].replace(plgs[name].identifier, function(){

                                var replacement =  plgs[name].cb({
                                    "area" : $this,
                                    "found": arguments,
                                    "line" : line,
                                    "pos"  : i++,
                                    "uid"  : [name, line, i, (new Date().getTime())+"RAND"+(Math.ceil(Math.random() *100000))].join('-'),
                                    "replace": function(strwith){
                                        var src   = this.area.editor.getLine(this.line),
                                            start = src.indexOf(this.found[0]);
                                            end   = start + this.found[0].length;

                                        this.area.editor.replaceRange(strwith, {"line": this.line, "ch":start}, {"line": this.line, "ch":end} );
                                    }
                                });

                                return replacement;
                            });
                        });
                    })(line);
                }

                this.currentvalue = lines.join("\n");

            }
        },

        _buildtoolbar: function(){

            if(!(this.options.toolbar && this.options.toolbar.length)) return;

            var $this = this, bar = [];

            this.options.toolbar.forEach(function(cmd){
                if(Markdownarea.commands[cmd]) {

                   var title = Markdownarea.commands[cmd].title ? Markdownarea.commands[cmd].title : cmd;

                   bar.push('
'+Markdownarea.commands[cmd].label+'
');

                   if(Markdownarea.commands[cmd].shortcut) {
                       $this.registerShortcut(Markdownarea.commands[cmd].shortcut, Markdownarea.commands[cmd].action);
                   }
                }
            });

            this.toolbar.html(bar.join("\n"));

            this.markdownarea.on("click", "a[data-markdownarea-cmd]", function(){
                var cmd = $(this).data("markdownareaCmd");

                if(cmd && Markdownarea.commands[cmd] && (!$this.activetab || $this.activetab=="code" || cmd=="fullscreen")) {
                    Markdownarea.commands[cmd].action.apply($this, [$this.editor])
                }

            });
        },

        fit: function() {

            var mode = this.options.mode;

            if(mode=="split" && this.markdownarea.width() < this.options.maxsplitsize) {
                mode = "tab";
            }

            if(mode=="tab") {

                if(!this.activetab) {
                    this.activetab = "code";
                    this.markdownarea.attr("data-active-tab", this.activetab);
                }

                this.markdownarea.find(".uk-markdown-button-markdown, .uk-markdown-button-preview").removeClass("uk-active")
                                 .filter(this.activetab=="code" ? '.uk-markdown-button-markdown':'.uk-markdown-button-preview').addClass("uk-active");

            }

            this.editor.refresh();
            this.preview.parent().css("height", this.code.height());

            this.markdownarea.attr("data-mode", mode);
        },

        registerShortcut: function(combination, callback){

            var $this = this;

            combination = $.isArray(combination) ? combination : [combination];

            for(var i=0,max=combination.length;i < max;i++) {
                var map = {};

                map[combination[i]] = function(){
                    callback.apply($this, [$this.editor]);
                };

                $this.editor.addKeyMap(map);
            }
        }
    });

    //jQuery plugin

    $.fn.markdownarea = function(options){

        return this.each(function(){

            var ele = $(this);

            if(!ele.data("markdownarea")) {
                var obj = new Markdownarea(ele, options);
            }
        });
    };

    var baseReplacer = function(replace, editor){
        var text     = editor.getSelection(),
            markdown = replace.replace('$1', text);

        editor.replaceSelection(markdown, 'end');
    };

    Markdownarea.commands = {
        "fullscreen": {
            "title"  : 'Fullscreen',
            "label"  : '',
            "action" : function(editor){

                editor.markdownarea.markdownarea.toggleClass("uk-markdownarea-fullscreen");

                var wrap = editor.getWrapperElement();

                if(editor.markdownarea.markdownarea.hasClass("uk-markdownarea-fullscreen")) {

                    editor.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, width: wrap.style.width, height: wrap.style.height};
                    wrap.style.width  = "";
                    wrap.style.height = editor.markdownarea.content.height()+"px";
                    document.documentElement.style.overflow = "hidden";

                } else {

                    document.documentElement.style.overflow = "";
                    var info = editor.state.fullScreenRestore;
                    wrap.style.width = info.width; wrap.style.height = info.height;
                    window.scrollTo(info.scrollLeft, info.scrollTop);
                }

                editor.refresh();
                editor.markdownarea.preview.parent().css("height", editor.markdownarea.code.height());
            }
        },

        "bold" : {
            "title"  : "Bold",
            "label"  : '',
            "shortcut": ['Ctrl-B', 'Cmd-B'],
            "action" : function(editor){

                baseReplacer("**$1**", editor);
            }
        },
        "italic" : {
            "title"  : "Italic",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("*$1*", editor);
            }
        },
        "strike" : {
            "title"  : "Strikethrough",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("~~$1~~", editor);
            }
        },
        "blockquote" : {
            "title"  : "Blockquote",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("> $1", editor);
            }
        },
        "link" : {
            "title"  : "Link",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("[$1](http://)", editor);
            }
        },
        "picture" : {
            "title"  : "Picture",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("![$1](http://)", editor);
            }
        },
        "listUl" : {
            "title"  : "Unordered List",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("* $1", editor);
            }
        },
        "listOl" : {
            "title"  : "Ordered List",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("1. $1", editor);
            }
        }
    }

    Markdownarea.defaults = {
        "mode"         : "split",
        "height"       : 500,
        "maxsplitsize" : 1000,
        "codemirror"   : { mode: 'gfm', tabMode: 'indent', tabindex: "2", lineWrapping: true, dragDrop: false },
        "toolbar"      : [ "bold", "italic", "strike", "link", "picture", "blockquote", "listUl", "listOl" ],
        "lblPreview"   : "Preview",
        "lblCodeview"  : "Markdown"
    };

    Markdownarea.template = '
' +
                                '
' +
                                    '

' +
                                    '
' +
                                        '
' +
                                            '
{:lblCodeview}
' +
                                            '
{:lblPreview}
' +
                                            '

' +
                                        '
' +
                                    '
' +
                                '
' +
                                '
' +
                                    '

' +
                                    '

' +
                                '
' +
                            '
';

    Markdownarea.plugins   = {};
    Markdownarea.addPlugin = function(name, identifier, callback) {
        Markdownarea.plugins[name] = {"identifier":identifier, "cb":callback};
    };

    UI["markdownarea"] = Markdownarea;

    // init code
    $(function() {

        $("textarea[data-uk-markdownarea]").each(function() {
            var area = $(this), obj;

            if (!area.data("markdownarea")) {
                obj = new Markdownarea(area, UI.Utils.options(area.attr("data-uk-markdownarea")));
            }
        });
    });

    return Markdownarea;
});<commit_msg>default arked options changed<commit_after>(function(addon) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit-markdownarea", ["uikit"], function(){
            return jQuery.UIkit.markdownarea || addon(window, window.jQuery, window.jQuery.UIkit);
        });
    }

    if(window && window.jQuery && window.jQuery.UIkit) {
        addon(window, window.jQuery, window.jQuery.UIkit);
    }

})(function(global, $, UI){

    var Markdownarea = function(element, options){

        var $element = $(element);

        if($element.data("markdownarea")) return;

        this.element = $element;
        this.options = $.extend({}, Markdownarea.defaults, options);

        this.marked     = this.options.marked || marked;
        this.CodeMirror = this.options.CodeMirror || CodeMirror;

        this.marked.setOptions({
          gfm           : true,
          tables        : true,
          breaks        : false,
          pedantic      : false,
          sanitize      : false,
          smartLists    : true,
          smartypants   : false,
          langPrefix    : 'lang-'
        });

        this.init();

        this.element.data("markdownarea", this);
    };

    $.extend(Markdownarea.prototype, {

        init: function(){

            var $this = this, tpl = Markdownarea.template;

            tpl = tpl.replace(/\{\:lblPreview\}/g, this.options.lblPreview);
            tpl = tpl.replace(/\{\:lblCodeview\}/g, this.options.lblCodeview);

            this.markdownarea = $(tpl);
            this.content      = this.markdownarea.find(".uk-markdownarea-content");
            this.toolbar      = this.markdownarea.find(".uk-markdownarea-toolbar");
            this.preview      = this.markdownarea.find(".uk-markdownarea-preview").children().eq(0);
            this.code         = this.markdownarea.find(".uk-markdownarea-code");

            this.element.before(this.markdownarea).appendTo(this.code);

            this.editor = this.CodeMirror.fromTextArea(this.element[0], this.options.codemirror);

            this.editor.markdownarea = this;

            this.editor.on("change", (function(){
                var render = function(){

                    var value   = $this.editor.getValue();

                    $this.currentvalue  = String(value);

                    $this.element.trigger("markdownarea-before", [$this]);

                    $this.applyPlugins();

                    $this.marked($this.currentvalue, function (err, markdown) {

                      if (err) throw err;

                      $this.preview.html(markdown);
                      $this.element.val($this.editor.getValue()).trigger("markdownarea-update", [$this]);
                    });
                };
                render();
                return UI.Utils.debounce(render, 150);
            })());

            this.code.find(".CodeMirror").css("height", this.options.height);

            this._buildtoolbar();
            this.fit();

            $(window).on("resize", UI.Utils.debounce(function(){
                $this.fit();
            }, 200));

            var previewContainer = $this.preview.parent(),
                codeContent      = this.code.find('.CodeMirror-sizer'),
                codeScroll       = this.code.find('.CodeMirror-scroll').on('scroll',UI.Utils.debounce(function() {

                    if($this.markdownarea.attr("data-mode")=="tab") return;

                    // calc position
                    var codeHeight       = codeContent.height()   - codeScroll.height(),
                        previewHeight    = previewContainer[0].scrollHeight - previewContainer.height(),
                        ratio            = previewHeight / codeHeight,
                        previewPostition = codeScroll.scrollTop() * ratio;

                    // apply new scroll
                    previewContainer.scrollTop(previewPostition);
            }, 10));

            this.markdownarea.on("click", ".uk-markdown-button-markdown, .uk-markdown-button-preview", function(e){

                e.preventDefault();

                if($this.markdownarea.attr("data-mode")=="tab") {

                    $this.markdownarea.find(".uk-markdown-button-markdown, .uk-markdown-button-preview").removeClass("uk-active").filter(this).addClass("uk-active");

                    $this.activetab = $(this).hasClass("uk-markdown-button-markdown") ? "code":"preview";
                    $this.markdownarea.attr("data-active-tab", $this.activetab);
                }
            });

            this.preview.parent().css("height", this.code.height());
        },

        applyPlugins: function(){

            var $this   = this,
                plugins = Object.keys(Markdownarea.plugins),
                plgs    = Markdownarea.plugins;

            this.markers = {};

            if(plugins.length) {

                var lines = this.currentvalue.split("\n");

                plugins.forEach(function(name){
                    this.markers[name] = [];
                }, this);

                for(var line=0,max=lines.length;line<max;line++) {

                    (function(line){
                        plugins.forEach(function(name){

                            var i = 0;

                            lines[line] = lines[line].replace(plgs[name].identifier, function(){

                                var replacement =  plgs[name].cb({
                                    "area" : $this,
                                    "found": arguments,
                                    "line" : line,
                                    "pos"  : i++,
                                    "uid"  : [name, line, i, (new Date().getTime())+"RAND"+(Math.ceil(Math.random() *100000))].join('-'),
                                    "replace": function(strwith){
                                        var src   = this.area.editor.getLine(this.line),
                                            start = src.indexOf(this.found[0]);
                                            end   = start + this.found[0].length;

                                        this.area.editor.replaceRange(strwith, {"line": this.line, "ch":start}, {"line": this.line, "ch":end} );
                                    }
                                });

                                return replacement;
                            });
                        });
                    })(line);
                }

                this.currentvalue = lines.join("\n");

            }
        },

        _buildtoolbar: function(){

            if(!(this.options.toolbar && this.options.toolbar.length)) return;

            var $this = this, bar = [];

            this.options.toolbar.forEach(function(cmd){
                if(Markdownarea.commands[cmd]) {

                   var title = Markdownarea.commands[cmd].title ? Markdownarea.commands[cmd].title : cmd;

                   bar.push('
'+Markdownarea.commands[cmd].label+'
');

                   if(Markdownarea.commands[cmd].shortcut) {
                       $this.registerShortcut(Markdownarea.commands[cmd].shortcut, Markdownarea.commands[cmd].action);
                   }
                }
            });

            this.toolbar.html(bar.join("\n"));

            this.markdownarea.on("click", "a[data-markdownarea-cmd]", function(){
                var cmd = $(this).data("markdownareaCmd");

                if(cmd && Markdownarea.commands[cmd] && (!$this.activetab || $this.activetab=="code" || cmd=="fullscreen")) {
                    Markdownarea.commands[cmd].action.apply($this, [$this.editor])
                }

            });
        },

        fit: function() {

            var mode = this.options.mode;

            if(mode=="split" && this.markdownarea.width() < this.options.maxsplitsize) {
                mode = "tab";
            }

            if(mode=="tab") {

                if(!this.activetab) {
                    this.activetab = "code";
                    this.markdownarea.attr("data-active-tab", this.activetab);
                }

                this.markdownarea.find(".uk-markdown-button-markdown, .uk-markdown-button-preview").removeClass("uk-active")
                                 .filter(this.activetab=="code" ? '.uk-markdown-button-markdown':'.uk-markdown-button-preview').addClass("uk-active");

            }

            this.editor.refresh();
            this.preview.parent().css("height", this.code.height());

            this.markdownarea.attr("data-mode", mode);
        },

        registerShortcut: function(combination, callback){

            var $this = this;

            combination = $.isArray(combination) ? combination : [combination];

            for(var i=0,max=combination.length;i < max;i++) {
                var map = {};

                map[combination[i]] = function(){
                    callback.apply($this, [$this.editor]);
                };

                $this.editor.addKeyMap(map);
            }
        }
    });

    //jQuery plugin

    $.fn.markdownarea = function(options){

        return this.each(function(){

            var ele = $(this);

            if(!ele.data("markdownarea")) {
                var obj = new Markdownarea(ele, options);
            }
        });
    };

    var baseReplacer = function(replace, editor){
        var text     = editor.getSelection(),
            markdown = replace.replace('$1', text);

        editor.replaceSelection(markdown, 'end');
    };

    Markdownarea.commands = {
        "fullscreen": {
            "title"  : 'Fullscreen',
            "label"  : '',
            "action" : function(editor){

                editor.markdownarea.markdownarea.toggleClass("uk-markdownarea-fullscreen");

                var wrap = editor.getWrapperElement();

                if(editor.markdownarea.markdownarea.hasClass("uk-markdownarea-fullscreen")) {

                    editor.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, width: wrap.style.width, height: wrap.style.height};
                    wrap.style.width  = "";
                    wrap.style.height = editor.markdownarea.content.height()+"px";
                    document.documentElement.style.overflow = "hidden";

                } else {

                    document.documentElement.style.overflow = "";
                    var info = editor.state.fullScreenRestore;
                    wrap.style.width = info.width; wrap.style.height = info.height;
                    window.scrollTo(info.scrollLeft, info.scrollTop);
                }

                editor.refresh();
                editor.markdownarea.preview.parent().css("height", editor.markdownarea.code.height());
            }
        },

        "bold" : {
            "title"  : "Bold",
            "label"  : '',
            "shortcut": ['Ctrl-B', 'Cmd-B'],
            "action" : function(editor){

                baseReplacer("**$1**", editor);
            }
        },
        "italic" : {
            "title"  : "Italic",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("*$1*", editor);
            }
        },
        "strike" : {
            "title"  : "Strikethrough",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("~~$1~~", editor);
            }
        },
        "blockquote" : {
            "title"  : "Blockquote",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("> $1", editor);
            }
        },
        "link" : {
            "title"  : "Link",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("[$1](http://)", editor);
            }
        },
        "picture" : {
            "title"  : "Picture",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("![$1](http://)", editor);
            }
        },
        "listUl" : {
            "title"  : "Unordered List",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("* $1", editor);
            }
        },
        "listOl" : {
            "title"  : "Ordered List",
            "label"  : '',
            "action" : function(editor){
                baseReplacer("1. $1", editor);
            }
        }
    }

    Markdownarea.defaults = {
        "mode"         : "split",
        "height"       : 500,
        "maxsplitsize" : 1000,
        "codemirror"   : { mode: 'gfm', tabMode: 'indent', tabindex: "2", lineWrapping: true, dragDrop: false },
        "toolbar"      : [ "bold", "italic", "strike", "link", "picture", "blockquote", "listUl", "listOl" ],
        "lblPreview"   : "Preview",
        "lblCodeview"  : "Markdown"
    };

    Markdownarea.template = '
' +
                                '
' +
                                    '

' +
                                    '
' +
                                        '
' +
                                            '
{:lblCodeview}
' +
                                            '
{:lblPreview}
' +
                                            '

' +
                                        '
' +
                                    '
' +
                                '
' +
                                '
' +
                                    '

' +
                                    '

' +
                                '
' +
                            '
';

    Markdownarea.plugins   = {};
    Markdownarea.addPlugin = function(name, identifier, callback) {
        Markdownarea.plugins[name] = {"identifier":identifier, "cb":callback};
    };

    UI["markdownarea"] = Markdownarea;

    // init code
    $(function() {

        $("textarea[data-uk-markdownarea]").each(function() {
            var area = $(this), obj;

            if (!area.data("markdownarea")) {
                obj = new Markdownarea(area, UI.Utils.options(area.attr("data-uk-markdownarea")));
            }
        });
    });

    return Markdownarea;
});<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import { View, Text, ScrollView, TouchableOpacity, StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { navigatePush } from '../redux/modules/routing';

class Demos extends Component {
  render() {
    const { handlePress } = this.props;

    return (
      <ScrollView style={styles.container}>

        <View style={[styles.row, styles.header]}>
          <Text style={styles.headerText}>use D3Path/D3Shape</Text>
        </View>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('SVGBasic')}>
          <Text>react-native-svg</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Scale')}>
          <Text>D3 Scale</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Shape')}>
          <Text>D3 Shape</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Ticks')}>
          <Text>Draw the grid line</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('CustomStockChart')}>
          <Text>Custom Stock Chart</Text>
        </TouchableOpacity>

        <View style={[styles.row, styles.header]}>
          <Text style={styles.headerText}>use formidable chart</Text>
        </View>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('BasicLineChart')}>
          <Text>Basic Line Chart</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('ChartWithAxis')}>
          <Text>Line Chart with Axis</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('MultipleAxes')}>
          <Text>Line Chart with multiple Axes</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('VolumeChart')}>
          <Text>Volume Chart</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('StockChartWithVolume')}>
          <Text>Stock Chart with Volume</Text>
        </TouchableOpacity>
      </ScrollView>
    );
  }
}

Demos.propTypes = {
  handlePress: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    backgroundColor: 'rgb(234, 234, 234)',
  },
  headerText: {
    fontSize: 18
  },
  row: {
    height: 40,
    paddingLeft: 20,
    justifyContent: 'center'
  }
});

const mapDispatchToProps = (dispatch) => {
  return {
    handlePress: (key) => {
      dispatch(navigatePush({ key }));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(Demos);
<commit_msg>update page title<commit_after>import React, { PropTypes, Component } from 'react';
import { View, Text, ScrollView, TouchableOpacity, StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { navigatePush } from '../redux/modules/routing';

class Demos extends Component {
  render() {
    const { handlePress } = this.props;

    return (
      <ScrollView style={styles.container}>

        <View style={[styles.row, styles.header]}>
          <Text style={styles.headerText}>use D3Path/D3Shape</Text>
        </View>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('SVGBasic')}>
          <Text>SVG Basics</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Scale')}>
          <Text>D3 Scale</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Shape')}>
          <Text>D3 Shape</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('D3Ticks')}>
          <Text>Draw the grid line</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('CustomStockChart')}>
          <Text>Custom Stock Chart</Text>
        </TouchableOpacity>

        <View style={[styles.row, styles.header]}>
          <Text style={styles.headerText}>use formidable chart</Text>
        </View>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('BasicLineChart')}>
          <Text>Basic Line Chart</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('ChartWithAxis')}>
          <Text>Line Chart with Axis</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('MultipleAxes')}>
          <Text>Line Chart with multiple Axes</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.row} onPress={() => handlePress('VolumeChart')}>
          <Text>Volume Chart</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.row} onPress={() => handlePress('StockChartWithVolume')}>
          <Text>Stock Chart with Volume</Text>
        </TouchableOpacity>
      </ScrollView>
    );
  }
}

Demos.propTypes = {
  handlePress: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    backgroundColor: 'rgb(234, 234, 234)',
  },
  headerText: {
    fontSize: 18
  },
  row: {
    height: 40,
    paddingLeft: 20,
    justifyContent: 'center'
  }
});

const mapDispatchToProps = (dispatch) => {
  return {
    handlePress: (key) => {
      dispatch(navigatePush({ key }));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(Demos);
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import DocsArticle from './DocsArticle';
import Query from 'grommet-index/utils/Query';

export default class QueryDoc extends Component {

  render () {
    let query = Query('(a OR b) AND (n:v OR n:w) "big deal" NOT 01:23:45:67:89:ab 2016-01-31T16:45:46Z');
    let errorQuery = Query('a b "');

    return (
      <DocsArticle title="Query" colorIndex="neutral-3">

A query descriptor. Query can be used for:

User typed text containing simple text terms, which
            might be quoted. For
            instance, name or 'search term'.

User typed text containing faceted filter terms. For
            instance, name:value.

Combined text terms, faceted filters, and boolean logic. The
            boolean logic available
            includes AND, OR, NOT, and
            parentheses for grouping.

Constructor

(string)

Initializes a Query with the specified query string.

Methods

clone ()

Returns a new Query instance identical to this one.

error ()

Returns a text description of any syntactical errors.

set (string)

Sets the query string.

toString ()

Gets the query string.

tree ()

Returns a boolean logic tree. This permits syntax highlighting
              and programmatic processing. Connecting nodes are of the
              form {"{ op: and|or, left: , right: }"}. Leaf nodes
              are of the form {"{ text: , name:, value: , not: true|false }"}

Examples

Boolean Logic

            {`let query = Query('${query.toString()}');\n`}
            {'query.toString();\n'}
            {'>> ' + query.toString() + "\n"}
            {'query.error();\n'}
            {'>> ' + query.error() + "\n"}
            {'query.tree();\n'}
            {'>> ' + JSON.stringify(query.tree(), null, '  ')}

Syntax error

            {`let errorQuery = Query('${errorQuery.toString()}');\n`}
            {'errorQuery.toString();\n'}
            {'>> ' + errorQuery.toString() + "\n"}
            {'errorQuery.error();\n'}
            {'>> ' + errorQuery.error() + "\n"}

      </DocsArticle>
    );
  }
}
<commit_msg>Updated Query documentation.<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import DocsArticle from './DocsArticle';
import Query from 'grommet-index/utils/Query';

export default class QueryDoc extends Component {

  render () {
    let query = new Query('(a OR b) AND (n:v OR n:w) "big deal" NOT 01:23:45:67:89:ab 2016-01-31T16:45:46Z');
    let errorQuery = new Query('a b "');

    return (
      <DocsArticle title="Query" colorIndex="neutral-3">

A query descriptor. Query can be used for:

User typed text containing simple text terms, which
            might be quoted. For
            instance, name or 'search term'.

User typed text containing faceted filter terms. For
            instance, name:value.

Combined text terms, faceted filters, and boolean logic. The
            boolean logic available
            includes AND, OR, NOT, and
            parentheses for grouping.

Constructor

new Query(string)

Initializes a Query with the specified query string.

Methods

error ()

Returns a text description of any syntactical errors.

set (string)

Sets the query string.

toString ()

Gets the query string.

tree ()

Returns a boolean logic tree. This permits syntax highlighting
              and programmatic processing. Connecting nodes are of the
              form {"{ op: and|or, left: , right: }"}. Leaf nodes
              are of the form {"{ text: , name:, value: , not: true|false }"}

Examples

Boolean Logic

            {`let query = new Query('${query.toString()}');\n`}
            {'query.toString();\n'}
            {'>> ' + query.toString() + "\n"}
            {'query.error();\n'}
            {'>> ' + query.error() + "\n"}
            {'query.tree();\n'}
            {'>> ' + JSON.stringify(query.tree(), null, '  ')}

Syntax error

            {`let errorQuery = Query('${errorQuery.toString()}');\n`}
            {'errorQuery.toString();\n'}
            {'>> ' + errorQuery.toString() + "\n"}
            {'errorQuery.error();\n'}
            {'>> ' + errorQuery.error() + "\n"}

      </DocsArticle>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * FACTFinder_Tracking
 *
 * @category Mage
 * @package FACTFinder_Tracking
 * @author Flagbit Magento Team <magento@flagbit.de>
 * @copyright Copyright (c) 2015 Flagbit GmbH & Co. KG
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @link http://www.flagbit.de
 *
 */

var FactfinderTracking = Class.create({
	url:  null,
	data: null,
	classname: null,
	mapping: null,
	request: null,
	regex: new RegExp(/product\/([0-9]+)\//),
	asynchronous: true,
	initialize: function(classname, data, mapping, url, asynchronous) {
		this.classname = classname;
		this.data = data;
		this.mapping = mapping;
		this.url = url;
		if(typeof asynchronous !== 'undefined')
			this.asynchronous = asynchronous;
	},

	init: function() {
		$$(this.classname+' a',this.classname+' button').each(function(element) {
			this.mapping.each(function(pair, index) {
				if(element.readAttribute('href') && element.readAttribute('href').indexOf(pair.key) >= 0){
					return this.prepareElement(element, pair.value, 'click');
				}
				if(element.readAttribute('onclick') && element.readAttribute('onclick').indexOf(pair.key) >= 0){
					return this.prepareElement(element, pair.value, 'click');
				}
			}.bind(this));

			if(element.readAttribute('href')) {
				var match = this.regex.exec(element.readAttribute('href'));
				if(match && match[1]) {
					return this.prepareElement(element, match[1], 'click');
				}
			}

			if(element.readAttribute('onclick')) {
				var match = this.regex.exec(element.readAttribute('onclick'));
				if(match && match[1]) {
					return this.prepareElement(element, match[1], 'click');
				}
			}
		}.bind(this));
	},

	prepareElement: function(element, id, eventType) {
		Event.observe(element, 'click', function(event) {
			this.recordRequest(id, eventType);
		}.bind(this));
	},

	recordRequest: function(id, eventType) {

		var data = this.data.get(id);

		this.request = new Ajax.Request(this.url, {
			asynchronous: this.asynchronous,
			method: 'post',
			parameters: data
		});
		return false;
	}
});<commit_msg>[+TASK] Replace tabs with 4 spaces in tracking.js<commit_after>/**
 * FACTFinder_Tracking
 *
 * @category Mage
 * @package FACTFinder_Tracking
 * @author Flagbit Magento Team <magento@flagbit.de>
 * @copyright Copyright (c) 2015 Flagbit GmbH & Co. KG
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @link http://www.flagbit.de
 *
 */

var FactfinderTracking = Class.create({
    url:  null,
    data: null,
    classname: null,
    mapping: null,
    request: null,
    regex: new RegExp(/product\/([0-9]+)\//),
    asynchronous: true,
    initialize: function(classname, data, mapping, url, asynchronous) {
        this.classname = classname;
        this.data = data;
        this.mapping = mapping;
        this.url = url;
        if(typeof asynchronous !== 'undefined')
            this.asynchronous = asynchronous;
    },

    init: function() {
        $$(this.classname+' a',this.classname+' button').each(function(element) {
            this.mapping.each(function(pair, index) {
                if(element.readAttribute('href') && element.readAttribute('href').indexOf(pair.key) >= 0){
                    return this.prepareElement(element, pair.value, 'click');
                }
                if(element.readAttribute('onclick') && element.readAttribute('onclick').indexOf(pair.key) >= 0){
                    return this.prepareElement(element, pair.value, 'click');
                }
            }.bind(this));

            if(element.readAttribute('href')) {
                var match = this.regex.exec(element.readAttribute('href'));
                if(match && match[1]) {
                    return this.prepareElement(element, match[1], 'click');
                }
            }

            if(element.readAttribute('onclick')) {
                var match = this.regex.exec(element.readAttribute('onclick'));
                if(match && match[1]) {
                    return this.prepareElement(element, match[1], 'click');
                }
            }
        }.bind(this));
    },

    prepareElement: function(element, id, eventType) {
        Event.observe(element, 'click', function(event) {
            this.recordRequest(id, eventType);
        }.bind(this));
    },

    recordRequest: function(id, eventType) {

        var data = this.data.get(id);

        this.request = new Ajax.Request(this.url, {
            asynchronous: this.asynchronous,
            method: 'post',
            parameters: data
        });
        return false;
    }
});
<|endoftext|>


<commit_before>describe('smallestSubstring', function() {

  var exampleArr = ['x', 'y', 'z'];
  var exampleStr = 'xyyzyzyx';

  it('should return a string', function() {
    var result = smallestSubstring(exampleArr, exampleStr);

    expect(result).to.be.a('string');
  });

  it('should handle example case', function() {
    var result = smallestSubstring(exampleArr, exampleStr);

    expect(result).to.be.equal('zyx');
  });

  it('should return first substring if there are multiple shortest', function() {
    var arr = ['a', 'b', 'c'];
    var str = 'ccbcab'
    var result = smallestSubstring(arr, str);

    expect(result).to.be.equal('bca');
  });
});
<commit_msg>(fix) Add missing semicolon in smallestSubstringSpec<commit_after>describe('smallestSubstring', function() {

  var exampleArr = ['x', 'y', 'z'];
  var exampleStr = 'xyyzyzyx';

  it('should return a string', function() {
    var result = smallestSubstring(exampleArr, exampleStr);

    expect(result).to.be.a('string');
  });

  it('should handle example case', function() {
    var result = smallestSubstring(exampleArr, exampleStr);

    expect(result).to.be.equal('zyx');
  });

  it('should return first substring if there are multiple shortest', function() {
    var arr = ['a', 'b', 'c'];
    var str = 'ccbcab';
    var result = smallestSubstring(arr, str);

    expect(result).to.be.equal('bca');
  });
});
<|endoftext|>


<commit_before>

var fs = require('fs');
var open = require('open-uri');
var Hitch = require('hitch');
require('./inflector');
var walk = require('./find');
var load = new Hitch();

var JSONLY = new Class({

	Implements: Options,

	options: {
		uri: false,
		path: false,
		endpoints: []
	},

	cache: {},
	query: {},

	initialize: function(options, next){
		this.setOptions(options);
		this.endpoint = (this.options.path === false) ? this.options.uri : this.options.path;
		this.refresh(this.options.endpoints, next);
	},

	refresh: function(endpoints, next){
		var combined = Array.clone(this.options.endpoints).combine(endpoints);
		if (this.options.endpoints.length !== combined.length) return;

		endpoints.forEach(function(endpoint, index){
			load.chain(this.store.bind(this, endpoint));
		}.bind(this));

		load.chain(this.done.pass(next, this));
		load.next();
	},

	store: function(endpoint){
		console.log('Caching "' + endpoint + '" endpoint');

		var uri = this.endpoint + endpoint + '.json';

		if (this.options.uri) {
			open(uri, function(err, json){
				if (err) throw err;
				this.cache[endpoint] = json;
				load.next();
			}.bind(this));

		} else {
			var file = this.options.path + endpoint + '.json';

			console.log('file path ' + file);

			fs.readFile(file, 'utf8', function(err, json){
				if (err) throw err;
				this.cache[endpoint] = JSON.decode(json);
				load.next();
			}.bind(this));

			fs.unwatchFile(file);

			fs.watchFile(file, function(curr, prev){
				if (curr.mtime.getTime() - prev.mtime.getTime()) {
					this.store(file, endpoint);
				}
			}.bind(this));
		}
	},

	done: function(next){
		console.log('All endpoints are loaded and cached');
//			console.log(JSON.stringify(this.cache));
		console.log('add arrays on index types');

		console.log(this.options.endpoints);
		this.options.endpoints.forEach(function(endpoint, e){
//			var endpoint = this.cache[endpoint].meta.type;
//			var type = endpoint.meta.type;
//			var data = endpoint[type];
			if (this.cache[endpoint].meta.type == 'index') {
				console.log('the ' +endpoint+ ' needs a collection property');
//				this.cache[endpoint].index.for
				this.cache[endpoint].collection = [];

				for (var id in this.cache[endpoint].index) {
					var obj = this.cache[endpoint].index[id];
					this.cache[endpoint].collection.push(obj);
				}
			}
		}.bind(this));

		if (next) next();
	},

	get: function(endpoint){
		if (endpoint.split('.').length > 1) {
			console.log('this is longer');
			var keys = endpoint.split('.');
//			var obj = this.cache[key[0]];
			return this.getProperty(this.cache, keys);
		}
		console.log('get without clone');
		var type = this.cache[endpoint].meta.type;
		return this.cache[endpoint][type];
	},

	in: function(endpoint){
		this.query = {};
		this.query.endpoint = endpoint;
		return this;
	},

	where: function(match){
		this.query.where = match;
//		if (typeof match == 'string') this.query.key = match;
		return this;
	},

	like: function(key, value){
		var match = {};
		match[key] = '$like('+ value +')';
		this.query.where = match;
		return this;
	},

	order: function(key, direction){
		this.query.order = { key: key, direction: direction || 'asc' };
		return this;
	},

	limit: function(arr, count){
		return arr.slice(0, count.toInt());
	},

	getProperty: function(obj, keys){
	    var prop = obj;
	    for (var i = 0; i < keys.length; i++) prop = prop[keys[i]];
	    return prop;
	},

	orderBy: function(arr, key, way){
		var keys = key.split('.');

		arr.sort(function compare(a, b){
			var a_prop = this.getProperty(a, keys);
			var b_prop = this.getProperty(b, keys);

			switch (way) {
				case 'dec':
					if (a_prop > b_prop) return -1;
					if (a_prop < b_prop) return 1;
					return 0;
				case 'asc':
				default:
					if (a_prop < b_prop) return -1;
					if (a_prop > b_prop) return 1;
					return 0;
			}
		}.bind(this));

		return arr;
	},

	match: function(obj, matcher){
		for (var prop in obj) {
			var value = obj[prop];
			if (walk(matcher, value)) return value;
		}
		return false;
	},

	matchAll: function(obj, matcher){
		var arr = [];

		for (var prop in obj) {
			var value = obj[prop];
			if (walk(matcher, value)) arr.push(value);
		}

		return arr;
	},

	getMatches: function(limit){
		var terms = this.query.where || false;
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var data = endpoint[type];

		if (!terms) 						return data
		else if (typeof limit == 'string')	return data[terms]
//		else if (limit === 1) 				return collection.match(terms)
//		else 								return collection.matchAll(terms);
		else if (limit === 1) 				return this.match(data, terms)
		else 								return this.matchAll(data, terms);
		return false;
	},

	findById: function(id){
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var item = type === 'collection' ? endpoint[type].match({id: id}) : endpoint[type][id];
//		var item = this.getMatches(id);
		return Object.clone(item);
//		return this.populate(item);
//		return this.populate(item);
	},

	findOne: function(id){
		var item = this.getMatches(1);
		return Object.clone(item);
//		return this.populate(item);
	},

	findMany: function(limit){
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var items = endpoint[type];
		var is_array = Array.isArray(items);
		return is_array ? Array.clone(items) : Object.clone(items);
//		return this.populateAll(items);
//		return Object.clone(items);
	},

	find: function(limit){
		var matches = this.getMatches(limit);
		var is_array = Array.isArray(matches);

		if (this.query.populate) {
			// loop through and create a new array from index thats loaded
			matches = is_array ? this.populateAll(matches) : this.populate(matches);
		}

		if (this.query.order) {
			matches = this.orderBy(matches, this.query.order.key, this.query.order.direction);
		}
		if (is_array && limit) matches = this.limit(matches, limit);

		return matches;
	},

	populate: function(item){
		if (!item) return false;

		var obj = Object.clone(item);

		Object.each(obj, function(value, key){
			if (key.test(/_id/g)) {
				var new_key = key.replace('_id', '');
				var collection = new_key.pluralize();
				if (this.cache[collection] == undefined) return;
				var nested_obj = this.in(collection).findById(value);
				obj[new_key] = this.populate(nested_obj);
			}
		}.bind(this));

		return obj;
	},

	populateAll: function(data){
		if (Array.isArray(data)) {
			return data.map(function(item){
				return this.populate(item);
			}.bind(this));
		} else {
			var doc = Object.clone(data);
			console.log(doc);

			for (var prop in doc) {
				doc[prop] = this.populate(doc[prop]);
//					if (doc.hasOwnProperty(prop)) doc[prop] = this.populate(doc[prop]);
			}

			console.log(doc);
			return doc;
		}

//			return arr.map(function(obj){
//				return this.populate(obj);
//			}.bind(this));
	}

});

module.exports = JSONLY;<commit_msg>fixed faulty conditional on refresh method which was ignoring all refresh calls that didn't include all endpoints<commit_after>

var fs = require('fs');
var open = require('open-uri');
var Hitch = require('hitch');
require('./inflector');
var walk = require('./find');
var load = new Hitch();

var JSONLY = new Class({

	Implements: Options,

	options: {
		uri: false,
		path: false,
		endpoints: []
	},

	cache: {},
	query: {},

	initialize: function(options, next){
		this.setOptions(options);
		this.endpoint = (this.options.path === false) ? this.options.uri : this.options.path;
		this.refresh(this.options.endpoints, next);
	},

	refresh: function(endpoints, next){
		var watching = endpoints.filter(function(endpoint){
			return this.options.endpoints.contains(endpoint);
		}.bind(this));

		watching.forEach(function(endpoint, index){
			load.chain(this.store.bind(this, endpoint));
		}.bind(this));

		load.chain(this.done.pass(next, this));
		load.next();
	},

	store: function(endpoint){
		console.log('Caching "' + endpoint + '" endpoint');

		var uri = this.endpoint + endpoint + '.json';

		if (this.options.uri) {
			open(uri, function(err, json){
				if (err) throw err;
				this.cache[endpoint] = json;
				load.next();
			}.bind(this));

		} else {
			var file = this.options.path + endpoint + '.json';

			console.log('file path ' + file);

			fs.readFile(file, 'utf8', function(err, json){
				if (err) throw err;
				this.cache[endpoint] = JSON.decode(json);
				load.next();
			}.bind(this));

			fs.unwatchFile(file);

			fs.watchFile(file, function(curr, prev){
				if (curr.mtime.getTime() - prev.mtime.getTime()) {
					this.store(file, endpoint);
				}
			}.bind(this));
		}
	},

	done: function(next){
		console.log('All endpoints are loaded and cached');
//			console.log(JSON.stringify(this.cache));
		console.log('add arrays on index types');

		console.log(this.options.endpoints);
		this.options.endpoints.forEach(function(endpoint, e){
//			var endpoint = this.cache[endpoint].meta.type;
//			var type = endpoint.meta.type;
//			var data = endpoint[type];
			if (this.cache[endpoint].meta.type == 'index') {
				console.log('the ' +endpoint+ ' needs a collection property');
//				this.cache[endpoint].index.for
				this.cache[endpoint].collection = [];

				for (var id in this.cache[endpoint].index) {
					var obj = this.cache[endpoint].index[id];
					this.cache[endpoint].collection.push(obj);
				}
			}
		}.bind(this));

		if (next) next();
	},

	get: function(endpoint){
		if (endpoint.split('.').length > 1) {
			console.log('this is longer');
			var keys = endpoint.split('.');
//			var obj = this.cache[key[0]];
			return this.getProperty(this.cache, keys);
		}
		console.log('get without clone');
		var type = this.cache[endpoint].meta.type;
		return this.cache[endpoint][type];
	},

	in: function(endpoint){
		this.query = {};
		this.query.endpoint = endpoint;
		return this;
	},

	where: function(match){
		this.query.where = match;
//		if (typeof match == 'string') this.query.key = match;
		return this;
	},

	like: function(key, value){
		var match = {};
		match[key] = '$like('+ value +')';
		this.query.where = match;
		return this;
	},

	order: function(key, direction){
		this.query.order = { key: key, direction: direction || 'asc' };
		return this;
	},

	limit: function(arr, count){
		return arr.slice(0, count.toInt());
	},

	getProperty: function(obj, keys){
	    var prop = obj;
	    for (var i = 0; i < keys.length; i++) prop = prop[keys[i]];
	    return prop;
	},

	orderBy: function(arr, key, way){
		var keys = key.split('.');

		arr.sort(function compare(a, b){
			var a_prop = this.getProperty(a, keys);
			var b_prop = this.getProperty(b, keys);

			switch (way) {
				case 'dec':
					if (a_prop > b_prop) return -1;
					if (a_prop < b_prop) return 1;
					return 0;
				case 'asc':
				default:
					if (a_prop < b_prop) return -1;
					if (a_prop > b_prop) return 1;
					return 0;
			}
		}.bind(this));

		return arr;
	},

	match: function(obj, matcher){
		for (var prop in obj) {
			var value = obj[prop];
			if (walk(matcher, value)) return value;
		}
		return false;
	},

	matchAll: function(obj, matcher){
		var arr = [];

		for (var prop in obj) {
			var value = obj[prop];
			if (walk(matcher, value)) arr.push(value);
		}

		return arr;
	},

	getMatches: function(limit){
		var terms = this.query.where || false;
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var data = endpoint[type];

		if (!terms) 						return data
		else if (typeof limit == 'string')	return data[terms]
//		else if (limit === 1) 				return collection.match(terms)
//		else 								return collection.matchAll(terms);
		else if (limit === 1) 				return this.match(data, terms)
		else 								return this.matchAll(data, terms);
		return false;
	},

	findById: function(id){
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var item = type === 'collection' ? endpoint[type].match({id: id}) : endpoint[type][id];
//		var item = this.getMatches(id);
		return Object.clone(item);
//		return this.populate(item);
//		return this.populate(item);
	},

	findOne: function(id){
		var item = this.getMatches(1);
		return Object.clone(item);
//		return this.populate(item);
	},

	findMany: function(limit){
		var endpoint = this.cache[this.query.endpoint];
		var type = endpoint.meta.type;
		var items = endpoint[type];
		var is_array = Array.isArray(items);
		return is_array ? Array.clone(items) : Object.clone(items);
//		return this.populateAll(items);
//		return Object.clone(items);
	},

	find: function(limit){
		var matches = this.getMatches(limit);
		var is_array = Array.isArray(matches);

		if (this.query.populate) {
			// loop through and create a new array from index thats loaded
			matches = is_array ? this.populateAll(matches) : this.populate(matches);
		}

		if (this.query.order) {
			matches = this.orderBy(matches, this.query.order.key, this.query.order.direction);
		}
		if (is_array && limit) matches = this.limit(matches, limit);

		return matches;
	},

	populate: function(item){
		if (!item) return false;

		var obj = Object.clone(item);

		Object.each(obj, function(value, key){
			if (key.test(/_id/g)) {
				var new_key = key.replace('_id', '');
				var collection = new_key.pluralize();
				if (this.cache[collection] == undefined) return;
				var nested_obj = this.in(collection).findById(value);
				obj[new_key] = this.populate(nested_obj);
			}
		}.bind(this));

		return obj;
	},

	populateAll: function(data){
		if (Array.isArray(data)) {
			return data.map(function(item){
				return this.populate(item);
			}.bind(this));
		} else {
			var doc = Object.clone(data);
			console.log(doc);

			for (var prop in doc) {
				doc[prop] = this.populate(doc[prop]);
//					if (doc.hasOwnProperty(prop)) doc[prop] = this.populate(doc[prop]);
			}

			console.log(doc);
			return doc;
		}

//			return arr.map(function(obj){
//				return this.populate(obj);
//			}.bind(this));
	}

});

module.exports = JSONLY;<|endoftext|>


<commit_before>/*
 * L.Control.GeoSearch - search for an address and zoom to it's location
 * https://github.com/smeijer/leaflet.control.geosearch
 */

L.GeoSearch = {};
L.GeoSearch.Provider = {};

// MSIE needs cors support
jQuery.support.cors = true;

L.GeoSearch.Result = function (x, y, label) {
    this.X = x;
    this.Y = y;
    this.Label = label;
};

L.Control.GeoSearch = L.Control.extend({
    options: {
        position: 'topcenter'
    },

    initialize: function (options) {
        this._config = {};
        L.Util.extend(this.options, options);
        this.setConfig(options);
    },

    setConfig: function (options) {
        this._config = {
            'country': options.country || '',
            'provider': options.provider,

            'searchLabel': options.searchLabel || 'search for address...',
            'notFoundMessage' : options.notFoundMessage || 'Sorry, that address could not be found.',
            'messageHideDelay': options.messageHideDelay || 3000,
            'zoomLevel': options.zoomLevel || 18
        };
    },

    onAdd: function (map) {
        var $controlContainer = $(map._controlContainer);

        if ($controlContainer.children('.leaflet-top.leaflet-center').length == 0) {
            $controlContainer.append('

');
            map._controlCorners.topcenter = $controlContainer.children('.leaflet-top.leaflet-center').first()[0];
        }

        this._map = map;
        this._container = L.DomUtil.create('div', 'leaflet-control-geosearch');

        var searchbox = document.createElement('input');
        searchbox.id = 'leaflet-control-geosearch-qry';
        searchbox.type = 'text';
        searchbox.placeholder = this._config.searchLabel;
        this._searchbox = searchbox;

        var msgbox = document.createElement('div');
        msgbox.id = 'leaflet-control-geosearch-msg';
        msgbox.className = 'leaflet-control-geosearch-msg';
        this._msgbox = msgbox;

        var resultslist = document.createElement('ul');
        resultslist.id = 'leaflet-control-geosearch-results';
        this._resultslist = resultslist;

        $(this._msgbox).append(this._resultslist);
        $(this._container).append(this._searchbox, this._msgbox);

        L.DomEvent
          .addListener(this._container, 'click', L.DomEvent.stop)
          .addListener(this._container, 'keypress', this._onKeyUp, this);

        L.DomEvent.disableClickPropagation(this._container);

        return this._container;
    },

    geosearch: function (qry) {
        try {
            var provider = this._config.provider;

            if(typeof provider.GetLocations == 'function') {
                var results = provider.GetLocations(qry, function(results) {
                    this._processResults(results);
                }.bind(this));
            }
            else {
                var url = provider.GetServiceUrl(qry);

                $.getJSON(url, function (data) {
                    try {
                        var results = provider.ParseJSON(data);
                        this._processResults(results);
                    }
                    catch (error) {
                        this._printError(error);
                    }
                }.bind(this));
            }
        }
        catch (error) {
            this._printError(error);
        }
    },

    _processResults: function(results) {
        if (results.length == 0)
            throw this._config.notFoundMessage;

        this._map.fireEvent('geosearch_foundlocations', {Locations: results});
        this._showLocation(results[0]);
    },

    _showLocation: function (location) {
        if (typeof this._positionMarker === 'undefined')
            this._positionMarker = L.marker([location.Y, location.X]).addTo(this._map);
        else
            this._positionMarker.setLatLng([location.Y, location.X]);

        this._map.setView([location.Y, location.X], this._config.zoomLevel, false);
        this._map.fireEvent('geosearch_showlocation', {Location: location});
    },

    _printError: function(message) {
        $(this._resultslist)
            .html('
'+message+'
')
            .fadeIn('slow').delay(this._config.messageHideDelay).fadeOut('slow',
                    function () { $(this).html(''); });
    },

    _onKeyUp: function (e) {
        var escapeKey = 27;
        var enterKey = 13;

        if (e.keyCode === escapeKey) {
            $('#leaflet-control-geosearch-qry').val('');
            $(this._map._container).focus();
        }
        else if (e.keyCode === enterKey) {
            this.geosearch($('#leaflet-control-geosearch-qry').val());
        }
    }
});<commit_msg>Fix minor typo<commit_after>/*
 * L.Control.GeoSearch - search for an address and zoom to its location
 * https://github.com/smeijer/leaflet.control.geosearch
 */

L.GeoSearch = {};
L.GeoSearch.Provider = {};

// MSIE needs cors support
jQuery.support.cors = true;

L.GeoSearch.Result = function (x, y, label) {
    this.X = x;
    this.Y = y;
    this.Label = label;
};

L.Control.GeoSearch = L.Control.extend({
    options: {
        position: 'topcenter'
    },

    initialize: function (options) {
        this._config = {};
        L.Util.extend(this.options, options);
        this.setConfig(options);
    },

    setConfig: function (options) {
        this._config = {
            'country': options.country || '',
            'provider': options.provider,

            'searchLabel': options.searchLabel || 'search for address...',
            'notFoundMessage' : options.notFoundMessage || 'Sorry, that address could not be found.',
            'messageHideDelay': options.messageHideDelay || 3000,
            'zoomLevel': options.zoomLevel || 18
        };
    },

    onAdd: function (map) {
        var $controlContainer = $(map._controlContainer);

        if ($controlContainer.children('.leaflet-top.leaflet-center').length == 0) {
            $controlContainer.append('

');
            map._controlCorners.topcenter = $controlContainer.children('.leaflet-top.leaflet-center').first()[0];
        }

        this._map = map;
        this._container = L.DomUtil.create('div', 'leaflet-control-geosearch');

        var searchbox = document.createElement('input');
        searchbox.id = 'leaflet-control-geosearch-qry';
        searchbox.type = 'text';
        searchbox.placeholder = this._config.searchLabel;
        this._searchbox = searchbox;

        var msgbox = document.createElement('div');
        msgbox.id = 'leaflet-control-geosearch-msg';
        msgbox.className = 'leaflet-control-geosearch-msg';
        this._msgbox = msgbox;

        var resultslist = document.createElement('ul');
        resultslist.id = 'leaflet-control-geosearch-results';
        this._resultslist = resultslist;

        $(this._msgbox).append(this._resultslist);
        $(this._container).append(this._searchbox, this._msgbox);

        L.DomEvent
          .addListener(this._container, 'click', L.DomEvent.stop)
          .addListener(this._container, 'keypress', this._onKeyUp, this);

        L.DomEvent.disableClickPropagation(this._container);

        return this._container;
    },

    geosearch: function (qry) {
        try {
            var provider = this._config.provider;

            if(typeof provider.GetLocations == 'function') {
                var results = provider.GetLocations(qry, function(results) {
                    this._processResults(results);
                }.bind(this));
            }
            else {
                var url = provider.GetServiceUrl(qry);

                $.getJSON(url, function (data) {
                    try {
                        var results = provider.ParseJSON(data);
                        this._processResults(results);
                    }
                    catch (error) {
                        this._printError(error);
                    }
                }.bind(this));
            }
        }
        catch (error) {
            this._printError(error);
        }
    },

    _processResults: function(results) {
        if (results.length == 0)
            throw this._config.notFoundMessage;

        this._map.fireEvent('geosearch_foundlocations', {Locations: results});
        this._showLocation(results[0]);
    },

    _showLocation: function (location) {
        if (typeof this._positionMarker === 'undefined')
            this._positionMarker = L.marker([location.Y, location.X]).addTo(this._map);
        else
            this._positionMarker.setLatLng([location.Y, location.X]);

        this._map.setView([location.Y, location.X], this._config.zoomLevel, false);
        this._map.fireEvent('geosearch_showlocation', {Location: location});
    },

    _printError: function(message) {
        $(this._resultslist)
            .html('
'+message+'
')
            .fadeIn('slow').delay(this._config.messageHideDelay).fadeOut('slow',
                    function () { $(this).html(''); });
    },

    _onKeyUp: function (e) {
        var escapeKey = 27;
        var enterKey = 13;

        if (e.keyCode === escapeKey) {
            $('#leaflet-control-geosearch-qry').val('');
            $(this._map._container).focus();
        }
        else if (e.keyCode === enterKey) {
            this.geosearch($('#leaflet-control-geosearch-qry').val());
        }
    }
});
<|endoftext|>