<commit_before>define(['knockout', 'factory/calendar', 'mods/format'], function(ko, calfac, format) {

    var items = ko.observableArray([]);
    var breadcrumbitems = ko.observableArray([]);
    var freetext = "";
    var filterwithoutdates = "";
    var search = null;

    function update(pfreetext, pfilterwithoutdates, pdatebegin, pdateend, searchmethod) {
        freetext = pfreetext;
        filterwithoutdates = pfilterwithoutdates;
        search = searchmethod;

        var any = false;

        if (pdatebegin != null && pdateend != null) {

            var d1 = pdatebegin;
            var d2 = pdateend;
            var d1yyyy = "" + d1.getFullYear();
            var d2yyyy = "" + d2.getFullYear();

            if (
                    d1yyyy.substring(0, 3) == d2yyyy.substring(0, 3) &&
                    d1yyyy.slice(-1) == "0" && d2yyyy.slice(-1) == "9"
                    ) {

                any = true;
                doyears(d1.getFullYear());
            }
            else if (d1yyyy == d2yyyy && d1.getMonth() != d2.getMonth()) {
                any = true;
                domonths(d1.getFullYear());
            }
            else if (d1yyyy == d2yyyy && d1.getMonth() == d2.getMonth()) {
                any = true;
                dodays(d1.getFullYear(), d1.getMonth());
            }
        }

        if (!any) {
            dodecades();
        }
    }

    function dodecades() {
        items.removeAll();
        breadcrumbitems.removeAll();
        addBreadcrumbDecades(true);

        var yearb = 1920;
        var yeare = (new Date().getFullYear()) / 10 * 10;

        for (var i = yearb; i < yeare; i += 10) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(i + "'erne");
            item.datebegin(i + "-01-01");
            item.dateend(i + 9 + "-12-31");
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function doyears(year) {
        items.removeAll();

        var yearb = year;
        var yeare = year + 9;

        for (var i = yearb; i < yeare; i++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(i);
            item.datebegin(i + "-01-01");
            item.dateend(i + "-12-31");
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    var monthnames =["","Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","Oktober","November","December"];

    function domonths(y) {

        items.removeAll();

        for (var m = 1; m < 13; m++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(monthnames[m]);
            item.datebegin(y + "-" + format.getDigit2(m) + "-01");
            var lastDay = new Date(y, m, 0);
            item.dateend(y + "-" + format.getDigit2(m) + "-" + format.getDigit2(lastDay.getDate()));
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function dodays(y,m) {

        items.removeAll();

        var lastDay = new Date(y, m+1, 0);

        for (var d = 1; d <= lastDay.getDate(); d++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.issmall(true);
            item.title(d + ".");
            item.datebegin(y + "-" + format.getDigit2(m+1) + "-" + format.getDigit2(d));
            item.dateend(y + "-" + format.getDigit2(m+1) + "-" + format.getDigit2(d));
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function addBreadcrumbDecades(active){
        breadcrumbitems.push(getCalItem("Årtier",null,null,active));
    }

    function addBreadcrumbDecade(title,db,de,active){
        breadcrumbitems.push(getCalItem(title,db,de,active));
    }

    function getCalItem(title,db,de,active){
        var item = new calfac.CalendarItem();
        item.search = itemclick;
        item.title(title);
        item.datebegin(db);
        item.dateend(de);
        item.isactive(active);
        return item;
    }

    function itemclick(item){

        var idx = -1;
        // Set all items to isactive false and find item index.
        for(var i = 0; i < breadcrumbitems().length; i++){
            breadcrumbitems()[i].isactive(false);
            if(breadcrumbitems()[i]===item)
                idx = i;
        }

        /// Remove item and above items from list.
        if(idx > -1){
            var il = breadcrumbitems().length - idx;
            for(var i = 0; i < il ; i++){
                breadcrumbitems.pop();
            }
        }

        /// Stop breadcrumb at day
        if(breadcrumbitems().length === 5)
            breadcrumbitems.pop();

        if(breadcrumbitems().length < 4)
            breadcrumbitems.push(getCalItem(item.title(),item.datebegin(),item.dateend(),true));

        search(item.datebegin(),item.dateend());
    }

    return {
        freetext: freetext,
        items: items,
        breadcrumbitems: breadcrumbitems,
        update: update,
        search: search
    };
});

<commit_msg>Fixed calendar years.<commit_after>define(['knockout', 'factory/calendar', 'mods/format'], function(ko, calfac, format) {

    var items = ko.observableArray([]);
    var breadcrumbitems = ko.observableArray([]);
    var freetext = "";
    var filterwithoutdates = "";
    var search = null;

    function update(pfreetext, pfilterwithoutdates, pdatebegin, pdateend, searchmethod) {
        freetext = pfreetext;
        filterwithoutdates = pfilterwithoutdates;
        search = searchmethod;

        var any = false;

        if (pdatebegin != null && pdateend != null) {

            var d1 = pdatebegin;
            var d2 = pdateend;
            var d1yyyy = "" + d1.getFullYear();
            var d2yyyy = "" + d2.getFullYear();

            if (
                    d1yyyy.substring(0, 3) == d2yyyy.substring(0, 3) &&
                    d1yyyy.slice(-1) == "0" && d2yyyy.slice(-1) == "9"
                    ) {

                any = true;
                doyears(d1.getFullYear());
            }
            else if (d1yyyy == d2yyyy && d1.getMonth() != d2.getMonth()) {
                any = true;
                domonths(d1.getFullYear());
            }
            else if (d1yyyy == d2yyyy && d1.getMonth() == d2.getMonth()) {
                any = true;
                dodays(d1.getFullYear(), d1.getMonth());
            }
        }

        if (!any) {
            dodecades();
        }
    }

    function dodecades() {
        items.removeAll();
        breadcrumbitems.removeAll();
        addBreadcrumbDecades(true);

        var yearb = 1920;
        var yeare = (new Date().getFullYear()) / 10 * 10;

        for (var i = yearb; i < yeare; i += 10) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(i + "'erne");
            item.datebegin(i + "-01-01");
            item.dateend(i + 9 + "-12-31");
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function doyears(year) {
        items.removeAll();

        var yearb = year;
        var yeare = year + 9;

        var yearnow = new Date().getFullYear();
        if (yeare > yearnow)
            yeare = yearnow;

        for (var i = yearb; i <= yeare; i++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(i);
            item.datebegin(i + "-01-01");
            item.dateend(i + "-12-31");
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    var monthnames = ["", "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"];

    function domonths(y) {

        items.removeAll();

        for (var m = 1; m < 13; m++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.title(monthnames[m]);
            item.datebegin(y + "-" + format.getDigit2(m) + "-01");
            var lastDay = new Date(y, m, 0);
            item.dateend(y + "-" + format.getDigit2(m) + "-" + format.getDigit2(lastDay.getDate()));
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function dodays(y, m) {

        items.removeAll();

        var lastDay = new Date(y, m + 1, 0);

        for (var d = 1; d <= lastDay.getDate(); d++) {
            var item = new calfac.CalendarItem();
            item.search = itemclick;
            item.issmall(true);
            item.title(d + ".");
            item.datebegin(y + "-" + format.getDigit2(m + 1) + "-" + format.getDigit2(d));
            item.dateend(y + "-" + format.getDigit2(m + 1) + "-" + format.getDigit2(d));
            items.push(item);
            item.load(freetext, filterwithoutdates);
        }
    }

    function addBreadcrumbDecades(active) {
        breadcrumbitems.push(getCalItem("Årtier", null, null, active));
    }

    function addBreadcrumbDecade(title, db, de, active) {
        breadcrumbitems.push(getCalItem(title, db, de, active));
    }

    function getCalItem(title, db, de, active) {
        var item = new calfac.CalendarItem();
        item.search = itemclick;
        item.title(title);
        item.datebegin(db);
        item.dateend(de);
        item.isactive(active);
        return item;
    }

    function itemclick(item) {

        var idx = -1;
        // Set all items to isactive false and find item index.
        for (var i = 0; i < breadcrumbitems().length; i++) {
            breadcrumbitems()[i].isactive(false);
            if (breadcrumbitems()[i] === item)
                idx = i;
        }

        /// Remove item and above items from list.
        if (idx > -1) {
            var il = breadcrumbitems().length - idx;
            for (var i = 0; i < il; i++) {
                breadcrumbitems.pop();
            }
        }

        /// Stop breadcrumb at day
        if (breadcrumbitems().length === 5)
            breadcrumbitems.pop();

        if (breadcrumbitems().length < 4)
            breadcrumbitems.push(getCalItem(item.title(), item.datebegin(), item.dateend(), true));

        search(item.datebegin(), item.dateend());
    }

    return {
        freetext: freetext,
        items: items,
        breadcrumbitems: breadcrumbitems,
        update: update,
        search: search
    };
});

<|endoftext|>


<commit_before>import keyMirror from 'keymirror';
import invariant from 'invariant';

const { EventEmitter } = require('events');

const _emitter = new EventEmitter();

let _nextUpdateHandle = 0;
let _inc = 0;
let _deadline = -1;

const InteractionManager = {
  Events: keyMirror({
    interactionStart: true,
    interactionComplete: true,
  }),

  /**
   * Schedule a function to run after all interactions have completed.
   */
  runAfterInteractions(task) {
    return new Promise(resolve => {
      // TODO(lmr):
      // _scheduleUpdate();
      //if (task) {
      //  _taskQueue.enqueue(task);
      //}
      //const name = task && task.name || '?';
      //_taskQueue.enqueue({ run: resolve, name: 'resolve ' + name });
    });
  },

  /**
   * Notify manager that an interaction has started.
   */
  createInteractionHandle() {
    // TODO(lmr):
    // _scheduleUpdate();
    var handle = ++_inc;
    //_addInteractionSet.add(handle);
    return handle;
  },

  /**
   * Notify manager that an interaction has completed.
   */
  clearInteractionHandle(handle) {
    invariant(
      !!handle,
      'Must provide a handle to clear.'
    );
    // TODO(lmr):
    // _scheduleUpdate();
    //_addInteractionSet.delete(handle);
    //_deleteInteractionSet.add(handle);
  },

  addListener: _emitter.addListener.bind(_emitter),

  /**
   * A positive number will use setTimeout to schedule any tasks after the
   * eventLoopRunningTime hits the deadline value, otherwise all tasks will be
   * executed in one setImmediate batch (default).
   */
  setDeadline(deadline) {
    _deadline = deadline;
  },
};
<commit_msg>[minor] Export InteractionManager<commit_after>import keyMirror from 'keymirror';
import invariant from 'invariant';

const { EventEmitter } = require('events');

const _emitter = new EventEmitter();

let _nextUpdateHandle = 0;
let _inc = 0;
let _deadline = -1;

const InteractionManager = {
  Events: keyMirror({
    interactionStart: true,
    interactionComplete: true,
  }),

  /**
   * Schedule a function to run after all interactions have completed.
   */
  runAfterInteractions(task) {
    return new Promise(resolve => {
      // TODO(lmr):
      // _scheduleUpdate();
      //if (task) {
      //  _taskQueue.enqueue(task);
      //}
      //const name = task && task.name || '?';
      //_taskQueue.enqueue({ run: resolve, name: 'resolve ' + name });
    });
  },

  /**
   * Notify manager that an interaction has started.
   */
  createInteractionHandle() {
    // TODO(lmr):
    // _scheduleUpdate();
    var handle = ++_inc;
    //_addInteractionSet.add(handle);
    return handle;
  },

  /**
   * Notify manager that an interaction has completed.
   */
  clearInteractionHandle(handle) {
    invariant(
      !!handle,
      'Must provide a handle to clear.'
    );
    // TODO(lmr):
    // _scheduleUpdate();
    //_addInteractionSet.delete(handle);
    //_deleteInteractionSet.add(handle);
  },

  addListener: _emitter.addListener.bind(_emitter),

  /**
   * A positive number will use setTimeout to schedule any tasks after the
   * eventLoopRunningTime hits the deadline value, otherwise all tasks will be
   * executed in one setImmediate batch (default).
   */
  setDeadline(deadline) {
    _deadline = deadline;
  },
};

module.exports = InteractionManager;
<|endoftext|>


<commit_before>/**
 * Created by 3er on 1/9/15.
 */

var qs = require('querystring');
var path = require('path');
var fs = require('fs');
var PRIVATE = require('./config/private')

var AND = ' && ';
var FFMPEG = ' ' + PRIVATE.dir.ffmpeg + 'ffmpeg ';

//前面有可能跟路径不能带空格
var h = function (d) {
    return {
        dir: d,
        origin: d + '/h.mp4 ',
        compo: d + '/h.list ',
        output: d + '/outputh.mp4 ',
        target: 'high/'
    }
};

var m = function (d) {
    return {
        dir: d,
        origin: d + '/m.mp4 ',
        compo: d + '/m.list ',
        output: d + '/outputm.mp4 ',
        target: 'medium/'
    }
};

var l = function (d) {
    return {
        dir: d,
        origin: d + '/l.mp4 ',
        compo: d + '/l.list ',
        output: d + '/outputl.mp4 ',
        target: 'low/'
    }
};

var LOOP = function (A, f, param1, param2) {
    var ret = new String();
    for (var i = 0; i < A.length; i++) {
        ret = ret + f(A[i], param1, param2) + AND;
    }
    return ret;
};

video = {
    ULTRAFAST: 'ultrafast',
    ULTRASLOW: 'ultraslow',
    param: function (w, h, sw, sh) {
        return '-vf setsar=sar=' + sw + '/' + sh + ',setdar=dar=16/9,scale=' + w + 'x' + h
            + ' -pix_fmt yuv420p -c:v libx264 -r 25 -benchmark -threads 0 -preset ' + video.ULTRASLOW;
    }
};

audio = {
    param: function (a, b, vbr) {
        //TODO: vba need compilation
        return ' -c:a libfdk_aac -ar ' + a + ' -b:a ' + b + 'k ';
    }
};

origin = {
    ver: function (F, w, h, sw, sh, a, b, vbr) {
        return  video.param(w, h, sw, sh) + audio.param(a, b, vbr) + F.origin;
    },
    generate: function (H, M, L) {
        return this.ver(H, 1280, 720, 1, 1, 48000, 128)
            + this.ver(M, 854, 480, 1280, 1281, 44100, 96)
            + this.ver(L, 480, 270, 1, 1, 22050, 64) + AND;
    }
};

bash = {
    cp: function (src, dest) {
        return ' cp ' + src + ' ' + dest + ' ';
    },
    mv: function (src, dest) {
        return ' mv ' + src + ' ' + dest + ' ';
    },
    rmDir: function (dir) {
        return ' rm -rf ' + dir + ' ';
    },
    cpO2O: function (F) {
        return ' cp ' + F.origin + F.output;
    },
    mvO2T: function (F, target, fileName) {
        return ' mv ' + F.output + target + F.target + fileName;
    }
};

var oped = function () {
    this.op_name = '';
    this.op_duration = 0;
    this.ed_name = '';
    this.ed_duration = 0;
};

oped.prototype.metadata = function () {
    return qs.stringify(this);
};

exports.oped = oped;

concat = {
    concat: function (F, oped) {
        return FFMPEG + '-y -f concat -i ' + F.compo + ' -c copy -metadata "'
            + oped.metadata() + '" ' + F.output;
    },

    cmd: function (A, oped) {
        return LOOP(A, this.concat, oped);
    }
};

ffmpeg = {
    input: function (path) {
        return FFMPEG + '-y -i "' + path + '" ';
    }
};

command = {

    addOped: function (A, oe) {
        if (oe.op_name == 'null' && oe.ed_name == 'null') {
            return LOOP(A, bash.cpO2O);
        }
        else {
            return concat.cmd(A, oe);
        }
    },

    mv: function (A, target, fileName) {
        // origin h
        var ret = bash.cp(A[0].output, target + 'origin/' + fileName) + AND;
        // high/medium/low
        ret = ret + LOOP(A, bash.mvO2T, target, fileName);
        return ret;
    },

    all: function (p, oe) {
        var dir = path.dirname(p);
        var fileName = path.basename(p);
        var H = h(dir), M = m(dir), L = l(dir);
        var A = [H, M, L];

        // output: h.mp4 m.mp4 l.mp4
        var ret = ffmpeg.input(p) + origin.generate(H, M, L);
        // output: outputh.mp4 outputm.mp4 outputl.mp4
        ret = ret + this.addOped(A, oe);
        // output: rsync 4 folders
        ret = ret + this.mv(A, PRIVATE.dir.rsync, fileName);
        // rm
        ret = ret + bash.rmDir(dir) + '\n';
        return ret;
    }
};

var file = {
    content: function (opedDir, inputDir, oe, v) {
        var f;
        var VMP4 = v + '.mp4\n';
        if (oe.op_name != 'null')
            f = 'file ' + opedDir + oe.op_name + VMP4;
        else
            f = ''

        f = f + 'file ' + inputDir + VMP4;

        if (oe.ed_name != 'null')
            f = f + 'file ' + opedDir + oe.ed_name + VMP4;
        else
            f = f;
        return f;
    },

    write: function (inputPath, opedDir, oped) {
        var inputDir = path.dirname(inputPath) + '/';
        fs.writeFileSync(inputDir + 'h.list', this.content(opedDir, inputDir, oped, 'h'));
        fs.writeFileSync(inputDir + 'm.list', this.content(opedDir, inputDir, oped, 'm'));
        fs.writeFileSync(inputDir + 'l.list', this.content(opedDir, inputDir, oped, 'l'));
    }
};

exports.generate = function (filePath, oe) {
//    oe.op_name = 'null'
//    oe.ed_name = 'null'
    var cmd = command.all(filePath, oe);
    if (oe.op_name != 'null' || oe.ed_name != 'null') {
        file.write(filePath, PRIVATE.dir.oped, oe);
    }
    fs.writeFileSync(path.dirname(filePath) + '/' + 'command', cmd);
    return cmd;
};

<commit_msg>video preset<commit_after>/**
 * Created by 3er on 1/9/15.
 */

var qs = require('querystring');
var path = require('path');
var fs = require('fs');
var PRIVATE = require('./config/private')

var AND = ' && ';
var FFMPEG = ' ' + PRIVATE.dir.ffmpeg + 'ffmpeg ';

//前面有可能跟路径不能带空格
var h = function (d) {
    return {
        dir: d,
        origin: d + '/h.mp4 ',
        compo: d + '/h.list ',
        output: d + '/outputh.mp4 ',
        target: 'high/'
    }
};

var m = function (d) {
    return {
        dir: d,
        origin: d + '/m.mp4 ',
        compo: d + '/m.list ',
        output: d + '/outputm.mp4 ',
        target: 'medium/'
    }
};

var l = function (d) {
    return {
        dir: d,
        origin: d + '/l.mp4 ',
        compo: d + '/l.list ',
        output: d + '/outputl.mp4 ',
        target: 'low/'
    }
};

var LOOP = function (A, f, param1, param2) {
    var ret = new String();
    for (var i = 0; i < A.length; i++) {
        ret = ret + f(A[i], param1, param2) + AND;
    }
    return ret;
};

video = {
    ULTRAFAST: 'ultrafast',
    VERYSLOW: 'veryslow',
    param: function (w, h, sw, sh) {
        return '-vf setsar=sar=' + sw + '/' + sh + ',setdar=dar=16/9,scale=' + w + 'x' + h
            + ' -pix_fmt yuv420p -c:v libx264 -r 25 -benchmark -threads 0 -preset ' + video.VERYSLOW;
    }
};

audio = {
    param: function (a, b, vbr) {
        //TODO: vba need compilation
        return ' -c:a libfdk_aac -ar ' + a + ' -b:a ' + b + 'k ';
    }
};

origin = {
    ver: function (F, w, h, sw, sh, a, b, vbr) {
        return  video.param(w, h, sw, sh) + audio.param(a, b, vbr) + F.origin;
    },
    generate: function (H, M, L) {
        return this.ver(H, 1280, 720, 1, 1, 48000, 128)
            + this.ver(M, 854, 480, 1280, 1281, 44100, 96)
            + this.ver(L, 480, 270, 1, 1, 22050, 64) + AND;
    }
};

bash = {
    cp: function (src, dest) {
        return ' cp ' + src + ' ' + dest + ' ';
    },
    mv: function (src, dest) {
        return ' mv ' + src + ' ' + dest + ' ';
    },
    rmDir: function (dir) {
        return ' rm -rf ' + dir + ' ';
    },
    cpO2O: function (F) {
        return ' cp ' + F.origin + F.output;
    },
    mvO2T: function (F, target, fileName) {
        return ' mv ' + F.output + target + F.target + fileName;
    }
};

var oped = function () {
    this.op_name = '';
    this.op_duration = 0;
    this.ed_name = '';
    this.ed_duration = 0;
};

oped.prototype.metadata = function () {
    return qs.stringify(this);
};

exports.oped = oped;

concat = {
    concat: function (F, oped) {
        return FFMPEG + '-y -f concat -i ' + F.compo + ' -c copy -metadata "'
            + oped.metadata() + '" ' + F.output;
    },

    cmd: function (A, oped) {
        return LOOP(A, this.concat, oped);
    }
};

ffmpeg = {
    input: function (path) {
        return FFMPEG + '-y -i "' + path + '" ';
    }
};

command = {

    addOped: function (A, oe) {
        if (oe.op_name == 'null' && oe.ed_name == 'null') {
            return LOOP(A, bash.cpO2O);
        }
        else {
            return concat.cmd(A, oe);
        }
    },

    mv: function (A, target, fileName) {
        // origin h
        var ret = bash.cp(A[0].output, target + 'origin/' + fileName) + AND;
        // high/medium/low
        ret = ret + LOOP(A, bash.mvO2T, target, fileName);
        return ret;
    },

    all: function (p, oe) {
        var dir = path.dirname(p);
        var fileName = path.basename(p);
        var H = h(dir), M = m(dir), L = l(dir);
        var A = [H, M, L];

        // output: h.mp4 m.mp4 l.mp4
        var ret = ffmpeg.input(p) + origin.generate(H, M, L);
        // output: outputh.mp4 outputm.mp4 outputl.mp4
        ret = ret + this.addOped(A, oe);
        // output: rsync 4 folders
        ret = ret + this.mv(A, PRIVATE.dir.rsync, fileName);
        // rm
        ret = ret + bash.rmDir(dir) + '\n';
        return ret;
    }
};

var file = {
    content: function (opedDir, inputDir, oe, v) {
        var f;
        var VMP4 = v + '.mp4\n';
        if (oe.op_name != 'null')
            f = 'file ' + opedDir + oe.op_name + VMP4;
        else
            f = ''

        f = f + 'file ' + inputDir + VMP4;

        if (oe.ed_name != 'null')
            f = f + 'file ' + opedDir + oe.ed_name + VMP4;
        else
            f = f;
        return f;
    },

    write: function (inputPath, opedDir, oped) {
        var inputDir = path.dirname(inputPath) + '/';
        fs.writeFileSync(inputDir + 'h.list', this.content(opedDir, inputDir, oped, 'h'));
        fs.writeFileSync(inputDir + 'm.list', this.content(opedDir, inputDir, oped, 'm'));
        fs.writeFileSync(inputDir + 'l.list', this.content(opedDir, inputDir, oped, 'l'));
    }
};

exports.generate = function (filePath, oe) {
//    oe.op_name = 'null'
//    oe.ed_name = 'null'
    var cmd = command.all(filePath, oe);
    if (oe.op_name != 'null' || oe.ed_name != 'null') {
        file.write(filePath, PRIVATE.dir.oped, oe);
    }
    fs.writeFileSync(path.dirname(filePath) + '/' + 'command', cmd);
    return cmd;
};

<|endoftext|>


<commit_before>window.cls || (window.cls = {});

cls.OpenSingleResource = function(resource_manager, url)
{
  this._resman = resource_manager;
  this._url = url;
  if (!this._tagman)
  {
    this._init_prototype();
  }
  this._show_resource();
};

cls.OpenSingleResource.prototype = new function()
{
  const
  TRANSPORT_STRING = 1,
  TRANSPORT_DATA_URI = 3,
  DECODE_TRUE = 1,
  SIZE_LIMIT = 1e7,
  TRANSPORT_OFF = 4;

  this._show_resource = function()
  {
    if (!this._resman.show_resource_for_url(this._url))
    {
      if (this._service.requestGetResourceID)
      {
        var tag = this._tagman.set_callback(this, this._on_resolve_url);
        this._service.requestGetResourceID(tag, [this._url]);
      }
      else
      {
        this._fallback();
      }
    }
  };

  this._on_resolve_url = function(status, message)
  {
    if (status)
    {
      opera.postError("GetResourceID in OpenSingleResource failed");
      this._fallback();
    }
    else
    {
      const RESOURCE_ID = 0;
      this._rid = message[RESOURCE_ID];
      if (!this._resman.show_resource_for_id(this._rid))
      {
        var tag = this._tagman.set_callback(this, this._on_mime_type);
        this._service.requestGetResource(tag, [this._rid, [TRANSPORT_OFF]]);
      }
    }
  };

  this._on_mime_type = function(status, message)
  {
    if (status)
    {
      opera.postError("GetResource in OpenSingleResource failed");
      this._fallback();
    }
    else
    {
      this._res = new cls.Resource(this._rid);
      this._res.update("urlfinished", new this._ResourceData(message));
      var resptype = this._utils.mime_to_content_mode(this._res.mime);
      var tag = this._tagman.set_callback(this, this._on_resource);
      var msg =
      [
        this._rid,
        [
          resptype == "datauri" ? TRANSPORT_DATA_URI : TRANSPORT_STRING,
          DECODE_TRUE,
          SIZE_LIMIT
        ]
      ];
      this._service.requestGetResource(tag, msg);
    }
  };

  this._on_resource = function(status, message)
  {
    if (status)
    {
      opera.postError("GetResource in OpenSingleResource failed");
      this._fallback();
    }
    else
    {
      this._res.update("urlfinished", new this._ResourceData(message));
      this._resman.open_resource_tab(this._res);
    }
  };

  this._fallback = function()
  {
    window.open(this._url);
  };

  this._init_prototype = function()
  {
    this._tagman = window.tagManager;
    this._service = window.services['resource-manager'];
    this._ResourceData = cls.ResourceManager["1.0"].ResourceData;
    this._utils = cls.ResourceUtil;
  }.bind(this);

};
<commit_msg>Removed opera.postError's.<commit_after>window.cls || (window.cls = {});

cls.OpenSingleResource = function(resource_manager, url)
{
  this._resman = resource_manager;
  this._url = url;
  if (!this._tagman)
  {
    this._init_prototype();
  }
  this._show_resource();
};

cls.OpenSingleResource.prototype = new function()
{
  const
  TRANSPORT_STRING = 1,
  TRANSPORT_DATA_URI = 3,
  DECODE_TRUE = 1,
  SIZE_LIMIT = 1e7,
  TRANSPORT_OFF = 4;

  this._show_resource = function()
  {
    if (!this._resman.show_resource_for_url(this._url))
    {
      if (this._service.requestGetResourceID)
      {
        var tag = this._tagman.set_callback(this, this._on_resolve_url);
        this._service.requestGetResourceID(tag, [this._url]);
      }
      else
      {
        this._fallback();
      }
    }
  };

  this._on_resolve_url = function(status, message)
  {
    if (status)
    {
      this._fallback();
    }
    else
    {
      const RESOURCE_ID = 0;
      this._rid = message[RESOURCE_ID];
      if (!this._resman.show_resource_for_id(this._rid))
      {
        var tag = this._tagman.set_callback(this, this._on_mime_type);
        this._service.requestGetResource(tag, [this._rid, [TRANSPORT_OFF]]);
      }
    }
  };

  this._on_mime_type = function(status, message)
  {
    if (status)
    {
      this._fallback();
    }
    else
    {
      this._res = new cls.Resource(this._rid);
      this._res.update("urlfinished", new this._ResourceData(message));
      var resptype = this._utils.mime_to_content_mode(this._res.mime);
      var tag = this._tagman.set_callback(this, this._on_resource);
      var msg =
      [
        this._rid,
        [
          resptype == "datauri" ? TRANSPORT_DATA_URI : TRANSPORT_STRING,
          DECODE_TRUE,
          SIZE_LIMIT
        ]
      ];
      this._service.requestGetResource(tag, msg);
    }
  };

  this._on_resource = function(status, message)
  {
    if (status)
    {
      this._fallback();
    }
    else
    {
      this._res.update("urlfinished", new this._ResourceData(message));
      this._resman.open_resource_tab(this._res);
    }
  };

  this._fallback = function()
  {
    window.open(this._url);
  };

  this._init_prototype = function()
  {
    this._tagman = window.tagManager;
    this._service = window.services['resource-manager'];
    this._ResourceData = cls.ResourceManager["1.0"].ResourceData;
    this._utils = cls.ResourceUtil;
  }.bind(this);

};
<|endoftext|>


<commit_before>var _ = require("lodash/core");

/**
 * Contains the logic for the export button.
 * @returns {{}}
 */
module.exports = function (graph) {

	var exportMenu = {},
		exportSvgButton,
		exportFilename,
		exportJsonButton,
		exportableJsonText;

	/**
	 * Adds the export button to the website.
	 */
	exportMenu.setup = function () {
		exportSvgButton = d3.select("#exportSvg")
			.on("click", exportSvg);
		exportJsonButton = d3.select("#exportJson")
			.on("click", exportJson);
	};

	exportMenu.setFilename = function (filename) {
		exportFilename = filename || "export";
	};

	exportMenu.setJsonText = function (jsonText) {
		exportableJsonText = jsonText;
	};

	function exportSvg() {
		// Get the d3js SVG element
		var graphSvg = d3.select(graph.options().graphContainerSelector()).select("svg"),
			graphSvgCode,
			escapedGraphSvgCode,
			dataURI;

		// inline the styles, so that the exported svg code contains the css rules
		inlineVowlStyles();
		hideNonExportableElements();

		graphSvgCode = graphSvg.attr("version", 1.1)
			.attr("xmlns", "http://www.w3.org/2000/svg")
			.node().parentNode.innerHTML;

		// Insert the reference to VOWL
		graphSvgCode = "<!-- Created with WebVOWL (version " + webvowl.version + ")" +
		               ", http://vowl.visualdataweb.org -->\n" + graphSvgCode;

		escapedGraphSvgCode = escapeUnicodeCharacters(graphSvgCode);
		//btoa(); Creates a base-64 encoded ASCII string from a "string" of binary data.
		dataURI = "data:image/svg+xml;base64," + btoa(escapedGraphSvgCode);

		exportSvgButton.attr("href", dataURI)
			.attr("download", exportFilename + ".svg");

		// remove graphic styles for interaction to go back to normal
		removeVowlInlineStyles();
		showNonExportableElements();
	}

	function escapeUnicodeCharacters(text) {
		var textSnippets = [],
			i, textLength = text.length,
			character,
			charCode;

		for (i = 0; i < textLength; i++) {
			character = text.charAt(i);
			charCode = character.charCodeAt(0);

			if (charCode < 128) {
				textSnippets.push(character);
			} else {
				textSnippets.push("&#" + charCode + ";");
			}
		}

		return textSnippets.join("");
	}

	function inlineVowlStyles() {
		setStyleSensitively(".text", [{name: "font-family", value: "Helvetica, Arial, sans-serif"}, {name: "font-size", value: "12px"}]);
		setStyleSensitively(".subtext", [{name: "font-size", value: "9px"}]);
		setStyleSensitively(".text.instance-count", [{name: "fill", value: "#666"}]);
		setStyleSensitively(".external + text .instance-count", [{name: "fill", value: "#aaa"}]);
		setStyleSensitively(".cardinality", [{name: "font-size", value: "10px"}]);
		setStyleSensitively(".text, .embedded", [{name: "pointer-events", value: "none"}]);
		setStyleSensitively(".class, .object, .disjoint, .objectproperty, .disjointwith, .equivalentproperty, .transitiveproperty, .functionalproperty, .inversefunctionalproperty, .symmetricproperty, .allvaluesfromproperty, .somevaluesfromproperty", [{name: "fill", value: "#acf"}]);
		setStyleSensitively(".label .datatype, .datatypeproperty", [{name: "fill", value: "#9c6"}]);
		setStyleSensitively(".rdf, .rdfproperty", [{name: "fill", value: "#c9c"}]);
		setStyleSensitively(".literal, .node .datatype", [{name: "fill", value: "#fc3"}]);
		setStyleSensitively(".deprecated, .deprecatedproperty", [{name: "fill", value: "#ccc"}]);
		setStyleSensitively(".external, .externalproperty", [{name: "fill", value: "#36c"}]);
		setStyleSensitively("path, .nofill", [{name: "fill", value: "none"}]);
		setStyleSensitively("marker path", [{name: "fill", value: "#000"}]);
		setStyleSensitively(".class, path, line, .fineline", [{name: "stroke", value: "#000"}]);
		setStyleSensitively(".white, .subclass, .subclassproperty, .external + text", [{name: "fill", value: "#fff"}]);
		setStyleSensitively(".class.hovered, .property.hovered, .cardinality.hovered, .cardinality.focused, circle.pin, .filled.hovered, .filled.focused", [{name: "fill", value: "#f00"}, {name: "cursor", value: "pointer"}]);
		setStyleSensitively(".focused, path.hovered", [{name: "stroke", value: "#f00"}]);
		setStyleSensitively(".indirect-highlighting, .feature:hover", [{name: "fill", value: "#f90"}]);
		setStyleSensitively(".values-from", [{name: "stroke", value: "#69c"}]);
		setStyleSensitively(".symbol, .values-from.filled", [{name: "fill", value: "#69c"}]);
		setStyleSensitively(".class, path, line", [{name: "stroke-width", value: "2"}]);
		setStyleSensitively(".fineline", [{name: "stroke-width", value: "1"}]);
		setStyleSensitively(".dashed, .anonymous", [{name: "stroke-dasharray", value: "8"}]);
		setStyleSensitively(".dotted", [{name: "stroke-dasharray", value: "3"}]);
		setStyleSensitively("rect.focused, circle.focused", [{name: "stroke-width", value: "4px"}]);
		setStyleSensitively(".nostroke", [{name: "stroke", value: "none"}]);
		setStyleSensitively("marker path", [{name: "stroke-dasharray", value: "100"}]);
	}

	function setStyleSensitively(selector, styles) {
		var elements = d3.selectAll(selector);
		if (elements.empty()) {
			return;
		}

		styles.forEach(function (style) {
			elements.each(function () {
				var element = d3.select(this);
				if (!shouldntChangeInlineCss(element, style.name)) {
					element.style(style.name, style.value);
				}
			});
		});
	}

	function shouldntChangeInlineCss(element, style) {
		return style === "fill" && hasBackgroundColorSet(element);
	}

	function hasBackgroundColorSet(element) {
		var data = element.datum();
		return data.backgroundColor && !!data.backgroundColor();
	}

	/**
	 * For example the pin of the pick&pin module should be invisible in the exported graphic.
	 */
	function hideNonExportableElements() {
		d3.selectAll(".hidden-in-export").style("display", "none");
	}

	function removeVowlInlineStyles() {
		d3.selectAll(".text, .subtext, .text.instance-count, .external + text .instance-count, .cardinality, .text, .embedded, .class, .object, .disjoint, .objectproperty, .disjointwith, .equivalentproperty, .transitiveproperty, .functionalproperty, .inversefunctionalproperty, .symmetricproperty, .allvaluesfromproperty, .somevaluesfromproperty, .label .datatype, .datatypeproperty, .rdf, .rdfproperty, .literal, .node .datatype, .deprecated, .deprecatedproperty, .external, .externalproperty, path, .nofill, .symbol, .values-from.filled, marker path, .class, path, line, .fineline, .white, .subclass, .subclassproperty, .external + text, .class.hovered, .property.hovered, .cardinality.hovered, .cardinality.focused, circle.pin, .filled.hovered, .filled.focused, .focused, path.hovered, .indirect-highlighting, .feature:hover, .values-from, .class, path, line, .fineline, .dashed, .anonymous, .dotted, rect.focused, circle.focused, .nostroke, marker path")
			.each(function () {
				var element = d3.select(this);

				var inlineStyles = element.node().style;
				for (var styleName in inlineStyles) {
					if (inlineStyles.hasOwnProperty(styleName)) {
						if (shouldntChangeInlineCss(element, styleName)) {
							continue;
						}
						element.style(styleName, null);
					}
				}
			});
	}

	function showNonExportableElements() {
		d3.selectAll(".hidden-in-export").style("display", null);
	}

	function exportJson() {
		if (!exportableJsonText) {
			alert("No graph data available.");
			// Stop the redirection to the path of the href attribute
			d3.event.preventDefault();
			return;
		}

		var dataURI = "data:text/json;charset=utf-8," + encodeURIComponent(exportableJsonText);
		exportJsonButton.attr("href", dataURI)
			.attr("download", exportFilename + ".json");
	}

	return exportMenu;
};
<commit_msg>Remove unused import<commit_after>/**
 * Contains the logic for the export button.
 * @returns {{}}
 */
module.exports = function (graph) {

	var exportMenu = {},
		exportSvgButton,
		exportFilename,
		exportJsonButton,
		exportableJsonText;

	/**
	 * Adds the export button to the website.
	 */
	exportMenu.setup = function () {
		exportSvgButton = d3.select("#exportSvg")
			.on("click", exportSvg);
		exportJsonButton = d3.select("#exportJson")
			.on("click", exportJson);
	};

	exportMenu.setFilename = function (filename) {
		exportFilename = filename || "export";
	};

	exportMenu.setJsonText = function (jsonText) {
		exportableJsonText = jsonText;
	};

	function exportSvg() {
		// Get the d3js SVG element
		var graphSvg = d3.select(graph.options().graphContainerSelector()).select("svg"),
			graphSvgCode,
			escapedGraphSvgCode,
			dataURI;

		// inline the styles, so that the exported svg code contains the css rules
		inlineVowlStyles();
		hideNonExportableElements();

		graphSvgCode = graphSvg.attr("version", 1.1)
			.attr("xmlns", "http://www.w3.org/2000/svg")
			.node().parentNode.innerHTML;

		// Insert the reference to VOWL
		graphSvgCode = "<!-- Created with WebVOWL (version " + webvowl.version + ")" +
		               ", http://vowl.visualdataweb.org -->\n" + graphSvgCode;

		escapedGraphSvgCode = escapeUnicodeCharacters(graphSvgCode);
		//btoa(); Creates a base-64 encoded ASCII string from a "string" of binary data.
		dataURI = "data:image/svg+xml;base64," + btoa(escapedGraphSvgCode);

		exportSvgButton.attr("href", dataURI)
			.attr("download", exportFilename + ".svg");

		// remove graphic styles for interaction to go back to normal
		removeVowlInlineStyles();
		showNonExportableElements();
	}

	function escapeUnicodeCharacters(text) {
		var textSnippets = [],
			i, textLength = text.length,
			character,
			charCode;

		for (i = 0; i < textLength; i++) {
			character = text.charAt(i);
			charCode = character.charCodeAt(0);

			if (charCode < 128) {
				textSnippets.push(character);
			} else {
				textSnippets.push("&#" + charCode + ";");
			}
		}

		return textSnippets.join("");
	}

	function inlineVowlStyles() {
		setStyleSensitively(".text", [{name: "font-family", value: "Helvetica, Arial, sans-serif"}, {name: "font-size", value: "12px"}]);
		setStyleSensitively(".subtext", [{name: "font-size", value: "9px"}]);
		setStyleSensitively(".text.instance-count", [{name: "fill", value: "#666"}]);
		setStyleSensitively(".external + text .instance-count", [{name: "fill", value: "#aaa"}]);
		setStyleSensitively(".cardinality", [{name: "font-size", value: "10px"}]);
		setStyleSensitively(".text, .embedded", [{name: "pointer-events", value: "none"}]);
		setStyleSensitively(".class, .object, .disjoint, .objectproperty, .disjointwith, .equivalentproperty, .transitiveproperty, .functionalproperty, .inversefunctionalproperty, .symmetricproperty, .allvaluesfromproperty, .somevaluesfromproperty", [{name: "fill", value: "#acf"}]);
		setStyleSensitively(".label .datatype, .datatypeproperty", [{name: "fill", value: "#9c6"}]);
		setStyleSensitively(".rdf, .rdfproperty", [{name: "fill", value: "#c9c"}]);
		setStyleSensitively(".literal, .node .datatype", [{name: "fill", value: "#fc3"}]);
		setStyleSensitively(".deprecated, .deprecatedproperty", [{name: "fill", value: "#ccc"}]);
		setStyleSensitively(".external, .externalproperty", [{name: "fill", value: "#36c"}]);
		setStyleSensitively("path, .nofill", [{name: "fill", value: "none"}]);
		setStyleSensitively("marker path", [{name: "fill", value: "#000"}]);
		setStyleSensitively(".class, path, line, .fineline", [{name: "stroke", value: "#000"}]);
		setStyleSensitively(".white, .subclass, .subclassproperty, .external + text", [{name: "fill", value: "#fff"}]);
		setStyleSensitively(".class.hovered, .property.hovered, .cardinality.hovered, .cardinality.focused, circle.pin, .filled.hovered, .filled.focused", [{name: "fill", value: "#f00"}, {name: "cursor", value: "pointer"}]);
		setStyleSensitively(".focused, path.hovered", [{name: "stroke", value: "#f00"}]);
		setStyleSensitively(".indirect-highlighting, .feature:hover", [{name: "fill", value: "#f90"}]);
		setStyleSensitively(".values-from", [{name: "stroke", value: "#69c"}]);
		setStyleSensitively(".symbol, .values-from.filled", [{name: "fill", value: "#69c"}]);
		setStyleSensitively(".class, path, line", [{name: "stroke-width", value: "2"}]);
		setStyleSensitively(".fineline", [{name: "stroke-width", value: "1"}]);
		setStyleSensitively(".dashed, .anonymous", [{name: "stroke-dasharray", value: "8"}]);
		setStyleSensitively(".dotted", [{name: "stroke-dasharray", value: "3"}]);
		setStyleSensitively("rect.focused, circle.focused", [{name: "stroke-width", value: "4px"}]);
		setStyleSensitively(".nostroke", [{name: "stroke", value: "none"}]);
		setStyleSensitively("marker path", [{name: "stroke-dasharray", value: "100"}]);
	}

	function setStyleSensitively(selector, styles) {
		var elements = d3.selectAll(selector);
		if (elements.empty()) {
			return;
		}

		styles.forEach(function (style) {
			elements.each(function () {
				var element = d3.select(this);
				if (!shouldntChangeInlineCss(element, style.name)) {
					element.style(style.name, style.value);
				}
			});
		});
	}

	function shouldntChangeInlineCss(element, style) {
		return style === "fill" && hasBackgroundColorSet(element);
	}

	function hasBackgroundColorSet(element) {
		var data = element.datum();
		return data.backgroundColor && !!data.backgroundColor();
	}

	/**
	 * For example the pin of the pick&pin module should be invisible in the exported graphic.
	 */
	function hideNonExportableElements() {
		d3.selectAll(".hidden-in-export").style("display", "none");
	}

	function removeVowlInlineStyles() {
		d3.selectAll(".text, .subtext, .text.instance-count, .external + text .instance-count, .cardinality, .text, .embedded, .class, .object, .disjoint, .objectproperty, .disjointwith, .equivalentproperty, .transitiveproperty, .functionalproperty, .inversefunctionalproperty, .symmetricproperty, .allvaluesfromproperty, .somevaluesfromproperty, .label .datatype, .datatypeproperty, .rdf, .rdfproperty, .literal, .node .datatype, .deprecated, .deprecatedproperty, .external, .externalproperty, path, .nofill, .symbol, .values-from.filled, marker path, .class, path, line, .fineline, .white, .subclass, .subclassproperty, .external + text, .class.hovered, .property.hovered, .cardinality.hovered, .cardinality.focused, circle.pin, .filled.hovered, .filled.focused, .focused, path.hovered, .indirect-highlighting, .feature:hover, .values-from, .class, path, line, .fineline, .dashed, .anonymous, .dotted, rect.focused, circle.focused, .nostroke, marker path")
			.each(function () {
				var element = d3.select(this);

				var inlineStyles = element.node().style;
				for (var styleName in inlineStyles) {
					if (inlineStyles.hasOwnProperty(styleName)) {
						if (shouldntChangeInlineCss(element, styleName)) {
							continue;
						}
						element.style(styleName, null);
					}
				}
			});
	}

	function showNonExportableElements() {
		d3.selectAll(".hidden-in-export").style("display", null);
	}

	function exportJson() {
		if (!exportableJsonText) {
			alert("No graph data available.");
			// Stop the redirection to the path of the href attribute
			d3.event.preventDefault();
			return;
		}

		var dataURI = "data:text/json;charset=utf-8," + encodeURIComponent(exportableJsonText);
		exportJsonButton.attr("href", dataURI)
			.attr("download", exportFilename + ".json");
	}

	return exportMenu;
};
<|endoftext|>


<commit_before>var getItemDetails = require('./../../config.js').config.dataService.getItemDetails;

function init(pageTitle, feedItem){
	var page = tabris.create("Page", { title: "Loading...", topLevel: false, _feedItem: feedItem });
	addItemWebView(page,feedItem, pageTitle);

	return page;
}

/*************************
 * Add the webview with the feed content.
 **************************/

var handlers = {
	html : function(webView, itemDetails, container, titleOnLoad){
		webView.set("html", itemDetails.content );
		if(titleOnLoad){
			container.set({title:titleOnLoad});
		}
	},
	url : function(webView, itemDetails, container, titleOnLoad){
		webView.set("url", itemDetails.content );
		if(titleOnLoad){
			webView.on("load",function(){
				container.set({title:titleOnLoad});
			});
		}
	},
};

function addItemWebView(container, feedItem, titleOnLoad){
	var itemWebView = tabris.create('WebView',{ left: 0, right: 0, top: 0, bottom: 0}).appendTo(container);
	container.set('_itemWebView', itemWebView);

	var itemDetails = getItemDetails(feedItem);
	handlers[itemDetails.type] (itemWebView, itemDetails, container, titleOnLoad);
}

function open(pageTitle, feedItem) {
	var p = init(pageTitle, feedItem);
	return p.open();
}

module.exports  = {
	open: open,
	init: init,
	addItemWebView: addItemWebView,
};
<commit_msg>open item in new url<commit_after>var getItemDetails = require('./../../config.js').config.dataService.getItemDetails;

function init(pageTitle, feedItem){
	var page = tabris.create("Page", { title: "Loading...", topLevel: false, _feedItem: feedItem });
	addItemWebView(page,feedItem, pageTitle);
	registerPageActions(page, feedItem);

	return page;
}

/*************************
 * Add the webview with the feed content.
 **************************/

var handlers = {
	html : function(webView, itemDetails, container, titleOnLoad){
		webView.set("html", itemDetails.content );
		if(titleOnLoad){
			container.set({title:titleOnLoad});
		}
	},
	url : function(webView, itemDetails, container, titleOnLoad){
		webView.set("url", itemDetails.content );
		if(titleOnLoad){
			webView.on("load",function(){
				container.set({title:titleOnLoad});
			});
		}
	},
};

function addItemWebView(container, feedItem, titleOnLoad){
	var itemWebView = tabris.create('WebView',{ left: 0, right: 0, top: 0, bottom: 0}).appendTo(container);
	container.set('_itemWebView', itemWebView);

	var itemDetails = getItemDetails(feedItem);
	handlers[itemDetails.type] (itemWebView, itemDetails, container, titleOnLoad);
}

function open(pageTitle, feedItem) {
	var p = init(pageTitle, feedItem);
	return p.open();
}

function registerPageActions(page, feedItem){
	//tabris.create("Action", {
	//	placementPriority: "low",
	//	title: " ",
	//	image: {src:"images/info@2x.png", scale:4}
	//}).on("select", function() {
	//	aboutPage.open();
	//});
	//
	//tabris.create("Action", {
	//	placementPriority: "normal",
	//	title: "Bookmark",
	//	//image: {src:"images/search@2x.png", scale:4}
	//}).on("select", function() {
	//	aboutPage.open();
	//});

	var openURLAction = tabris.create("Action", {
		placementPriority: "high",
		title: " ",
		image: {src:"images/home@2x.png", scale:4}
	}).on("select", function() {
		var itemDetails = getItemDetails(feedItem);
		var appLauncher = tabris.create("AppLauncher");
		appLauncher.openUrl(itemDetails.link || itemDetails.content);
	});
	page.on("disappear", function(){
		openURLAction.dispose();
	});

}

module.exports  = {
	open: open,
	init: init,
	addItemWebView: addItemWebView,
};
<|endoftext|>


<commit_before>const list = `
bnchdrff
`
    .trim()
    .split('\n');

export default list;
<commit_msg>un-gdpr myself<commit_after>const list = `
`
    .trim()
    .split('\n');

export default list;
<|endoftext|>


<commit_before>/*
 * GridGallery is a plugin that will generate a grid depending on
 * the elements width and height. it is not required to have the same height
 * also you can enable/disable show lightbox effect to load content
 *
 * license: under MIT
 *          https://github.com/pencilpix/grid-gallery/blob/master/LICENSE
 * Author: Mohamed Hassan
 * Author Url: mohamedhassan@me
 */
(function($doc, $win){
  'use strict';

  /*=========================
   * @private helper functions
   *=========================*/

   /*
    * _extend Private method that extends an object using
    * properties of another object.
    * @param { Object } obj1 The object that will be extended
    * @param { Object } obj2 The object that will be used to extend another.
    *
    * @return { Object } obj1 The first object after being extended.
    */
  function _extend(obj1, obj2) {
    for ( var prop in obj2 ) {
      if ( obj2.hasOwnProperty(prop) ) {
        obj1[prop] = obj2[prop];
      }
    }

    return obj1;
  }

  /*
   * _checkItems Private method that check if GridGallery enabled on items
   * @param { Array-like } items The grid elements.
   * @return { Array } notEnabled The grid items that not set yet.
   */
  function _checkItems(items) {
    var notEnabled = Array.prototype.filter.call(items, function(item) {
      var pattern = new RegExp('grid-gallery__item');
      if(!item.dataset.grid && pattern.test(item.className)){
        return item;
      }
    });

    if (notEnabled.length){
      return notEnabled;
    }
  }

  /**
   * method that return the whitespace after get the available number of
   * items will be distributed through the parent width
   * @param  { Number } parentWidth width of the container
   * @param  { Number } itemWidth the item width
   * @return { Number } whiteSpace.
   */
  function _calWhiteSpace (parentWidth, itemWidth) {
    var itemsNo = Math.floor(parentWidth / itemWidth);
    return parentWidth - itemWidth * itemsNo;
  }

  /*
   * _enableItems Private method to handle un-enabled grid items
   * and give each element position and data-grid attribute.
   * @param { Array } items un-enabled elements.
   * @retrun { Array } enabled elements after update position
   * and data-grid.
   */
  function _enableItems(items) {
    var parentPos = items[0].parentNode.getBoundingClientRect();
    var rowItemsNo = Math.floor(parentPos.width / items[0].offsetWidth);
    var nextPos = [];
    var prevItem, parentHeight;
    var whiteSpace = _calWhiteSpace(parentPos.width, items[0].offsetWidth);

    // enable elements and set each item position
    var enabled = items.map(function(item, index, ar) {
     if(index === 0) {
       item.style.top = 0;
       item.style.left = whiteSpace / 2 + 'px';

       nextPos[0] = {
         top: item.offsetHeight,
         left: 0
       }
     } else if(index < rowItemsNo) {
       prevItem = ar[index - 1];

       item.style.top = 0;
       item.style.left = prevItem.offsetLeft + prevItem.offsetWidth + 'px';

       nextPos[index] = {
         top: item.offsetHeight,
         left: item.offsetLeft
       };
     } else if(index % rowItemsNo <= nextPos.length){
       var posIndex = index % rowItemsNo;

       item.style.top = nextPos[posIndex].top + 'px';
       item.style.left = (posIndex) ? nextPos[posIndex].left + 'px' : (whiteSpace / 2) + 'px';

       nextPos[posIndex] = {
         top: item.offsetTop + item.offsetHeight,
         left: item.offsetLeft
       };
     }

     item.dataset.grid = true;
    });

    // set container height
    parentHeight = nextPos.reduce(function(prevPos, pos) {
      if(prevPos > pos.top) {
        return prevPos;
      } else {
        prevPos = pos.top;
        return prevPos;
      }
    }, nextPos[0].top);

    items[0].parentNode.style.height = parentHeight + 'px';
    return enabled;
  }

  /*
   * class constructor of GridGallery component
   * @param { HTMLElement } element The element that will be the container.
   * @param { Object } options The options to initialize the component.
   */
  function GridGallery(element, options) {
    var _defaultOptions = { lightBox: false };

    this.element = element;

    this.options = _extend({}, _defaultOptions); // extend options to default
    this.options = _extend(this.options, options); // extend default to custom

    this.init();
  }

  /*
   * init this method that do the rest of initialization
   * work and updates the dom.
   */
  GridGallery.prototype.init = function() {
    _enableItems(_checkItems(this.element.children))
  };

  /* test-code */
  GridGallery.prototype.__test__ = {
    extend:        _extend,
    checkItems:    _checkItems,
    calWhiteSpace: _calWhiteSpace,
    enableItems:   _enableItems
  }
  /* end-test-code */

  $win.GridGallery = GridGallery; // makes the component globally exist.
})(document, window);

<commit_msg>fix the file head<commit_after>/*
 * GridGallery is a plugin that will generate a grid depending on
 * the elements width and height. it is not required to have the same height
 * also you can enable/disable show lightbox effect to load content
 *
 * license:     under MIT
 *              https: //github.com/pencilpix/grid-gallery/blob/master/LICENSE
 * Author:      Mohamed Hassan
 * Author Url:  http://mohamedhassan.me
 */
(function($doc, $win){
  'use strict';

  /*=========================
   * @private helper functions
   *=========================*/

   /*
    * _extend Private method that extends an object using
    * properties of another object.
    * @param { Object } obj1 The object that will be extended
    * @param { Object } obj2 The object that will be used to extend another.
    *
    * @return { Object } obj1 The first object after being extended.
    */
  function _extend(obj1, obj2) {
    for ( var prop in obj2 ) {
      if ( obj2.hasOwnProperty(prop) ) {
        obj1[prop] = obj2[prop];
      }
    }

    return obj1;
  }

  /*
   * _checkItems Private method that check if GridGallery enabled on items
   * @param { Array-like } items The grid elements.
   * @return { Array } notEnabled The grid items that not set yet.
   */
  function _checkItems(items) {
    var notEnabled = Array.prototype.filter.call(items, function(item) {
      var pattern = new RegExp('grid-gallery__item');
      if(!item.dataset.grid && pattern.test(item.className)){
        return item;
      }
    });

    if (notEnabled.length){
      return notEnabled;
    }
  }

  /**
   * method that return the whitespace after get the available number of
   * items will be distributed through the parent width
   * @param  { Number } parentWidth width of the container
   * @param  { Number } itemWidth the item width
   * @return { Number } whiteSpace.
   */
  function _calWhiteSpace (parentWidth, itemWidth) {
    var itemsNo = Math.floor(parentWidth / itemWidth);
    return parentWidth - itemWidth * itemsNo;
  }

  /*
   * _enableItems Private method to handle un-enabled grid items
   * and give each element position and data-grid attribute.
   * @param { Array } items un-enabled elements.
   * @retrun { Array } enabled elements after update position
   * and data-grid.
   */
  function _enableItems(items) {
    var parentPos = items[0].parentNode.getBoundingClientRect();
    var rowItemsNo = Math.floor(parentPos.width / items[0].offsetWidth);
    var nextPos = [];
    var prevItem, parentHeight;
    var whiteSpace = _calWhiteSpace(parentPos.width, items[0].offsetWidth);

    // enable elements and set each item position
    var enabled = items.map(function(item, index, ar) {
     if(index === 0) {
       item.style.top = 0;
       item.style.left = whiteSpace / 2 + 'px';

       nextPos[0] = {
         top: item.offsetHeight,
         left: 0
       }
     } else if(index < rowItemsNo) {
       prevItem = ar[index - 1];

       item.style.top = 0;
       item.style.left = prevItem.offsetLeft + prevItem.offsetWidth + 'px';

       nextPos[index] = {
         top: item.offsetHeight,
         left: item.offsetLeft
       };
     } else if(index % rowItemsNo <= nextPos.length){
       var posIndex = index % rowItemsNo;

       item.style.top = nextPos[posIndex].top + 'px';
       item.style.left = (posIndex) ? nextPos[posIndex].left + 'px' : (whiteSpace / 2) + 'px';

       nextPos[posIndex] = {
         top: item.offsetTop + item.offsetHeight,
         left: item.offsetLeft
       };
     }

     item.dataset.grid = true;
    });

    // set container height
    parentHeight = nextPos.reduce(function(prevPos, pos) {
      if(prevPos > pos.top) {
        return prevPos;
      } else {
        prevPos = pos.top;
        return prevPos;
      }
    }, nextPos[0].top);

    items[0].parentNode.style.height = parentHeight + 'px';
    return enabled;
  }

  /*
   * class constructor of GridGallery component
   * @param { HTMLElement } element The element that will be the container.
   * @param { Object } options The options to initialize the component.
   */
  function GridGallery(element, options) {
    var _defaultOptions = { lightBox: false };

    this.element = element;

    this.options = _extend({}, _defaultOptions); // extend options to default
    this.options = _extend(this.options, options); // extend default to custom

    this.init();
  }

  /*
   * init this method that do the rest of initialization
   * work and updates the dom.
   */
  GridGallery.prototype.init = function() {
    _enableItems(_checkItems(this.element.children))
  };

  /* test-code */
  GridGallery.prototype.__test__ = {
    extend:        _extend,
    checkItems:    _checkItems,
    calWhiteSpace: _calWhiteSpace,
    enableItems:   _enableItems
  }
  /* end-test-code */

  $win.GridGallery = GridGallery; // makes the component globally exist.
})(document, window);

<|endoftext|>


<commit_before>/*
 * GridGallery is a plugin that will generate a grid depending on
 * the elements width and height. it is not required to have the same height
 * also you can enable/disable show lightbox effect to load content
 *
 * license:     under MIT
 *              https: //github.com/pencilpix/grid-gallery/blob/master/LICENSE
 * Author:      Mohamed Hassan
 * Author Url:  http://mohamedhassan.me
 */
(function($doc, $win){
  'use strict';

  /*=========================
   * @private helper functions
   *=========================*/

   /*
    * _extend Private method that extends an object using
    * properties of another object.
    * @param { Object } obj1 The object that will be extended
    * @param { Object } obj2 The object that will be used to extend another.
    *
    * @return { Object } obj1 The first object after being extended.
    */
  function _extend(obj1, obj2) {
    for ( var prop in obj2 ) {
      if ( obj2.hasOwnProperty(prop) ) {
        obj1[prop] = obj2[prop];
      }
    }

    return obj1;
  }

  /*
   * _checkItems Private method that check if GridGallery enabled on items
   * @param { Array-like } items The grid elements.
   * @return { Array } notEnabled The grid items that not set yet.
   */
  function _checkItems(items) {
    var notEnabled = Array.prototype.filter.call(items, function(item) {
      var pattern = new RegExp('grid-gallery__item');
      if(!item.dataset.grid && pattern.test(item.className)){
        return item;
      }
    });

    if (notEnabled.length){
      return notEnabled;
    }
  }

  /**
   * disables all items via data-grid
   * @param  { Array-like } items grid items
   * @return { Array }       array of items after clearing data-grid.
   */
  function _disableAll(items) {
    return Array.prototype.map.call(items, function(item){
      item.dataset.grid = '';
      return item;
    });
  }

  /**
   * method that return the whitespace after get the available number of
   * items will be distributed through the parent width
   * @param  { Number } parentWidth width of the container
   * @param  { Number } itemWidth the item width
   * @return { Number } whiteSpace.
   */
  function _calWhiteSpace (parentWidth, itemWidth) {
    var itemsNo = Math.floor(parentWidth / itemWidth);
    return parentWidth - itemWidth * itemsNo;
  }

  /*
   * _enableItems Private method to handle un-enabled grid items
   * and give each element position and data-grid attribute.
   * @param { Array } items un-enabled elements.
   * @retrun { Array } enabled elements after update position
   * and data-grid.
   */
  function _enableItems(items) {
    var parentPos = items[0].parentNode.getBoundingClientRect();
    var rowItemsNo = Math.floor(parentPos.width / items[0].offsetWidth);
    var nextPos = [];
    var prevItem, parentHeight;
    var whiteSpace = _calWhiteSpace(parentPos.width, items[0].offsetWidth);

    // enable elements and set each item position
    var enabled = items.map(function(item, index, ar) {
     if(index === 0) {
       item.style.top = 0;
       item.style.left = whiteSpace / 2 + 'px';

       nextPos[0] = {
         top: item.offsetHeight,
         left: 0
       }
     } else if(index < rowItemsNo) {
       prevItem = ar[index - 1];

       item.style.top = 0;
       item.style.left = prevItem.offsetLeft + prevItem.offsetWidth + 'px';

       nextPos[index] = {
         top: item.offsetHeight,
         left: item.offsetLeft
       };
     } else if(index % rowItemsNo <= nextPos.length){
       var posIndex = index % rowItemsNo;

       item.style.top = nextPos[posIndex].top + 'px';
       item.style.left = (posIndex) ? nextPos[posIndex].left + 'px' : (whiteSpace / 2) + 'px';

       nextPos[posIndex] = {
         top: item.offsetTop + item.offsetHeight,
         left: item.offsetLeft
       };
     }

     item.dataset.grid = true;
    });

    // set container height
    parentHeight = nextPos.reduce(function(prevPos, pos) {
      if(prevPos > pos.top) {
        return prevPos;
      } else {
        prevPos = pos.top;
        return prevPos;
      }
    }, nextPos[0].top);

    items[0].parentNode.style.height = parentHeight + 'px';
    return enabled;
  }

  /*
   * class constructor of GridGallery component
   * @param { HTMLElement } element The element that will be the container.
   * @param { Object } options The options to initialize the component.
   */
  function GridGallery(element, options) {
    var _defaultOptions = { lightBox: false };

    this.element = element;

    this.options = _extend({}, _defaultOptions); // extend options to default
    this.options = _extend(this.options, options); // extend default to custom

    this.init();
  }

  /*
   * init this method that do the rest of initialization
   * work and updates the dom.
   */
  GridGallery.prototype.init = function() {
    var _self = this,
        resizeTimeout;

    _enableItems(_checkItems(this.element.children));

    window.addEventListener('resize', resizeHandler);

    function resizeHandler() {
      clearTimeout(resizeTimeout);

      resizeTimeout = setTimeout(function(){
        _self.update();
      }, 250);
    }
  };

  GridGallery.prototype.update = function() {
    _disableAll(this.element.querySelectorAll('.grid-gallery__item'));
    _enableItems(_checkItems(this.element.children));
  };

  /* test-code */
  GridGallery.prototype.__test__ = {
    extend:        _extend,
    checkItems:    _checkItems,
    calWhiteSpace: _calWhiteSpace,
    enableItems:   _enableItems,
    disableAll: _disableAll
  }
  /* end-test-code */

  $win.GridGallery = GridGallery; // makes the component globally exist.

})(document, window);

<commit_msg>refactor positioning items '_enableItems' to use data attributes for positioning to fix the issue of animation delay<commit_after>/*
 * GridGallery is a plugin that will generate a grid depending on
 * the elements width and height. it is not required to have the same height
 * also you can enable/disable show lightbox effect to load content
 *
 * license:     under MIT
 *              https: //github.com/pencilpix/grid-gallery/blob/master/LICENSE
 * Author:      Mohamed Hassan
 * Author Url:  http://mohamedhassan.me
 */
(function($doc, $win){
  'use strict';

  /*=========================
   * @private helper functions
   *=========================*/

   /*
    * _extend Private method that extends an object using
    * properties of another object.
    * @param { Object } obj1 The object that will be extended
    * @param { Object } obj2 The object that will be used to extend another.
    *
    * @return { Object } obj1 The first object after being extended.
    */
  function _extend(obj1, obj2) {
    for ( var prop in obj2 ) {
      if ( obj2.hasOwnProperty(prop) ) {
        obj1[prop] = obj2[prop];
      }
    }

    return obj1;
  }

  /*
   * _checkItems Private method that check if GridGallery enabled on items
   * @param { Array-like } items The grid elements.
   * @return { Array } notEnabled The grid items that not set yet.
   */
  function _checkItems(items) {
    var notEnabled = Array.prototype.filter.call(items, function(item) {
      var pattern = new RegExp('grid-gallery__item');
      if(!item.dataset.grid && pattern.test(item.className)){
        return item;
      }
    });

    if (notEnabled.length){
      return notEnabled;
    }
  }

  /**
   * disables all items via data-grid
   * @param  { Array-like } items grid items
   * @return { Array }       array of items after clearing data-grid.
   */
  function _disableAll(items) {
    return Array.prototype.map.call(items, function(item){
      item.dataset.grid = '';
      return item;
    });
  }

  /**
   * method that return the whitespace after get the available number of
   * items will be distributed through the parent width
   * @param  { Number } parentWidth width of the container
   * @param  { Number } itemWidth the item width
   * @return { Number } whiteSpace.
   */
  function _calWhiteSpace (parentWidth, itemWidth) {
    var itemsNo = Math.floor(parentWidth / itemWidth);
    return parentWidth - itemWidth * itemsNo;
  }

  /*
   * _enableItems Private method to handle un-enabled grid items
   * and give each element position and data-grid attribute.
   * @param { Array } items un-enabled elements.
   * @retrun { Array } enabled elements after update position
   * and data-grid.
   */
  function _enableItems(items) {
    var parentPos = items[0].parentNode.getBoundingClientRect();
    var rowItemsNo = Math.floor(parentPos.width / items[0].offsetWidth);
    var nextPos = [];
    var prevItem, parentHeight;
    var whiteSpace = _calWhiteSpace(parentPos.width, items[0].offsetWidth);

    // enable elements and set each item position
    var enabled = items.map(function(item, index, ar) {
     if(index === 0) {
       item.dataset.top = 0;
       item.dataset.left = whiteSpace / 2;

       item.style.top = 0;
       item.style.left = whiteSpace / 2 + 'px';

       nextPos[0] = {
         top: item.offsetHeight,
         left: 0
       }
     } else if(index < rowItemsNo) {
       prevItem = ar[index - 1];

       item.dataset.top = 0;
       item.dataset.left = Number(prevItem.dataset.left) + prevItem.offsetWidth;

       item.style.top = 0;
       item.style.left = Number(prevItem.dataset.left) + prevItem.offsetWidth + 'px';

       nextPos[index] = {
         top: item.offsetHeight,
         left: Number(item.dataset.left)
       };
     } else if(index % rowItemsNo <= nextPos.length){
       var posIndex = index % rowItemsNo;

       item.dataset.top = nextPos[posIndex].top;
       item.dataset.left = (posIndex) ? nextPos[posIndex].left : (whiteSpace / 2);

       item.style.top = nextPos[posIndex].top + 'px';
       item.style.left = (posIndex) ? nextPos[posIndex].left + 'px' : (whiteSpace / 2) + 'px';

       nextPos[posIndex] = {
         top: Number(item.dataset.top) + item.offsetHeight,
         left: Number(item.dataset.left)
       };
     }

     item.dataset.grid = true;
    });

    // set container height
    parentHeight = nextPos.reduce(function(prevPos, pos) {
      if(prevPos > pos.top) {
        return prevPos;
      } else {
        prevPos = pos.top;
        return prevPos;
      }
    }, nextPos[0].top);

    items[0].parentNode.style.height = parentHeight + 'px';
    return enabled;
  }

  /*
   * class constructor of GridGallery component
   * @param { HTMLElement } element The element that will be the container.
   * @param { Object } options The options to initialize the component.
   */
  function GridGallery(element, options) {
    var _defaultOptions = { lightBox: false };

    this.element = element;

    this.options = _extend({}, _defaultOptions); // extend options to default
    this.options = _extend(this.options, options); // extend default to custom

    this.init();
  }

  /*
   * init this method that do the rest of initialization
   * work and updates the dom.
   */
  GridGallery.prototype.init = function() {
    var _self = this,
        resizeTimeout;

    _enableItems(_checkItems(this.element.children));

    window.addEventListener('resize', resizeHandler);

    function resizeHandler() {
      clearTimeout(resizeTimeout);

      resizeTimeout = setTimeout(function(){
        _self.update();
      }, 250);
    }
  };

  GridGallery.prototype.update = function() {
    _disableAll(this.element.querySelectorAll('.grid-gallery__item'));
    _enableItems(_checkItems(this.element.children));
  };

  /* test-code */
  GridGallery.prototype.__test__ = {
    extend:        _extend,
    checkItems:    _checkItems,
    calWhiteSpace: _calWhiteSpace,
    enableItems:   _enableItems,
    disableAll: _disableAll
  }
  /* end-test-code */

  $win.GridGallery = GridGallery; // makes the component globally exist.

})(document, window);

<|endoftext|>


<commit_before>

export const dealDamage = (defChar, damage) => {
  console.log(`Dealing Damage`);
  const [data, , , status] = defChar;
  const shield = status.find(({ type }) => type === `shield`);
  if(shield) damage *= (1 - shield.effect);
  console.log(`Deal ${damage} Damage to ${data.name}`);
  defChar[1] -= damage;
};

export const heal = (defChar, heal) => {
  defChar[1] = Math.min(defChar[1] + heal, defChar[0].maxHealth);
};

export const handlStatuses = (character) => {
  const [, , , statuses] = character;
  console.log(`handling Statuses: ${statuses.length}`);
  character[3] = statuses.map((status) => --status.duration < 0 ? false : status).filter(x => x);
  statuses.forEach(status => {
    console.log(`handling Status: ${status.type}`);
    switch(status.type) {
      case `damage`:
        dealDamage(character, status.effect);
        break;
      case `heal`:
        heal(character, status.effect);
        break;
    }
  });
};
<commit_msg>Optimize<commit_after>

export const dealDamage = (defChar, damage) => {
  console.log(`Dealing Damage`);
  const [, , , status] = defChar;
  const shield = status.find(({ type }) => type === `shield`);
  if(shield) damage *= (1 - shield.effect);
  console.log(`Deal ${damage} Damage to ${defChar[0].name}`);
  defChar[1] -= damage;
};

export const heal =
  (defChar, heal) =>
    defChar[1] = Math.min(defChar[1] + heal, defChar[0].maxHealth);

export const handlStatuses = (character) => {
  const [, , , statuses] = character;
  console.log(`handling Statuses: ${statuses.length}`);
  character[3] = statuses.map((status) => --status.duration < 0 ? false : status).filter(x => x);
  statuses.forEach(status => {
    console.log(`handling Status: ${status.type}`);
    switch(status.type) {
      case `damage`:
        dealDamage(character, status.effect);
        break;
      case `heal`:
        heal(character, status.effect);
        break;
    }
  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2017 Intel Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const fs = require('mz/fs');
const fse = require('fs-extra');
const mkdirp = require('mkdirp');
const path = require('path');
const parser = require('../rosidl_parser/rosidl_parser.js');
const packages = require('./packages.js');
const dot = require('dot');
const os = require('os');

dot.templateSettings.strip = false;
dot.log = process.env.RCLNODEJS_LOG_VERBOSE || false;
const dots = dot.process({path: path.join(__dirname, '../rosidl_gen/templates')});

const generatedRoot = path.join(__dirname, '../generated/');
const installedPackagesRoot = (os.type() === 'Windows_NT')
                              ? process.env.AMENT_PREFIX_PATH.split(';')
                              : process.env.AMENT_PREFIX_PATH.split(':');

function removeExtraSpaceLines(str) {
  return str.replace(/^\s*\n/gm, '');
}

function removeAllIntermediateFiles(path) {
  return fse.remove(path);
}

function writeGeneratedCode(dir, fileName, code) {
  mkdirp.sync(dir);
  return fs.writeFile(dir + fileName, code);
}

function generateServiceJSStruct(serviceInfo) {
  const dir = path.join(generatedRoot, `${serviceInfo.pkgName}/`);
  const fileName = serviceInfo.pkgName + '__' + serviceInfo.subFolder + '__' + serviceInfo.interfaceName + '.js';
  const generatedCode = removeExtraSpaceLines(dots.service({serviceInfo: serviceInfo}));
  return writeGeneratedCode(dir, fileName, generatedCode);
}

function generateMessageJSStruct(messageInfo) {
  return new Promise((resolve, reject) => {
    parser.parseMessageFile(messageInfo.pkgName, messageInfo.filePath).then((spec) => {
      const dir = path.join(generatedRoot, `${spec.baseType.pkgName}/`);
      const fileName = spec.baseType.pkgName + '__' + messageInfo.subFolder + '__' + spec.msgName + '.js';

      const generatedCode = removeExtraSpaceLines(dots.message({
        messageInfo: messageInfo,
        spec: spec,
        json: JSON.stringify(spec, null, '  '),
      }));
      return writeGeneratedCode(dir, fileName, generatedCode);
    }).then(() => {
      resolve();
    }).catch((e) => {
      reject(e);
    });
  });
}

function generateStructForPkg(pkg) {
  return new Promise((resolve, reject) => {
    let promises = [];
    pkg.messages.forEach((messageInfo) => {
      promises.push(generateMessageJSStruct(messageInfo));
    });
    pkg.services.forEach((serviceInfo) => {
      promises.push(generateServiceJSStruct(serviceInfo));
    });

    Promise.all(promises).then(() => {
      resolve();
    }).catch((e) => {
      reject(e);
    });
  });
}

function generateAll(forcedGenerating) {
  return new Promise((resolve, reject) => {
    if (forcedGenerating || !generator.isRootGererated()) {
      fse.copy(path.join(__dirname, 'generator.json'), path.join(generatedRoot, 'generator.json'), err => {
        if (err) reject(err);
        installedPackagesRoot.forEach((packageRoot) => {
          let promises = [];
          packages.findPackagesInDirectory(packageRoot).then((pkgs) => {
            pkgs.forEach((pkg) => {
              promises.push(generateStructForPkg(pkg));
            });

            Promise.all(promises).then(() => {
              resolve();
            }).catch((e) => {
              reject(e);
            });
          }).catch((e) => {
            reject(e);
          });
        });
      });
    } else {
      resolve();
    }
  });
}

const generator = {
  generateAll: generateAll,

  generatedRoot: generatedRoot,

  generateForPackage(pkgName) {
    installedPackagesRoot.forEach((packageRoot) => {
      let packagePath = path.join(packageRoot, 'share', pkgName);

      // eslint-disable-next-line
      if (fs.existsSync(packagePath)) {
        findPackagesInDirectory(packagePath).then((pkg) => {
        });
      }
    });
  },

  isRootGererated() {
    // eslint-disable-next-line
    return fs.existsSync(generatedRoot);
  },

  version() {
    // eslint-disable-next-line
    return JSON.parse(fs.readFileSync(path.join(__dirname, 'generator.json'), 'utf8')).version;
  }
};

module.exports = generator;
<commit_msg>Wait for the generator to complete its work<commit_after>// Copyright (c) 2017 Intel Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const fs = require('mz/fs');
const fse = require('fs-extra');
const mkdirp = require('mkdirp');
const path = require('path');
const parser = require('../rosidl_parser/rosidl_parser.js');
const packages = require('./packages.js');
const dot = require('dot');
const os = require('os');

dot.templateSettings.strip = false;
dot.log = process.env.RCLNODEJS_LOG_VERBOSE || false;
const dots = dot.process({path: path.join(__dirname, '../rosidl_gen/templates')});

const generatedRoot = path.join(__dirname, '../generated/');
const installedPackagesRoot = (os.type() === 'Windows_NT')
                              ? process.env.AMENT_PREFIX_PATH.split(';')
                              : process.env.AMENT_PREFIX_PATH.split(':');

function removeExtraSpaceLines(str) {
  return str.replace(/^\s*\n/gm, '');
}

function removeAllIntermediateFiles(path) {
  return fse.remove(path);
}

function writeGeneratedCode(dir, fileName, code) {
  mkdirp.sync(dir);
  return fs.writeFile(dir + fileName, code);
}

function generateServiceJSStruct(serviceInfo) {
  const dir = path.join(generatedRoot, `${serviceInfo.pkgName}/`);
  const fileName = serviceInfo.pkgName + '__' + serviceInfo.subFolder + '__' + serviceInfo.interfaceName + '.js';
  const generatedCode = removeExtraSpaceLines(dots.service({serviceInfo: serviceInfo}));
  return writeGeneratedCode(dir, fileName, generatedCode);
}

function generateMessageJSStruct(messageInfo) {
  return new Promise((resolve, reject) => {
    parser.parseMessageFile(messageInfo.pkgName, messageInfo.filePath).then((spec) => {
      const dir = path.join(generatedRoot, `${spec.baseType.pkgName}/`);
      const fileName = spec.baseType.pkgName + '__' + messageInfo.subFolder + '__' + spec.msgName + '.js';

      const generatedCode = removeExtraSpaceLines(dots.message({
        messageInfo: messageInfo,
        spec: spec,
        json: JSON.stringify(spec, null, '  '),
      }));
      return writeGeneratedCode(dir, fileName, generatedCode);
    }).then(() => {
      resolve();
    }).catch((e) => {
      reject(e);
    });
  });
}

function generateStructForPkg(pkg) {
  return new Promise((resolve, reject) => {
    let promises = [];
    pkg.messages.forEach((messageInfo) => {
      promises.push(generateMessageJSStruct(messageInfo));
    });
    pkg.services.forEach((serviceInfo) => {
      promises.push(generateServiceJSStruct(serviceInfo));
    });

    Promise.all(promises).then(() => {
      resolve();
    }).catch((e) => {
      reject(e);
    });
  });
}

function generateInPath(path) {
  return new Promise((resolve, reject) => {
    let promises = [];
    packages.findPackagesInDirectory(path).then((pkgs) => {
      pkgs.forEach((pkg) => {
        promises.push(generateStructForPkg(pkg));
      });

      Promise.all(promises).then(() => {
        resolve();
      }).catch((e) => {
        reject(e);
      });
    }).catch((e) => {
      reject(e);
    });
  });
}

function generateAll(forcedGenerating) {
  return new Promise((resolve, reject) => {
    if (forcedGenerating || !generator.isRootGererated()) {
      fse.copy(path.join(__dirname, 'generator.json'), path.join(generatedRoot, 'generator.json'), err => {
        if (err) reject(err);

        let promises = [];
        installedPackagesRoot.forEach((packageRoot) => {
          promises.push(generateInPath(packageRoot));
        });

        Promise.all(promises).then(() => {
          resolve();
        }).catch((e) => {
          reject(e);
        });
      });
    } else {
      resolve();
    }
  });
}

const generator = {
  generateAll: generateAll,

  generatedRoot: generatedRoot,

  generateForPackage(pkgName) {
    installedPackagesRoot.forEach((packageRoot) => {
      let packagePath = path.join(packageRoot, 'share', pkgName);

      // eslint-disable-next-line
      if (fs.existsSync(packagePath)) {
        findPackagesInDirectory(packagePath).then((pkg) => {
        });
      }
    });
  },

  isRootGererated() {
    // eslint-disable-next-line
    return fs.existsSync(generatedRoot);
  },

  version() {
    // eslint-disable-next-line
    return JSON.parse(fs.readFileSync(path.join(__dirname, 'generator.json'), 'utf8')).version;
  }
};

module.exports = generator;
<|endoftext|>


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

// eslint-disable-next-line import/no-unresolved
import simpleExampleCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleStickerEditor';
// eslint-disable-next-line import/no-unresolved
import simpleExampleStickersCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleStickerEditor/stickers.js';
// eslint-disable-next-line import/no-unresolved
import simpleExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./SimpleStickerEditor/editorStyles.css';
// eslint-disable-next-line import/no-unresolved
import customExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomStickerEditor';
// eslint-disable-next-line import/no-unresolved
import customExampleStickersCode from '!!../../../loaders/prism-loader?language=javascript!./CustomStickerEditor/stickers.js';
// eslint-disable-next-line import/no-unresolved
import customExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomStickerEditor/editorStyles.css';
// eslint-disable-next-line import/no-unresolved
import gettingStarted from '!!../../../loaders/prism-loader?language=javascript!./gettingStarted';
// eslint-disable-next-line import/no-unresolved
import webpackConfig from '!!../../../loaders/prism-loader?language=javascript!./webpackConfig';
// eslint-disable-next-line import/no-unresolved
import webpackImport from '!!../../../loaders/prism-loader?language=javascript!./webpackImport';

import Container from '../../shared/Container';
import AlternateContainer from '../../shared/AlternateContainer';
import Heading from '../../shared/Heading';
import styles from './styles.css';
import Code from '../../shared/Code';
import SimpleStickerEditor from './SimpleStickerEditor';
import CustomStickerEditor from './CustomStickerEditor';
import ExternalLink from '../../shared/Link';
import InlineCode from '../../shared/InlineCode';
import SocialBar from '../../shared/SocialBar';
import NavBar from '../../shared/NavBar';
import Separator from '../../shared/Separator';

export default class App extends Component {
  render() {
    return (

        <NavBar />
        <Separator />
        <Container>
          <Heading level={2}>Sticker</Heading>
        </Container>
        <AlternateContainer>
          <Heading level={2}>Getting Started</Heading>

          <Heading level={3}>Importing the default styles</Heading>

            The plugin ships with a default styling available at this location in the installed package:

            <InlineCode code={'node_modules/draft-js-sticker-plugin/lib/plugin.css'} />

          <Heading level={4}>Webpack Usage</Heading>

              1. Install Webpack loaders:

              <InlineCode code={'npm i style-loader css-loader --save-dev'} />

              2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list.

              3. Add the below import line to your component to tell Webpack to inject the style to your component.

              4. Restart Webpack.

          <Heading level={4}>Browserify Usage</Heading>

            Please help, by submiting a Pull Request to the <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Sticker/index.js">documentation</ExternalLink>.

        </AlternateContainer>
        <Container>
          <Heading level={2}>Configuration Parameters</Heading>

            theme
            Object of CSS classes with the following keys.

sticker: CSS class for sticker.

stickerImage: CSS class for

stickerRemoveButton: CSS class for sticker remove button.

select: CSS class for sticker select.

selectPopover: CSS class for sticker select popup.

selectClosedPopover: CSS class for sticker select close button.

selectBottomGradient: CSS class for sticker select bottom gradient.

selectButton: CSS class for button to open sticker select.

selectPressedButton: CSS class for pressed state of button to open sticker select.

selectStickerList: CSS class for sticker select list.

selectSticker: CSS class for sticker select.

selectStickerImage: CSS class for sticker select image.

            stickers
            Immutable.js List of stickers.

            selectButtonContent
            Content of button which opens select sticker drop-down. (Default content is ☺)

            attachRemoveButton
            Flag to attach or detach a remove button to stickers. (Default value is true)

        </Container>
        <Container>
          <Heading level={2}>Simple Example</Heading>
          <SimpleStickerEditor />

        </Container>
        <Container>
          <Heading level={2}>Themed Sticker Example</Heading>
          <CustomStickerEditor />

        </Container>
        <SocialBar />

    );
  }
}
<commit_msg>[docs][draft-js-sticker-plugin] Fix typo<commit_after>import React, { Component } from 'react';

// eslint-disable-next-line import/no-unresolved
import simpleExampleCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleStickerEditor';
// eslint-disable-next-line import/no-unresolved
import simpleExampleStickersCode from '!!../../../loaders/prism-loader?language=javascript!./SimpleStickerEditor/stickers.js';
// eslint-disable-next-line import/no-unresolved
import simpleExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./SimpleStickerEditor/editorStyles.css';
// eslint-disable-next-line import/no-unresolved
import customExampleCode from '!!../../../loaders/prism-loader?language=javascript!./CustomStickerEditor';
// eslint-disable-next-line import/no-unresolved
import customExampleStickersCode from '!!../../../loaders/prism-loader?language=javascript!./CustomStickerEditor/stickers.js';
// eslint-disable-next-line import/no-unresolved
import customExampleEditorStylesCode from '!!../../../loaders/prism-loader?language=css!./CustomStickerEditor/editorStyles.css';
// eslint-disable-next-line import/no-unresolved
import gettingStarted from '!!../../../loaders/prism-loader?language=javascript!./gettingStarted';
// eslint-disable-next-line import/no-unresolved
import webpackConfig from '!!../../../loaders/prism-loader?language=javascript!./webpackConfig';
// eslint-disable-next-line import/no-unresolved
import webpackImport from '!!../../../loaders/prism-loader?language=javascript!./webpackImport';

import Container from '../../shared/Container';
import AlternateContainer from '../../shared/AlternateContainer';
import Heading from '../../shared/Heading';
import styles from './styles.css';
import Code from '../../shared/Code';
import SimpleStickerEditor from './SimpleStickerEditor';
import CustomStickerEditor from './CustomStickerEditor';
import ExternalLink from '../../shared/Link';
import InlineCode from '../../shared/InlineCode';
import SocialBar from '../../shared/SocialBar';
import NavBar from '../../shared/NavBar';
import Separator from '../../shared/Separator';

export default class App extends Component {
  render() {
    return (

        <NavBar />
        <Separator />
        <Container>
          <Heading level={2}>Sticker</Heading>
        </Container>
        <AlternateContainer>
          <Heading level={2}>Getting Started</Heading>

          <Heading level={3}>Importing the default styles</Heading>

            The plugin ships with a default styling available at this location in the installed package:

            <InlineCode code={'node_modules/draft-js-sticker-plugin/lib/plugin.css'} />

          <Heading level={4}>Webpack Usage</Heading>

              1. Install Webpack loaders:

              <InlineCode code={'npm i style-loader css-loader --save-dev'} />

              2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list.

              3. Add the below import line to your component to tell Webpack to inject the style to your component.

              4. Restart Webpack.

          <Heading level={4}>Browserify Usage</Heading>

            Please help, by submiting a Pull Request to the <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Sticker/index.js">documentation</ExternalLink>.

        </AlternateContainer>
        <Container>
          <Heading level={2}>Configuration Parameters</Heading>

            theme
            Object of CSS classes with the following keys.

sticker: CSS class for sticker.

stickerImage: CSS class for sticker image tag.

stickerRemoveButton: CSS class for sticker remove button.

select: CSS class for sticker select.

selectPopover: CSS class for sticker select popup.

selectClosedPopover: CSS class for sticker select close button.

selectBottomGradient: CSS class for sticker select bottom gradient.

selectButton: CSS class for button to open sticker select.

selectPressedButton: CSS class for pressed state of button to open sticker select.

selectStickerList: CSS class for sticker select list.

selectSticker: CSS class for sticker select.

selectStickerImage: CSS class for sticker select image.

            stickers
            Immutable.js List of stickers.

            selectButtonContent
            Content of button which opens select sticker drop-down. (Default content is ☺)

            attachRemoveButton
            Flag to attach or detach a remove button to stickers. (Default value is true)

        </Container>
        <Container>
          <Heading level={2}>Simple Example</Heading>
          <SimpleStickerEditor />

        </Container>
        <Container>
          <Heading level={2}>Themed Sticker Example</Heading>
          <CustomStickerEditor />

        </Container>
        <SocialBar />

    );
  }
}
<|endoftext|>


<commit_before>function Con(id, mode) {
  this.console = CodeMirror(document.getElementById(id), {
    mode: mode,
    lineNumbers: true
  });

  this.content = "";

  this.log = function(msg) {
    this.content = this.content + "\n" + msg;
    this.console.setValue(this.content);
    var line = this.console.lineCount();
    this.console.setCursor({line: line, ch: 0})
  }

  this.clear = function() {
    this.content = "";
    this.console.setValue(this.content);
  }
}

// After page load
$(function() {

  var editor = CodeMirror(document.getElementById("editor"), {
    value: "(* 2 3)",
    mode: "scheme",
    theme: "ambiance",
    indentUnit: 2,
    tabSize: 2,
    matchBrackets: true
  });

  var con = new Con("console", "diff");
  var envCon = new Con("environment", "javascript");

  editor.setValue("; type Scheem code into this box and press run\n\
; or press one of the three example buttons\n\n");

  var parser = Scheem.parser;
  var scheemParser = parser.buildParser();
  var evalScheem = Scheem.interpreter.evalScheem;
  var env = {};

  $('#run').click(function() {
    var user_text = editor.getValue();
//    con.log('\n' + user_text.trim());
    try {
      var parsed = scheemParser(user_text);
      try {
        var result = evalScheem(parsed, env);
        con.log('> ' + JSON.stringify(result));
        envCon.clear();
        envCon.log(JSON.stringify(env));
      }
      catch(e) {
        con.log('- Eval Error: ' + e);
      }
    }
    catch(e) {
      con.log('- Parse Error: ' + e);
    }
  });

  function allClear() {
    con.clear();
    env = {};
    envCon.clear();
  }

  $('#clear-output').click(function() {
    con.clear();
  });
  $('#clear-environment').click(function() {
    env = {};
    envCon.clear();
  });

  $('#ex-1').click(function() {
    allClear();
    editor.setValue("\n\
; declare variables\n\
(define a 12)\n\
(define b 34)\n\
\n\
(define c (+ a b a b a b))\n\
\n\
; redefine variables\n\
(set! a 20)\n\
\n\
(+ a c)\n\
");
  })

  $('#ex-2').click(function() {
    allClear();
    editor.setValue("\n\
; a list of two items\n\
(define some-list '(foo bar))\n\
\n\
(define d 100)\n\
(define e 120)\n\
\n\
; prepend the minimum of d and e onto some-list\n\
(cons (if (< d e) \n\
          'd \n\
          'e) \n\
      some-list)\n\
\n\
\n\
");
  })

  $('#ex-3').click(function() {
    allClear();
    editor.setValue("\n\
; which item in the list is the largest\n\
(define number-list '(4 3))\n\
\n\
(if (> (car number-list)\n\
       (car (cdr number-list)))\n\
    'first 'second)\n\
\n\
");
  })

});
<commit_msg>console textareas are read-only<commit_after>function Con(id, mode) {
  this.console = CodeMirror(document.getElementById(id), {
    mode: mode,
    lineNumbers: true,
    readOnly: true
  });

  this.content = "";

  this.log = function(msg) {
    this.content = this.content + "\n" + msg;
    this.console.setValue(this.content);
    var line = this.console.lineCount();
    this.console.setCursor({line: line, ch: 0})
  }

  this.clear = function() {
    this.content = "";
    this.console.setValue(this.content);
  }
}

// After page load
$(function() {

  var editor = CodeMirror(document.getElementById("editor"), {
    value: "(* 2 3)",
    mode: "scheme",
    theme: "ambiance",
    indentUnit: 2,
    tabSize: 2,
    matchBrackets: true
  });

  var con = new Con("console", "diff");
  var envCon = new Con("environment", "javascript");

  editor.setValue("; type Scheem code into this box and press run\n\
; or press one of the three example buttons\n\n");

  var parser = Scheem.parser;
  var scheemParser = parser.buildParser();
  var evalScheem = Scheem.interpreter.evalScheem;
  var env = {};

  $('#run').click(function() {
    var user_text = editor.getValue();
//    con.log('\n' + user_text.trim());
    try {
      var parsed = scheemParser(user_text);
      try {
        var result = evalScheem(parsed, env);
        con.log('> ' + JSON.stringify(result));
        envCon.clear();
        envCon.log(JSON.stringify(env, null, '\t'));
      }
      catch(e) {
        con.log('- Eval Error: ' + e);
      }
    }
    catch(e) {
      con.log('- Parse Error: ' + e);
    }
  });

  function allClear() {
    con.clear();
    env = {};
    envCon.clear();
  }

  $('#clear-output').click(function() {
    con.clear();
  });
  $('#clear-environment').click(function() {
    env = {};
    envCon.clear();
  });

  $('#ex-1').click(function() {
    allClear();
    editor.setValue("\n\
; declare variables\n\
(define a 12)\n\
(define b 34)\n\
\n\
(define c (+ a b a b a b))\n\
\n\
; redefine variables\n\
(set! a 20)\n\
\n\
(+ a c)\n\
");
  })

  $('#ex-2').click(function() {
    allClear();
    editor.setValue("\n\
; a list of two items\n\
(define some-list '(foo bar))\n\
\n\
(define d 100)\n\
(define e 120)\n\
\n\
; prepend the minimum of d and e onto some-list\n\
(cons (if (< d e) \n\
          'd \n\
          'e) \n\
      some-list)\n\
\n\
\n\
");
  })

  $('#ex-3').click(function() {
    allClear();
    editor.setValue("\n\
; which item in the list is the largest\n\
(define number-list '(4 3))\n\
\n\
(if (> (car number-list)\n\
       (car (cdr number-list)))\n\
    'first 'second)\n\
\n\
");
  })

});
<|endoftext|>