<commit_before>const TYPE = require('./type');

process.on('error', errors => {
    console.error(errors);
    process.exit(1);
});

global.console.log = (...message) => {
    process.send({
        cmd: TYPE.WORKER_CONSOLE_LOG,
        data: message
    });
};

global.console.error = (...message) => {
    process.send({
        cmd: TYPE.WORKER_CONSOLE_ERROR,
        data: message
    });
};

process.on('message', message => {
    if (!message) {
        return;
    }

    let cmd = message.cmd;
    let data = message.data;

    if (cmd === TYPE.WORKER_LAUNCH) {

        // 接收子进程消息
        let onmessage = (errors, message) => {

            if (errors) {
                errors = {
                    type: errors.constructor.name,
                    message: errors.message,
                    stack: errors.stack
                };
            }

            process.send({
                cmd: errors ? TYPE.WORKER_ERROR : TYPE.WORKER_SUCCESS,
                data: errors ? errors : message
            }, () => {
                process.exit(0);
            });
        };

        try {
            // 加载 Node 模块
            let worker = require(data.target);
            worker(...data.params, onmessage);
        } catch (errors) {
            // 向父进程报告错误堆栈
            process.send({
                cmd: TYPE.WORKER_ERROR,
                data: {
                    type: errors.constructor.name,
                    message: errors.message,
                    stack: errors.stack
                }
            }, () => {
                process.exit(1);
            });
        }
    } else if (cmd === TYPE.WORKER_EXIT) {
        process.exit(0);
    }
});

<commit_msg>重构console.log<commit_after>const TYPE = require('./type');

process.on('error', errors => {
    console.error(errors);
    process.exit(1);
});

// 代理 console，让日志能够顺序的显示
const proxyConsole = name => {
    let cmds = {
        log: TYPE.WORKER_CONSOLE_LOG,
        error: TYPE.WORKER_CONSOLE_ERROR
    };
    global.console[name] = (...message) => {
        process.send({
            cmd: cmds[name],
            data: message
        });
    };
};

proxyConsole('log');
proxyConsole('error');

process.on('message', message => {
    if (!message) {
        return;
    }

    let cmd = message.cmd;
    let data = message.data;

    if (cmd === TYPE.WORKER_LAUNCH) {

        // 接收子进程消息
        let onmessage = (errors, message) => {

            if (errors) {
                errors = {
                    type: errors.constructor.name,
                    message: errors.message,
                    stack: errors.stack
                };
            }

            process.send({
                cmd: errors ? TYPE.WORKER_ERROR : TYPE.WORKER_SUCCESS,
                data: errors ? errors : message
            }, () => {
                process.exit(0);
            });
        };

        try {
            // 加载 Node 模块
            let worker = require(data.target);
            worker(...data.params, onmessage);
        } catch (errors) {
            // 向父进程报告错误堆栈
            process.send({
                cmd: TYPE.WORKER_ERROR,
                data: {
                    type: errors.constructor.name,
                    message: errors.message,
                    stack: errors.stack
                }
            }, () => {
                process.exit(1);
            });
        }
    } else if (cmd === TYPE.WORKER_EXIT) {
        process.exit(0);
    }
});

<|endoftext|>


<commit_before>(function(angular, $, RepeaterUtilities) {

    'use strict';

    var module = angular.module('table.empty-table', []);
    module.directive('tableEmptyMessage', function($timeout, $log) {

        return {
            link: function(scope, el, attrs) {
                var msg = (attrs.tableEmptyMessage !== '') ? attrs.tableEmptyMessage : 'No items.';
                var tr = $('

' + msg + '

');
                var emptyToggleFn = function(val) {
                    if (!val || val.length === 0) {
                        tr.show();
                    } else {
                        tr.hide();
                    }
                };
                $timeout(function() {
                    var modelData = RepeaterUtilities.extractCollection(el);
                    if( modelData === undefined ) {
                        $log.warn("no model data found.");
                    }
                    var tbody = el.find("tbody");
                    var rowCount = tbody.find("tr").length;
                    tr.hide();
                    tbody.append(tr);
                    if( rowCount === 0 ) {
                        tr.show();
                    }
                    if( modelData ) {
                        scope.$watchCollection(modelData, emptyToggleFn);
                    }
                },0, false);
            }
        };
    });
})(angular, jQuery, RepeaterUtilities);<commit_msg>Fix empty table not showing up<commit_after>(function(angular, $, RepeaterUtilities) {

    'use strict';

    var module = angular.module('table.empty-table', []);
    module.directive('tableEmptyMessage', function($timeout, $log) {

        return {
            link: function(scope, el, attrs) {
                var msg = (attrs.tableEmptyMessage !== '') ? attrs.tableEmptyMessage : 'No items.';
                var tr = $('

' + msg + '

');
                var emptyToggleFn = function(val) {
                    if (!val || val.length === 0) {
                        tr.show();
                    } else {
                        tr.hide();
                    }
                };
                $timeout(function() {
                    var modelData = RepeaterUtilities.extractCollection(el);
                    if( modelData === undefined ) {
                        $log.warn("no model data found.");
                    }
                    var tbody = el.find("tbody");
                    var rowCount = tbody.find("tr").length;
                    tbody.append(tr);
                    if( rowCount > 0) {
                        tr.hide();
                    }
                    if( modelData ) {
                        scope.$watchCollection(modelData, emptyToggleFn);
                    }
                },0, false);
            }
        };
    });
})(angular, jQuery, RepeaterUtilities);<|endoftext|>


<commit_before>/** * Imports ***/
import ParsersVolume from './parsers.volume';
import {Vector3} from 'three';

/**
 * @module parsers/mhd
 */
export default class ParsersMHD extends ParsersVolume {
  constructor(data, id) {
    super();

    /**
      * @member
      * @type {arraybuffer}
    */
    this._id = id;
    this._url = data.url;
    this._header = {};
    this._buffer = null;

    try {
      // parse header (mhd) data
      let lines = new TextDecoder().decode(data.mhdBuffer).split('\n');
      lines.forEach((line) => {
          let keyvalue = line.split('=');
          if (keyvalue.length === 2) {
            this._header[keyvalue[0].trim()] = keyvalue[1].trim();
          }
      });

      this._header.DimSize = this._header.DimSize.split(' ');
      this._header.ElementSpacing = this._header.ElementSpacing.split(' ');
      this._header.TransformMatrix = this._header.TransformMatrix.split(' ');
      this._header.Offset = this._header.Offset.split(' ');
      //
      this._buffer = data.rawBuffer;
    } catch (error) {
      window.console.log('ooops... :(');
    }
  }

  rightHanded() {
    let anatomicalOrientation = this._header.AnatomicalOrientation;
    if (anatomicalOrientation === 'RAS' ||
        anatomicalOrientation === 'RPI' ||
        anatomicalOrientation === 'LPS' ||
        anatomicalOrientation === 'LAI') {
      this._rightHanded = true;
    } else {
      this._rightHanded = false;
    }

    return this._rightHanded;
  }

  seriesInstanceUID() {
    // use filename + timestamp..?
    return this._url;
  }

  numberOfFrames() {
    return parseInt(this._header.DimSize[2], 10);
  }

  sopInstanceUID(frameIndex = 0) {
    return frameIndex;
  }

  rows(frameIndex = 0) {
    return parseInt(this._header.DimSize[1], 10);
  }

  columns(frameIndex = 0) {
    return parseInt(this._header.DimSize[0], 10);
  }

  pixelType(frameIndex = 0) {
    // 0 - int
    // 1 - float
    return 0;
  }

  bitsAllocated(frameIndex = 0) {
    let bitsAllocated = 1;

    if (this._header.ElementType === 'MET_UCHAR' ||
        this._header.ElementType === 'MET_CHAR') {
      bitsAllocated = 8;
    } else if (
        this._header.ElementType === 'MET_USHORT' ||
        this._header.ElementType === 'MET_SHORT') {
      bitsAllocated = 16;
    } else if (
        this._header.ElementType === 'MET_UINT' ||
        this._header.ElementType === 'MET_INT' ||
        this._header.ElementType === 'MET_UFLOAT' ||
        this._header.ElementType === 'MET_FLOAT') {
      bitsAllocated = 32;
    }

    return bitsAllocated;
  }

  /**
   * https://itk.org/Wiki/ITK/MetaIO/Documentation
   * ElementSpacing[0] spacing between elements along X axis (i.e. column spacing)
   * ElementSpacing[1] spacing between elements along Y axis (i.e. row spacing)
   *
   * @param {*} frameIndex
   */
  pixelSpacing(frameIndex = 0) {
    let x = parseFloat(this._header.ElementSpacing[1], 10);
    let y = parseFloat(this._header.ElementSpacing[0], 10);
    let z = parseFloat(this._header.ElementSpacing[2], 10);
    return [x, y, z];
  }

  imageOrientation(frameIndex = 0) {
    let invertX = this._header.AnatomicalOrientation.match(/L/) ? -1 : 1;
    let invertY = this._header.AnatomicalOrientation.match(/P/) ? -1 : 1;

    let x = new Vector3(
      parseFloat(this._header.TransformMatrix[0]) * invertX,
      parseFloat(this._header.TransformMatrix[1]) * invertY,
      parseFloat(this._header.TransformMatrix[2]));
    x.normalize();

    let y = new Vector3(
      parseFloat(this._header.TransformMatrix[3]) * invertX,
      parseFloat(this._header.TransformMatrix[4]) * invertY,
      parseFloat(this._header.TransformMatrix[5]));
    y.normalize();

    return [
      x.x, x.y, x.z,
      y.x, y.y, y.z,
      ];
  }

  imagePosition(frameIndex = 0) {
    return [
      parseFloat(this._header.Offset[0]),
      parseFloat(this._header.Offset[1]),
      parseFloat(this._header.Offset[2]),
    ];
  }

  extractPixelData(frameIndex = 0) {
    return this._decompressUncompressed(frameIndex);
  }

  _decompressUncompressed(frameIndex = 0) {
    let buffer = this._buffer;
    let numberOfChannels = this.numberOfChannels();
    let numPixels =
      this.rows(frameIndex) * this.columns(frameIndex) * numberOfChannels;
    if (!this.rightHanded()) {
      frameIndex = this.numberOfFrames() - 1 - frameIndex;
    }
    let frameOffset = frameIndex * numPixels;

    if (this._header.ElementType === 'MET_CHAR') {
      return new Int8Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_UCHAR') {
      return new Uint8Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_SHORT') {
      frameOffset = frameOffset * 2;
      return new Int16Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_USHORT') {
      frameOffset = frameOffset * 2;
      return new Uint16Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_INT') {
      frameOffset = frameOffset * 4;
      return new Int32Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_UINT') {
      frameOffset = frameOffset * 4;
      return new Uint32Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_FLOAT') {
      frameOffset = frameOffset * 4;
      return new Float32Array(buffer, frameOffset, numPixels);
    }
  }
}
<commit_msg>Mhd pixetype (#298)<commit_after>/** * Imports ***/
import ParsersVolume from './parsers.volume';
import {Vector3} from 'three';

/**
 * @module parsers/mhd
 */
export default class ParsersMHD extends ParsersVolume {
  constructor(data, id) {
    super();

    /**
      * @member
      * @type {arraybuffer}
    */
    this._id = id;
    this._url = data.url;
    this._header = {};
    this._buffer = null;

    try {
      // parse header (mhd) data
      let lines = new TextDecoder().decode(data.mhdBuffer).split('\n');
      lines.forEach((line) => {
          let keyvalue = line.split('=');
          if (keyvalue.length === 2) {
            this._header[keyvalue[0].trim()] = keyvalue[1].trim();
          }
      });

      this._header.DimSize = this._header.DimSize.split(' ');
      this._header.ElementSpacing = this._header.ElementSpacing.split(' ');
      this._header.TransformMatrix = this._header.TransformMatrix.split(' ');
      this._header.Offset = this._header.Offset.split(' ');
      //
      this._buffer = data.rawBuffer;
    } catch (error) {
      window.console.log('ooops... :(');
    }
  }

  rightHanded() {
    let anatomicalOrientation = this._header.AnatomicalOrientation;
    if (anatomicalOrientation === 'RAS' ||
        anatomicalOrientation === 'RPI' ||
        anatomicalOrientation === 'LPS' ||
        anatomicalOrientation === 'LAI') {
      this._rightHanded = true;
    } else {
      this._rightHanded = false;
    }

    return this._rightHanded;
  }

  seriesInstanceUID() {
    // use filename + timestamp..?
    return this._url;
  }

  numberOfFrames() {
    return parseInt(this._header.DimSize[2], 10);
  }

  sopInstanceUID(frameIndex = 0) {
    return frameIndex;
  }

  rows(frameIndex = 0) {
    return parseInt(this._header.DimSize[1], 10);
  }

  columns(frameIndex = 0) {
    return parseInt(this._header.DimSize[0], 10);
  }

  pixelType(frameIndex = 0) {
    // 0 - int
    // 1 - float
    let type = 0;
    if (this._header.ElementType === 'MET_UFLOAT' ||
        this._header.ElementType === 'MET_FLOAT') {
      type = 1;
    }
    return type;
  }

  bitsAllocated(frameIndex = 0) {
    let bitsAllocated = 1;

    if (this._header.ElementType === 'MET_UCHAR' ||
        this._header.ElementType === 'MET_CHAR') {
      bitsAllocated = 8;
    } else if (
        this._header.ElementType === 'MET_USHORT' ||
        this._header.ElementType === 'MET_SHORT') {
      bitsAllocated = 16;
    } else if (
        this._header.ElementType === 'MET_UINT' ||
        this._header.ElementType === 'MET_INT' ||
        this._header.ElementType === 'MET_UFLOAT' ||
        this._header.ElementType === 'MET_FLOAT') {
      bitsAllocated = 32;
    }

    return bitsAllocated;
  }

  /**
   * https://itk.org/Wiki/ITK/MetaIO/Documentation
   * ElementSpacing[0] spacing between elements along X axis (i.e. column spacing)
   * ElementSpacing[1] spacing between elements along Y axis (i.e. row spacing)
   *
   * @param {*} frameIndex
   */
  pixelSpacing(frameIndex = 0) {
    let x = parseFloat(this._header.ElementSpacing[1], 10);
    let y = parseFloat(this._header.ElementSpacing[0], 10);
    let z = parseFloat(this._header.ElementSpacing[2], 10);
    return [x, y, z];
  }

  imageOrientation(frameIndex = 0) {
    let invertX = this._header.AnatomicalOrientation.match(/L/) ? -1 : 1;
    let invertY = this._header.AnatomicalOrientation.match(/P/) ? -1 : 1;

    let x = new Vector3(
      parseFloat(this._header.TransformMatrix[0]) * invertX,
      parseFloat(this._header.TransformMatrix[1]) * invertY,
      parseFloat(this._header.TransformMatrix[2]));
    x.normalize();

    let y = new Vector3(
      parseFloat(this._header.TransformMatrix[3]) * invertX,
      parseFloat(this._header.TransformMatrix[4]) * invertY,
      parseFloat(this._header.TransformMatrix[5]));
    y.normalize();

    return [
      x.x, x.y, x.z,
      y.x, y.y, y.z,
      ];
  }

  imagePosition(frameIndex = 0) {
    return [
      parseFloat(this._header.Offset[0]),
      parseFloat(this._header.Offset[1]),
      parseFloat(this._header.Offset[2]),
    ];
  }

  extractPixelData(frameIndex = 0) {
    return this._decompressUncompressed(frameIndex);
  }

  _decompressUncompressed(frameIndex = 0) {
    let buffer = this._buffer;
    let numberOfChannels = this.numberOfChannels();
    let numPixels =
      this.rows(frameIndex) * this.columns(frameIndex) * numberOfChannels;
    if (!this.rightHanded()) {
      frameIndex = this.numberOfFrames() - 1 - frameIndex;
    }
    let frameOffset = frameIndex * numPixels;

    if (this._header.ElementType === 'MET_CHAR') {
      return new Int8Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_UCHAR') {
      return new Uint8Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_SHORT') {
      frameOffset = frameOffset * 2;
      return new Int16Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_USHORT') {
      frameOffset = frameOffset * 2;
      return new Uint16Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_INT') {
      frameOffset = frameOffset * 4;
      return new Int32Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_UINT') {
      frameOffset = frameOffset * 4;
      return new Uint32Array(buffer, frameOffset, numPixels);
    } else if (this._header.ElementType === 'MET_FLOAT') {
      frameOffset = frameOffset * 4;
      return new Float32Array(buffer, frameOffset, numPixels);
    }
  }
}
<|endoftext|>


<commit_before>define( [ "codemirror", "codemirror/addon/mode/simple" ], function( CodeMirror ) {

  CodeMirror.defineSimpleMode( "commander", {
    start: [
      // Escaped characters
      { regex: /`.?/, token: "hr" },

      // Commander specific
      { regex: /(?:chain|include)\b/, token: "header", sol: true },
      { regex: /(\s*)(default|def|invert|marker|var|void)\b/, token: [ "quote", "header" ], sol: true },
      { regex: /(\s+)([01irc\?!]+)(:)/, token: [ null, "quote", "operator" ], sol: true },

      // Commander specific
      { regex: /\$\w+/, token: "variable" },
      { regex: /\^\w+/, token: "variable-2" },
      { regex: /\=\>.*/, token: "tag"},
      { regex: /\/\/.*/, token: "comment" },
      { regex: /\/\*/, token: "comment", next: "comment" },

      // Minecraft Specific
      { regex: /@[aepr]\b/, token: "string" },
      { regex: /(?:area_effect_cloud|armor_stand|arrow|bat|blaze|boat|cave_spider|chest_minecart|chicken|commandblock_minecart|cow|creeper|donkey|dragon_fireball|egg|elder_guardian|ender_crystal|ender_dragon|ender_pearl|enderman|endermite|evocation_fangs|evocation_illager|eye_of_ender_signal|falling_block|fireball|fireworks_rocket|furnace_minecart|ghast|giant|guardian|hopper_minecart|horse|husk|illusion_illager|item|item_frame|leash_knot|lightning_bolt|llama|llama_spit|magma_cube|minecart|mooshroom|mule|ocelot|painting|parrot|pig|polar_bear|potion|rabbit|sheep|shulker|shulker_bullet|silverfish|skeleton|skeleton_horse|slime|small_fireball|snowball|snowman|spawner_minecart|spectral_arrow|spider|squid|stray|tnt|tnt_minecart|vex|villager|villager_golem|vindication_illager|witch|wither|wither_skeleton|wither_skull|wolf|xp_bottle|xp_orb|zombie|zombie_horse|zombie_pigman|zombie_villager)\b/,
        token: "property" },
      { regex: /\/?(?:achievement|advancement|ban|ban-ip|banlist|blockdata|clear|clone|debug|defaultgamemode|deop|difficulty|effect|enchant|entitydata|execute|fill|function|gamemode|gamerule|give|help|kick|kill|list|locate|me|msg|op|pardon|pardon-ip|particle|playsound|recipe|replaceitem|save-all|save-off|save-on|say|scoreboard|seed|setblock|setidletimeout|setworldspawn|spawnpoint|spreadplayers|stats|stop|stopsound|summon|teleport|tell|tellraw|testfor|testforblock|testforblocks|time|title|toggledownfall|tp|trigger|w|weather|whitelist|worldborder|xp)\b/i,
        token: "keyword" },

      // Numbers
      { regex: /(?:~?-?(?:\.\d+|\d+\.?\d*)[bfs]?|~)/, token: "number" },

      // Ponctuation
      { regex: /[\[\]{}\(\)]/, token: "bracket" },
      { regex: /[\+-/*=%;:]/, token: "operator" },
      // { regex: /:$/, token: "operator", indent: true },

      // Pass
      { regex: /(?:\w+)/ }
    ],
    comment: [
    { regex: /.*?\*\//, token: "comment", next: "start" },
    { regex: /.*/, token: "comment" }
    ],
    meta: {
      dontIndentStates: [ "comment" ],
      lineComment: "//"
    }
  } );

} );
<commit_msg>Update commander-mode.js<commit_after>define( [ "codemirror", "codemirror/addon/mode/simple" ], function( CodeMirror ) {

  CodeMirror.defineSimpleMode( "commander", {
    start: [
      // Escaped characters
      { regex: /`.?/, token: "hr" },

      // Commander specific
      { regex: /(?:chain|include)\b/, token: "header", sol: true },
      { regex: /(\s*)(default|def|invert|marker|var|void)\b/, token: [ "quote", "header" ], sol: true },
      { regex: /(\s+)([01irc\?!]+)(:)/, token: [ null, "quote", "operator" ], sol: true },

      // Commander specific
      { regex: /\$\w+/, token: "variable" },
      { regex: /\^\w+/, token: "variable-2" },
      { regex: /\=\>.*/, token: "tag"},
      { regex: /\/\/.*/, token: "comment" },
      { regex: /\/\*/, token: "comment", next: "comment" },

      // Minecraft Specific
      { regex: /@[aepr]\b/, token: "string" },
      { regex: /(?:area_effect_cloud|armor_stand|arrow|bat|blaze|boat|cave_spider|chest_minecart|chicken|commandblock_minecart|cow|creeper|donkey|dragon_fireball|egg|elder_guardian|ender_crystal|ender_dragon|ender_pearl|enderman|endermite|evocation_fangs|evocation_illager|eye_of_ender_signal|falling_block|fireball|fireworks_rocket|furnace_minecart|ghast|giant|guardian|hopper_minecart|horse|husk|illusion_illager|item|item_frame|leash_knot|lightning_bolt|llama|llama_spit|magma_cube|minecart|mooshroom|mule|ocelot|painting|parrot|pig|polar_bear|potion|rabbit|sheep|shulker|shulker_bullet|silverfish|skeleton|skeleton_horse|slime|small_fireball|snowball|snowman|spawner_minecart|spectral_arrow|spider|squid|stray|tnt|tnt_minecart|vex|villager|villager_golem|vindication_illager|witch|wither|wither_skeleton|wither_skull|wolf|xp_bottle|xp_orb|zombie|zombie_horse|zombie_pigman|zombie_villager)\b/,
        token: "property" },
      { regex: /\/?(?:achievement|advancement|ban|ban-ip|banlist|blockdata|clear|clone|debug|defaultgamemode|deop|difficulty|effect|enchant|entitydata|execute|fill|function|gamemode|gamerule|give|help|kick|kill|list|locate|me|msg|op|pardon|pardon-ip|particle|playsound|recipe|reload|replaceitem|save-all|save-off|save-on|say|scoreboard|seed|setblock|setidletimeout|setworldspawn|spawnpoint|spreadplayers|stats|stop|stopsound|summon|teleport|tell|tellraw|testfor|testforblock|testforblocks|time|title|toggledownfall|tp|trigger|w|weather|whitelist|worldborder|xp)\b/i,
        token: "keyword" },

      // Numbers
      { regex: /(?:~?-?(?:\.\d+|\d+\.?\d*)[bfs]?|~)/, token: "number" },

      // Ponctuation
      { regex: /[\[\]{}\(\)]/, token: "bracket" },
      { regex: /[\+-/*=%;:]/, token: "operator" },
      // { regex: /:$/, token: "operator", indent: true },

      // Pass
      { regex: /(?:\w+)/ }
    ],
    comment: [
    { regex: /.*?\*\//, token: "comment", next: "start" },
    { regex: /.*/, token: "comment" }
    ],
    meta: {
      dontIndentStates: [ "comment" ],
      lineComment: "//"
    }
  } );

} );
<|endoftext|>


<commit_before>(function (Shreds) {
  var name = 'subscription';

  var $subscribeInput = $('#subscribeInput');
  var $subscribeForm = $('#subscribe_form');
  var $feedUrl = $('#feed_url');
  var $categoryName = $('#category_name');
  var spinner = null;

  Shreds.components.push(name);
  Shreds[name] = {
    activate: function () {
      if ($subscribeInput.is(':hidden')) {
        $subscribeInput.slideDown();
        $feedUrl.focus();
      } else {
        spinner = Ladda.create(this);
        spinner.start();
        $.ajax('/i/feeds.json', {
          method: 'POST',
          data: $subscribeForm.find('form').serialize()
        }).done(function (data) {
          if (data && data.watch) {
            Shreds.watch.add(data.watch);
          }
        }).fail(function () {
          spinner.stop();
          Shreds.notification.error('Can not add feed at the moment.');
        });
        $feedUrl.val('');
        $categoryName.val('');
        $subscribeInput.slideUp();
      }
    },
    stopSpinner: function () {
      try {
        spinner.stop();
      } catch (e) { }
    },
    init: function () {
      setupDOMEvents();
    }
  };

  function setupDOMEvents() {
    var $doc = $(document);
    var amOut = true;

    $doc.on('mousedown', function (e) {
      if (!$subscribeInput.is(':hidden') && amOut) {
        $subscribeInput.slideUp();
      }
    });
    $doc.on('mouseover', function (e) {
      if ($subscribeForm.has(e.target).length === 0) {
        amOut = true;
        return;
      }
      amOut = false;
    });
  }
})(window.Shreds);

<commit_msg>Use Shreds.ajax for subscription.<commit_after>(function (Shreds) {
  var name = 'subscription';

  var $subscribeInput = $('#subscribeInput');
  var $subscribeForm = $('#subscribe_form');
  var $feedUrl = $('#feed_url');
  var $categoryName = $('#category_name');
  var spinner = null;

  Shreds.components.push(name);
  Shreds[name] = {
    activate: function () {
      if ($subscribeInput.is(':hidden')) {
        $subscribeInput.slideDown();
        $feedUrl.focus();
      } else {
        spinner = Ladda.create(this);
        spinner.start();
        Shreds.ajax.post('/i/feeds.json', {
          doWatch: true,
          opts: { data: $subscribeForm.find('form').serialize() },
          failMsg: 'Can not add feed at the moment.'
        }).fail(function () { spinner.stop(); });
        $feedUrl.val('');
        $categoryName.val('');
        $subscribeInput.slideUp();
      }
    },
    stopSpinner: function () {
      try {
        spinner.stop();
      } catch (e) { }
    },
    init: function () {
      setupDOMEvents();
    }
  };

  function setupDOMEvents() {
    var $doc = $(document);
    var amOut = true;

    $doc.on('mousedown', function (e) {
      if (!$subscribeInput.is(':hidden') && amOut) {
        $subscribeInput.slideUp();
      }
    });
    $doc.on('mouseover', function (e) {
      if ($subscribeForm.has(e.target).length === 0) {
        return amOut = true;
      }
      amOut = false;
    });
  }
})(window.Shreds);

<|endoftext|>


<commit_before>/*
FIXME: real documentation
<form sf-form="form"  sf-schema="schema" sf-decorator="foobar"></form>
*/

angular.module('schemaForm')
       .directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect',
  function($compile,  schemaForm,  schemaFormDecorators, sfSelect) {

    var SNAKE_CASE_REGEXP = /[A-Z]/g;
    var snakeCase = function(name, separator) {
      separator = separator || '_';
      return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
        return (pos ? separator : '') + letter.toLowerCase();
      });
    };

    return {
      scope: {
        schema: '=sfSchema',
        initialForm: '=sfForm',
        model: '=sfModel'
      },
      controller: ['$scope', function($scope) {
        this.evalInParentScope = function(expr, locals) {
          return $scope.$parent.$eval(expr, locals);
        };
      }],
      replace: false,
      restrict: 'A',
      transclude: true,
      require: '?form',
      link: function(scope, element, attrs, formCtrl, transclude) {

        //expose form controller on scope so that we don't force authors to use name on form
        scope.formCtrl = formCtrl;

        //We'd like to handle existing markup,
        //besides using it in our template we also
        //check for ng-model and add that to an ignore list
        //i.e. even if form has a definition for it or form is ["*"]
        //we don't generate it.
        var ignore = {};
        transclude(scope, function(clone) {
          clone.addClass('schema-form-ignore');
          element.prepend(clone);

          if (element[0].querySelectorAll) {
            var models = element[0].querySelectorAll('[ng-model]');
            if (models) {
              for (var i = 0; i < models.length; i++) {
                var key = models[i].getAttribute('ng-model');
                //skip first part before .
                ignore[key.substring(key.indexOf('.') + 1)] = true;
              }
            }
          }
        });
        //Since we are dependant on up to three
        //attributes we'll do a common watch
        var lastDigest = {};

        scope.$watch(function() {

          var schema = scope.schema;
          var form   = scope.initialForm || ['*'];

          //The check for schema.type is to ensure that schema is not {}
          if (form && schema && schema.type &&
              (lastDigest.form !== form || lastDigest.schema !== schema) &&
              Object.keys(schema.properties).length > 0) {
            lastDigest.schema = schema;
            lastDigest.form = form;

            // Check for options
            var options = scope.$eval(attrs.sfOptions);

            var merged = schemaForm.merge(schema, form, ignore, options);
            var frag = document.createDocumentFragment();

            //make the form available to decorators
            scope.schemaForm  = {form:  merged, schema: schema};

            //Create directives from the form definition
            angular.forEach(merged, function(obj, i) {
              var n = document.createElement(attrs.sfDecoratorName ||
                      snakeCase(schemaFormDecorators.defaultDecorator, '-'));
              n.setAttribute('form', 'schemaForm.form[' + i + ']');
              frag.appendChild(n);
            });

            //clean all but pre existing html.
            element.children(':not(.schema-form-ignore)').remove();

            element[0].appendChild(frag);

            //compile only children
            $compile(element.children())(scope);

            //ok, now that that is done let's set any defaults
            schemaForm.traverseSchema(schema, function(prop, path) {
              if (angular.isDefined(prop['default'])) {
                var val = sfSelect(path, scope.model);
                if (angular.isUndefined(val)) {
                  sfSelect(path, scope.model, prop['default']);
                }
              }
            });
          }
        });
      }
    };
  }
]);
<commit_msg>Evaluate sfModel in the parent scope<commit_after>/*
FIXME: real documentation
<form sf-form="form"  sf-schema="schema" sf-decorator="foobar"></form>
*/

angular.module('schemaForm')
       .directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect',
  function($compile,  schemaForm,  schemaFormDecorators, sfSelect) {

    var SNAKE_CASE_REGEXP = /[A-Z]/g;
    var snakeCase = function(name, separator) {
      separator = separator || '_';
      return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
        return (pos ? separator : '') + letter.toLowerCase();
      });
    };

    return {
      scope: {
        schema: '=sfSchema',
        initialForm: '=sfForm',
        model: '=sfModel',
        options: '=sfOptions'
      },
      controller: ['$scope', function($scope) {
        this.evalInParentScope = function(expr, locals) {
          return $scope.$parent.$eval(expr, locals);
        };
      }],
      replace: false,
      restrict: 'A',
      transclude: true,
      require: '?form',
      link: function(scope, element, attrs, formCtrl, transclude) {

        //expose form controller on scope so that we don't force authors to use name on form
        scope.formCtrl = formCtrl;

        //We'd like to handle existing markup,
        //besides using it in our template we also
        //check for ng-model and add that to an ignore list
        //i.e. even if form has a definition for it or form is ["*"]
        //we don't generate it.
        var ignore = {};
        transclude(scope, function(clone) {
          clone.addClass('schema-form-ignore');
          element.prepend(clone);

          if (element[0].querySelectorAll) {
            var models = element[0].querySelectorAll('[ng-model]');
            if (models) {
              for (var i = 0; i < models.length; i++) {
                var key = models[i].getAttribute('ng-model');
                //skip first part before .
                ignore[key.substring(key.indexOf('.') + 1)] = true;
              }
            }
          }
        });
        //Since we are dependant on up to three
        //attributes we'll do a common watch
        var lastDigest = {};

        scope.$watch(function() {

          var schema = scope.schema;
          var form   = scope.initialForm || ['*'];

          //The check for schema.type is to ensure that schema is not {}
          if (form && schema && schema.type &&
              (lastDigest.form !== form || lastDigest.schema !== schema) &&
              Object.keys(schema.properties).length > 0) {
            lastDigest.schema = schema;
            lastDigest.form = form;

            var merged = schemaForm.merge(schema, form, ignore, scope.options);
            var frag = document.createDocumentFragment();

            //make the form available to decorators
            scope.schemaForm  = {form:  merged, schema: schema};

            //Create directives from the form definition
            angular.forEach(merged, function(obj, i) {
              var n = document.createElement(attrs.sfDecoratorName ||
                      snakeCase(schemaFormDecorators.defaultDecorator, '-'));
              n.setAttribute('form', 'schemaForm.form[' + i + ']');
              frag.appendChild(n);
            });

            //clean all but pre existing html.
            element.children(':not(.schema-form-ignore)').remove();

            element[0].appendChild(frag);

            //compile only children
            $compile(element.children())(scope);

            //ok, now that that is done let's set any defaults
            schemaForm.traverseSchema(schema, function(prop, path) {
              if (angular.isDefined(prop['default'])) {
                var val = sfSelect(path, scope.model);
                if (angular.isUndefined(val)) {
                  sfSelect(path, scope.model, prop['default']);
                }
              }
            });
          }
        });
      }
    };
  }
]);
<|endoftext|>


<commit_before>var NODES_PER_LAYER = 6;

var Renderer = {};

Renderer.init = function(canvasId, resourceId, navigationListener){
    Renderer.engine.initParticleSystem();
    Renderer.canvas.init(canvasId);

    Renderer.engine.centerOn(resourceId, function(centralNodeData, childrenNodesData) {
        Renderer.engine.jsonOriginData = centralNodeData;
        Renderer.engine.jsonChildrenData = childrenNodesData;

        Renderer.layers.count = Math.ceil(Renderer.engine.jsonChildrenData.length / NODES_PER_LAYER);

        Renderer.canvas.resize();

        Renderer.engine.particleSystem.renderer = Renderer.loop;
        Renderer.nodes.central = new Renderer.Node(Renderer.engine.jsonOriginData);
        Renderer.layers.init();
        Renderer.layers.display(0);
        Renderer.navigation.navigationListener = navigationListener;
    });
};

Renderer.navigation = {};

Renderer.http = {
    getData: function(resourceId, callback) {
        $.get('/knownodes/:' + resourceId, function(centralNode) {
            $.get('/concepts/:' + resourceId + '/getRelatedKnownodes', function(relatedNodes) {
                callback(centralNode.success, relatedNodes.success);
            });
        });
    }
};

Renderer.engine = {};
Renderer.engine.centerOn = function(resourceId, callback) {
    Renderer.http.getData(resourceId, function(centralNodeData, childrenNodesData) {
        if(callback) callback(centralNodeData, childrenNodesData);
    });
}
Renderer.engine.particleSystem = null;
Renderer.engine.jsonOriginData = null;
Renderer.engine.jsonChildrenData = null;
Renderer.engine.isReady = function(){
    return Renderer.engine.particleSystem !== null && Renderer.canvas.stage !== null;
};

Renderer.engine.initParticleSystem = function(){
    this.particleSystem = arbor.ParticleSystem(1000, 600, 0.5);// create the system with sensible repulsion/stiffness/friction
    this.particleSystem.parameters({gravity:true}); // use center-gravity to make the graph settle nicely (ymmv)
    this.particleSystem.fps(40);

    this.particleSystem.originalPruneEdge = this.particleSystem.pruneEdge;
    this.particleSystem.pruneEdge = function(e){e.data.edge.delete();};
    this.particleSystem.originalPruneNode = this.particleSystem.pruneNode;
    this.particleSystem.pruneNode = function(e){e.data.node.delete();};
};

Renderer.canvas = {};
Renderer.canvas.stage = null;
Renderer.canvas.init = function(canvasId){
    this.stage = new Kinetic.Stage({
        container: canvasId,
        width: 800,
        height: 600,
        fill: "black"
    });
    this.stage.add(Renderer.edges.layer);
    this.stage.add(Renderer.nodes.layer);
    this.stage.add(Renderer.layers.layer);
};
Renderer.canvas.resize = function(){
    var div = $(".ui-layout-center");
    Renderer.engine.particleSystem.screenSize(div.width(), div.height());
    Renderer.engine.particleSystem.screenPadding(80,200,80,80);
    this.stage.setSize(div.width(), div.height());
    Renderer.loop.redraw();
};

Renderer.Layer = function(id){
    this.id = id;
    this.shape = new Kinetic.Rect({
        width: this.width,
        height: this.height,
        x: 0,
        y: id * (this.height + 3) + 20,
        fill: "white"
    });
    this.checkAndSetColor();
    this.shape.layer = this;
    Renderer.layers.layer.add(this.shape);
    this.bindEvents();
    Renderer.layers.list.push(this);
};
Renderer.Layer.prototype = {
    width: 50,
    height: 20,
    delete: function(){
        this.shape.destroy();
        delete this;
    },
    bindEvents: function(){
        this.shape.on('click', this.mouseClick);
        this.shape.on('mouseover', this.mouseOver);
        this.shape.on('mouseout', this.mouseOut);
    },
    mouseOver: function(e){
        new Kinetic.Tween({
            node: this,
            easing: Kinetic.Easings['StrongEaseOut'],
            duration: 0.5,
            scaleX: 1.3
        }).play();
    },
    mouseOut: function(e){
        new Kinetic.Tween({
            node: this,
            easing: Kinetic.Easings['StrongEaseOut'],
            duration: 1,
            scaleX: 1
        }).play();
    },
    mouseClick: function(e){
        Renderer.layers.display(this.layer.id);
    },
    checkAndSetColor: function(){
        var intensity = 255;
        if(this.id === Renderer.layers.current)
            intensity = 150;

        this.shape.setAttrs({
            fillR: intensity,
            fillG: intensity,
            fillB: intensity
        });
    }
};
Renderer.layers = {};
Renderer.layers.list = [];
Renderer.layers.current = -1;
Renderer.layers.layer = new Kinetic.Layer({});
Renderer.layers.init = function(){
    for(var layer in this.list){
        this.list[layer].delete();
    }
    this.list = [];
    for(var i = 0; i < this.count; i++) {
        new Renderer.Layer(i);
    }
};
Renderer.layers.display = function(layer){
    if(layer !== this.current){
        this.current = layer;
        for (var layerId in this.list) {
            this.list[layerId].checkAndSetColor();
        }

        var edges = Renderer.engine.particleSystem.getEdgesFrom(Renderer.nodes.central.node);
        for(var edge in edges)
            Renderer.engine.particleSystem.pruneNode(edges[edge].target);

        for(var i = this.current * NODES_PER_LAYER; i < (this.current + 1) * NODES_PER_LAYER && i < Renderer.engine.jsonChildrenData.length; i++){
            var node = new Renderer.Node(Renderer.engine.jsonChildrenData[i].article);
            new Renderer.Edge(Renderer.nodes.central, node, Renderer.engine.jsonChildrenData[i].connection);
        }
    }
};

Renderer.Node = function(data){
    this.data = data;
    this.displayGroup = new  Kinetic.Group({x:-200, y:-200});
    this.displayPolygon = this.newPolygon();
    this.displayText = this.newText();
    this.node =  Renderer.engine.particleSystem.addNode(this.data.id, {node: this});
    this.displayPolygon.node = this;
    Renderer.nodes.layer.add(this.displayGroup);
    this.tweenPolygonHover = new Kinetic.Tween({
        node: this.displayPolygon,
        duration: 1,
        easing: Kinetic.Easings['StrongEaseOut'],
        fillB: 200,
        scaleX: 2,
        scaleY: 2,
        strokeWidth: 5
    });
    this.tweenTextHover = new Kinetic.Tween({
        node: this.displayText,
        duration: 1,
        easing: Kinetic.Easings['StrongEaseOut'],
        fontSize: 18,
        x: 80,
        y: -20,
        width: 300
    });
    this.bindEvents();
};
Renderer.Node.prototype = {
    shape: [[26,15],[0,30],[-26,15],[-26,-15],[0,-30],[26,-15]],
    delete: function(){
        this.displayGroup.destroy();
        Renderer.engine.particleSystem.originalPruneNode(this.node);
        delete this;
    },
    newPolygon: function(){
        var polygon = new Kinetic.Polygon({
            points: this.shape,
            fill: "black",
            stroke: "white",
            strokeWidth: 3
        });
        polygon.node = this;
        this.displayGroup.add(polygon);
        return polygon;
    },
    newText: function(){
        var text = new Kinetic.Text({
            text: this.data.title,
            fill: "white",
            width: 120
        });
        text.node = this;
        this.displayGroup.add(text);
        text.setPosition(31, -5);
        return text;
    },
    moveTo: function (pos){
        this.displayGroup.setPosition(pos.x, pos.y);
    },
    bindEvents: function(){
        this.displayPolygon.on('mouseover', this.mouseOver);
        this.displayPolygon.on('mouseout', this.mouseOut);
        this.displayPolygon.on('click', this.mouseClick);
        this.displayPolygon.on('dblclick dbltap', this.mouseDblClick);
    },
    mouseDblClick: function() {
        var id = this.node.data.KN_ID;
        Renderer.engine.centerOn(id, function(centralNodeData, childrenNodesData) {

            Renderer.engine.jsonOriginData = centralNodeData;
            Renderer.engine.jsonChildrenData = childrenNodesData;
            Renderer.navigation.navigationListener(id);

            var edges = Renderer.engine.particleSystem.getEdgesFrom(Renderer.nodes.central.node);
            var newCentral;
            for(var edge in edges) {
                var node = edges[edge].target;
                if(node.data.node.data.KN_ID !== id) {
                    Renderer.engine.particleSystem.pruneNode(node);
                } else {
                    newCentral = node.data.node;
                }
            }

            Renderer.nodes.central.delete();

            Renderer.nodes.central = newCentral;

            Renderer.layers.count = Math.ceil(Renderer.engine.jsonChildrenData.length / NODES_PER_LAYER);

            Renderer.layers.init();
            Renderer.layers.current = -1;
            Renderer.layers.display(0);
        });
    },
    mouseOver: function(){
       this.node.tweenPolygonHover.play();
       this.node.tweenTextHover.play();
    },
    mouseOut: function(){
        this.node.tweenPolygonHover.reverse();
        this.node.tweenTextHover.reverse();
    },
    mouseClick: function(){
        Renderer.nodes.selected = this.node;
        var data = this.node.data;
        $("#node-link").attr('href', data.url).text(data.title);
        $("#node-content").html(data.bodyText);
        PanelsHandler.layout.open("west");
    }
};

Renderer.nodes = {};
Renderer.nodes.selected = null;
Renderer.nodes.central = null;
Renderer.nodes.layer = new Kinetic.Layer({});

Renderer.Edge = function(from, to, data){
    this.from = from;
    this.to = to;
    this.data = data;
    this.edge = Renderer.engine.particleSystem.addEdge(from.node, to.node, {edge: this});
    this.line = this.newLine(data);

    this.bindEvents();
};
Renderer.Edge.prototype = {
    delete: function(){
        this.line.destroy();
        Renderer.engine.particleSystem.originalPruneEdge(this.edge);
        delete this;
    },
    newLine: function(connection){
        var stroke = "white";
        if (connection.connectionType === "explain") {
            stroke = "blue";
        } else if (connection.connectionType === "inspire") {
            stroke = "yellow";
        } else if (connection.connectionType === "question") {
            stroke = "green";
        } else if (connection.connectionType === "Wikipedia Link") {
            stroke = "gray";
        }

        var line =  new Kinetic.Line({
            points: [0,0,0,0],
            stroke: stroke,
            strokeWidth: 2
        });
        line.edge = this;
        Renderer.edges.layer.add(line);
        return line;
    },
    bindEvents: function(){
        this.line.on("mouseover", this.mouseOver);
        this.line.on("mouseout", this.mouseOut);
    },
    moveTo: function(pos1, pos2){

        function generatePoints(fromx, fromy, tox, toy){
            var hexagon = 30;
            var headlen = 60;
            var angle = Math.atan2(toy-fromy,tox-fromx);

            return [fromx, fromy,
                    tox-hexagon*Math.cos(angle),toy-hexagon*Math.sin(angle),
                    tox-headlen*Math.cos(angle-Math.PI/6),toy-headlen*Math.sin(angle-Math.PI/6),
                    tox-headlen*Math.cos(angle+Math.PI/6),toy-headlen*Math.sin(angle+Math.PI/6),
                    tox-hexagon*Math.cos(angle),toy-hexagon*Math.sin(angle)
                    ];
        }

        var points = generatePoints(pos1.x, pos1.y, pos2.x, pos2.y);

        this.line.setAttr('points',points);
    },
    mouseOver: function(){
        new Kinetic.Tween({
            node: this,
            duration: 1,
            easing: Kinetic.Easings['StrongEaseOut'],
            strokeWidth: 5
        }).play();
    },
    mouseOut: function(){
        new Kinetic.Tween({
            node: this,
            duration: 1,
            easing: Kinetic.Easings['StrongEaseOut'],
            strokeWidth: 2
        }).play();
    }
};
Renderer.edges = {};
Renderer.edges.layer = new Kinetic.Layer({});

Renderer.loop = {}
Renderer.loop.init = function(){};
Renderer.loop.redraw = function(){
    Renderer.engine.particleSystem.eachEdge(function(edge, pt1, pt2){
        edge.data.edge.moveTo(pt1, pt2);
    });
    Renderer.engine.particleSystem.eachNode(function(node, pt){
        node.data.node.moveTo(pt);
    });
    Renderer.canvas.stage.draw();
};
<commit_msg>fixed ugly colored arrows (still ugly)<commit_after>var NODES_PER_LAYER = 6;

var Renderer = {};

Renderer.init = function(canvasId, resourceId, navigationListener){
    Renderer.engine.initParticleSystem();
    Renderer.canvas.init(canvasId);

    Renderer.engine.centerOn(resourceId, function(centralNodeData, childrenNodesData) {
        Renderer.engine.jsonOriginData = centralNodeData;
        Renderer.engine.jsonChildrenData = childrenNodesData;

        Renderer.layers.count = Math.ceil(Renderer.engine.jsonChildrenData.length / NODES_PER_LAYER);

        Renderer.canvas.resize();

        Renderer.engine.particleSystem.renderer = Renderer.loop;
        Renderer.nodes.central = new Renderer.Node(Renderer.engine.jsonOriginData);
        Renderer.layers.init();
        Renderer.layers.display(0);
        Renderer.navigation.navigationListener = navigationListener;
    });
};

Renderer.navigation = {};

Renderer.http = {
    getData: function(resourceId, callback) {
        $.get('/knownodes/:' + resourceId, function(centralNode) {
            $.get('/concepts/:' + resourceId + '/getRelatedKnownodes', function(relatedNodes) {
                callback(centralNode.success, relatedNodes.success);
            });
        });
    }
};

Renderer.engine = {};
Renderer.engine.centerOn = function(resourceId, callback) {
    Renderer.http.getData(resourceId, function(centralNodeData, childrenNodesData) {
        if(callback) callback(centralNodeData, childrenNodesData);
    });
}
Renderer.engine.particleSystem = null;
Renderer.engine.jsonOriginData = null;
Renderer.engine.jsonChildrenData = null;
Renderer.engine.isReady = function(){
    return Renderer.engine.particleSystem !== null && Renderer.canvas.stage !== null;
};

Renderer.engine.initParticleSystem = function(){
    this.particleSystem = arbor.ParticleSystem(1000, 600, 0.5);// create the system with sensible repulsion/stiffness/friction
    this.particleSystem.parameters({gravity:true}); // use center-gravity to make the graph settle nicely (ymmv)
    this.particleSystem.fps(40);

    this.particleSystem.originalPruneEdge = this.particleSystem.pruneEdge;
    this.particleSystem.pruneEdge = function(e){e.data.edge.delete();};
    this.particleSystem.originalPruneNode = this.particleSystem.pruneNode;
    this.particleSystem.pruneNode = function(e){e.data.node.delete();};
};

Renderer.canvas = {};
Renderer.canvas.stage = null;
Renderer.canvas.init = function(canvasId){
    this.stage = new Kinetic.Stage({
        container: canvasId,
        width: 800,
        height: 600,
        fill: "black"
    });
    this.stage.add(Renderer.edges.layer);
    this.stage.add(Renderer.nodes.layer);
    this.stage.add(Renderer.layers.layer);
};
Renderer.canvas.resize = function(){
    var div = $(".ui-layout-center");
    Renderer.engine.particleSystem.screenSize(div.width(), div.height());
    Renderer.engine.particleSystem.screenPadding(80,200,80,80);
    this.stage.setSize(div.width(), div.height());
    Renderer.loop.redraw();
};

Renderer.Layer = function(id){
    this.id = id;
    this.shape = new Kinetic.Rect({
        width: this.width,
        height: this.height,
        x: 0,
        y: id * (this.height + 3) + 20,
        fill: "white"
    });
    this.checkAndSetColor();
    this.shape.layer = this;
    Renderer.layers.layer.add(this.shape);
    this.bindEvents();
    Renderer.layers.list.push(this);
};
Renderer.Layer.prototype = {
    width: 50,
    height: 20,
    delete: function(){
        this.shape.destroy();
        delete this;
    },
    bindEvents: function(){
        this.shape.on('click', this.mouseClick);
        this.shape.on('mouseover', this.mouseOver);
        this.shape.on('mouseout', this.mouseOut);
    },
    mouseOver: function(e){
        new Kinetic.Tween({
            node: this,
            easing: Kinetic.Easings['StrongEaseOut'],
            duration: 0.5,
            scaleX: 1.3
        }).play();
    },
    mouseOut: function(e){
        new Kinetic.Tween({
            node: this,
            easing: Kinetic.Easings['StrongEaseOut'],
            duration: 1,
            scaleX: 1
        }).play();
    },
    mouseClick: function(e){
        Renderer.layers.display(this.layer.id);
    },
    checkAndSetColor: function(){
        var intensity = 255;
        if(this.id === Renderer.layers.current)
            intensity = 150;

        this.shape.setAttrs({
            fillR: intensity,
            fillG: intensity,
            fillB: intensity
        });
    }
};
Renderer.layers = {};
Renderer.layers.list = [];
Renderer.layers.current = -1;
Renderer.layers.layer = new Kinetic.Layer({});
Renderer.layers.init = function(){
    for(var layer in this.list){
        this.list[layer].delete();
    }
    this.list = [];
    for(var i = 0; i < this.count; i++) {
        new Renderer.Layer(i);
    }
};
Renderer.layers.display = function(layer){
    if(layer !== this.current){
        this.current = layer;
        for (var layerId in this.list) {
            this.list[layerId].checkAndSetColor();
        }

        var edges = Renderer.engine.particleSystem.getEdgesFrom(Renderer.nodes.central.node);
        for(var edge in edges)
            Renderer.engine.particleSystem.pruneNode(edges[edge].target);

        for(var i = this.current * NODES_PER_LAYER; i < (this.current + 1) * NODES_PER_LAYER && i < Renderer.engine.jsonChildrenData.length; i++){
            var node = new Renderer.Node(Renderer.engine.jsonChildrenData[i].article);
            new Renderer.Edge(Renderer.nodes.central, node, Renderer.engine.jsonChildrenData[i].connection);
        }
    }
};

Renderer.Node = function(data){
    this.data = data;
    this.displayGroup = new  Kinetic.Group({x:-200, y:-200});
    this.displayPolygon = this.newPolygon();
    this.displayText = this.newText();
    this.node =  Renderer.engine.particleSystem.addNode(this.data.id, {node: this});
    this.displayPolygon.node = this;
    Renderer.nodes.layer.add(this.displayGroup);
    this.tweenPolygonHover = new Kinetic.Tween({
        node: this.displayPolygon,
        duration: 1,
        easing: Kinetic.Easings['StrongEaseOut'],
        fillB: 200,
        scaleX: 2,
        scaleY: 2,
        strokeWidth: 5
    });
    this.tweenTextHover = new Kinetic.Tween({
        node: this.displayText,
        duration: 1,
        easing: Kinetic.Easings['StrongEaseOut'],
        fontSize: 18,
        x: 80,
        y: -20,
        width: 300
    });
    this.bindEvents();
};
Renderer.Node.prototype = {
    shape: [[26,15],[0,30],[-26,15],[-26,-15],[0,-30],[26,-15]],
    delete: function(){
        this.displayGroup.destroy();
        Renderer.engine.particleSystem.originalPruneNode(this.node);
        delete this;
    },
    newPolygon: function(){
        var polygon = new Kinetic.Polygon({
            points: this.shape,
            fill: "black",
            stroke: "white",
            strokeWidth: 3
        });
        polygon.node = this;
        this.displayGroup.add(polygon);
        return polygon;
    },
    newText: function(){
        var text = new Kinetic.Text({
            text: this.data.title,
            fill: "white",
            width: 120
        });
        text.node = this;
        this.displayGroup.add(text);
        text.setPosition(31, -5);
        return text;
    },
    moveTo: function (pos){
        this.displayGroup.setPosition(pos.x, pos.y);
    },
    bindEvents: function(){
        this.displayPolygon.on('mouseover', this.mouseOver);
        this.displayPolygon.on('mouseout', this.mouseOut);
        this.displayPolygon.on('click', this.mouseClick);
        this.displayPolygon.on('dblclick dbltap', this.mouseDblClick);
    },
    mouseDblClick: function() {
        var id = this.node.data.KN_ID;
        Renderer.engine.centerOn(id, function(centralNodeData, childrenNodesData) {

            Renderer.engine.jsonOriginData = centralNodeData;
            Renderer.engine.jsonChildrenData = childrenNodesData;
            Renderer.navigation.navigationListener(id);

            var edges = Renderer.engine.particleSystem.getEdgesFrom(Renderer.nodes.central.node);
            var newCentral;
            for(var edge in edges) {
                var node = edges[edge].target;
                if(node.data.node.data.KN_ID !== id) {
                    Renderer.engine.particleSystem.pruneNode(node);
                } else {
                    newCentral = node.data.node;
                }
            }

            Renderer.nodes.central.delete();

            Renderer.nodes.central = newCentral;

            Renderer.layers.count = Math.ceil(Renderer.engine.jsonChildrenData.length / NODES_PER_LAYER);

            Renderer.layers.init();
            Renderer.layers.current = -1;
            Renderer.layers.display(0);
        });
    },
    mouseOver: function(){
       this.node.tweenPolygonHover.play();
       this.node.tweenTextHover.play();
    },
    mouseOut: function(){
        this.node.tweenPolygonHover.reverse();
        this.node.tweenTextHover.reverse();
    },
    mouseClick: function(){
        Renderer.nodes.selected = this.node;
        var data = this.node.data;
        $("#node-link").attr('href', data.url).text(data.title);
        $("#node-content").html(data.bodyText);
        PanelsHandler.layout.open("west");
    }
};

Renderer.nodes = {};
Renderer.nodes.selected = null;
Renderer.nodes.central = null;
Renderer.nodes.layer = new Kinetic.Layer({});

Renderer.Edge = function(from, to, data){
    this.from = from;
    this.to = to;
    this.data = data;
    this.edge = Renderer.engine.particleSystem.addEdge(from.node, to.node, {edge: this});
    this.line = this.newLine(data);

    this.bindEvents();
};
Renderer.Edge.prototype = {
    delete: function(){
        this.line.destroy();
        Renderer.engine.particleSystem.originalPruneEdge(this.edge);
        delete this;
    },
    newLine: function(connection){
        var stroke = "white";
        if (connection.connectionType === "explain") {
            stroke = "blue";
        } else if (connection.connectionType === "inspire") {
            stroke = "yellow";
        } else if (connection.connectionType === "question") {
            stroke = "green";
        } else if (connection.connectionType === "Wikipedia Link") {
            stroke = "gray";
        }

        var line =  new Kinetic.Line({
            points: [0,0,0,0],
            stroke: stroke,
            strokeWidth: 2
        });
        line.edge = this;
        Renderer.edges.layer.add(line);
        return line;
    },
    bindEvents: function(){
        this.line.on("mouseover", this.mouseOver);
        this.line.on("mouseout", this.mouseOut);
    },
    moveTo: function(pos1, pos2){

        function generatePoints(fromx, fromy, tox, toy){
            var hexagon = 30;
            var headlen = 10;
            var angle = Math.atan2(toy-fromy,tox-fromx);

            var newTox = tox-hexagon*Math.cos(angle);
            var newToy = toy-hexagon*Math.sin(angle);

            return [fromx, fromy
                    ,newTox,newToy
                    ,newTox-headlen*Math.cos(angle-Math.PI/6),newToy-headlen*Math.sin(angle-Math.PI/6)
                    ,newTox-headlen*Math.cos(angle+Math.PI/6),newToy-headlen*Math.sin(angle+Math.PI/6)
                    ,newTox,newToy
                    ];
        }

        var points = generatePoints(pos1.x, pos1.y, pos2.x, pos2.y);

        this.line.setAttr('points',points);
    },
    mouseOver: function(){
        new Kinetic.Tween({
            node: this,
            duration: 1,
            easing: Kinetic.Easings['StrongEaseOut'],
            strokeWidth: 5
        }).play();
    },
    mouseOut: function(){
        new Kinetic.Tween({
            node: this,
            duration: 1,
            easing: Kinetic.Easings['StrongEaseOut'],
            strokeWidth: 2
        }).play();
    }
};
Renderer.edges = {};
Renderer.edges.layer = new Kinetic.Layer({});

Renderer.loop = {}
Renderer.loop.init = function(){};
Renderer.loop.redraw = function(){
    Renderer.engine.particleSystem.eachEdge(function(edge, pt1, pt2){
        edge.data.edge.moveTo(pt1, pt2);
    });
    Renderer.engine.particleSystem.eachNode(function(node, pt){
        node.data.node.moveTo(pt);
    });
    Renderer.canvas.stage.draw();
};
<|endoftext|>


<commit_before>const Sequelize = require('sequelize');

const Database = require('../postgreSQL');

const database = new Database();

let Money = database.db.define('money', {
	userID: Sequelize.STRING,
	money: {
		type: Sequelize.INTEGER,
		defaultValue: 0
	}
});

Money.sync();

module.exports = Money;
<commit_msg>Add db entry for slotmachine<commit_after>const Sequelize = require('sequelize');

const Database = require('../postgreSQL');

const database = new Database();

let Money = database.db.define('money', {
	userID: Sequelize.STRING,
	money: {
		type: Sequelize.INTEGER,
		defaultValue: 0
	}
});

Money.sync();

Money.find({ where: { userID: 'SLOTMACHINE' } }).then(slotmachine => {
	if (!slotmachine) {
		Money.create({
			userID: 'SLOTMACHINE',
			money: 10000
		});
	}
});

module.exports = Money;
<|endoftext|>


<commit_before>'use strict';

blurAdminApp.directive('amChart', function () {
  return {
    restrict: 'E',
    controller: ['$scope', function ($scope) {
      var chartData = [
        { date: new Date(2011, 0), value: -30700},
        { date: new Date(2011, 1), value: -16800},
        { date: new Date(2011, 2), value: -7300},
        { date: new Date(2011, 3), value: -2700},
        { date: new Date(2011, 4), value: -25100},
        { date: new Date(2011, 5), value: -28100},
        { date: new Date(2011, 6), value: -34800},
        { date: new Date(2011, 7), value: -7400},
        { date: new Date(2011, 8), value: -1100},
        { date: new Date(2011, 9), value: -7400},
        { date: new Date(2011, 10), value: -12400},
        { date: new Date(2011, 11), value: -2400},
        { date: new Date(2012, 0), value: -2200},
        { date: new Date(2012, 1), value: 0},
        { date: new Date(2012, 2), value: -29600},
        { date: new Date(2012, 3), value: -21700},
        { date: new Date(2012, 4), value: -14700},
        { date: new Date(2012, 5), value: -1500},
        { date: new Date(2012, 6), value: -1600},
        { date: new Date(2012, 7), value: -1100},
        { date: new Date(2012, 8), value: -6800},
        { date: new Date(2012, 9), value: -1900},
        { date: new Date(2012, 10), value: -5600},
        { date: new Date(2012, 11), value: -7700},
        { date: new Date(2013, 0), value: -21300},
        { date: new Date(2013, 1), value: -13700},
        { date: new Date(2013, 2), value: -300},
        { date: new Date(2013, 3), value: 10900},
        { date: new Date(2013, 4), value: 20300},
        { date: new Date(2013, 5), value: 25500},
        { date: new Date(2013, 6), value: 10700},
        { date: new Date(2013, 7), value: -4200},
        { date: new Date(2013, 8), value: -5000},
        { date: new Date(2013, 9), value: 17700},
        { date: new Date(2013, 10), value: 25100},
        { date: new Date(2013, 11), value: 37000},
        { date: new Date(2014, 0), value: 300},
        { date: new Date(2014, 1), value: 17900},
        { date: new Date(2014, 2), value: 1800},
        { date: new Date(2014, 3), value: 10400},
        { date: new Date(2014, 4), value: 25500},
        { date: new Date(2014, 5), value: 2100},
        { date: new Date(2014, 6), value: 6500},
        { date: new Date(2014, 7), value: 1100},
        { date: new Date(2014, 8), value: 17200},
        { date: new Date(2014, 9), value: 26900},
        { date: new Date(2014, 10), value: 14100},
        { date: new Date(2014, 11), value: 35300},
        { date: new Date(2015, 0), value: 54800},
        { date: new Date(2015, 1), value: 29800},
        { date: new Date(2015, 2), value: 26700},
        { date: new Date(2015, 3), value: 41100},
        { date: new Date(2015, 4), value: 46200},
        { date: new Date(2015, 5), value: 4700},
        { date: new Date(2015, 6), value: 44500},
        { date: new Date(2015, 7), value: 4700}
      ];

      var chart = AmCharts.makeChart('amchart', {
        type: 'serial',
        theme: 'blur',
        marginTop: 0,
        marginRight: 15,
        dataProvider: chartData,
        valueAxes: [
          {
            gridAlpha: 0
          }
        ],
        graphs: [
          {
            id: 'g1',
            bullet: 'round',
            bulletSize: 8,
            useLineColorForBulletBorder: true,
            lineColor: colorSuccess,
            lineThickness: 1,
            negativeLineColor: colorDanger,
            type: 'smoothedLine',
            valueField: 'value',
            fillAlphas: 0.3,
            fillColorsField: 'lineColor'
          }
        ],
        chartScrollbar: {
          graph: 'g1',
          gridAlpha: 0,
          color: '#888888',
          scrollbarHeight: 55,
          backgroundAlpha: 0,
          selectedBackgroundAlpha: 0.1,
          selectedBackgroundColor: '#ffffff',
          graphFillAlpha: 0,
          autoGridCount: true,
          selectedGraphFillAlpha: 0,
          graphLineAlpha: 0.2,
          graphLineColor: '#c2c2c2',
          selectedGraphLineColor: '#888888',
          selectedGraphLineAlpha: 1
        },
        chartCursor: {
          categoryBalloonDateFormat: 'MM YYYY',
          categoryBalloonColor: '#4285F4',
          categoryBalloonAlpha: 0.7,
          cursorAlpha: 0,
          valueLineEnabled: true,
          valueLineBalloonEnabled: true,
          valueLineAlpha: 0.5
        },
        dataDateFormat: 'MM YYYY',
        categoryField: 'date',
        categoryAxis: {
          parseDates: true,
          gridAlpha: 0
        },
        export: {
          enabled: true
        },
        creditsPosition: 'bottom-right',
        zoomOutButton: {
          backgroundColor: '#fff',
          backgroundAlpha: 0
        },
        zoomOutText: '',
        pathToImages: 'img/'
      });

      function zoomChart() {
        chart.zoomToDates(new Date(2013, 3), new Date(2013, 10));
      }

      chart.addListener('rendered', zoomChart);
      zoomChart();
      if (chart.zoomChart) {
        chart.zoomChart();
      }
    }],
    templateUrl: 'app/pages/dashboard/widgets/amChart/amChart.html'
  };
});<commit_msg>change data for main dashboard chart<commit_after>'use strict';

blurAdminApp.directive('amChart', function () {
  return {
    restrict: 'E',
    controller: ['$scope', function ($scope) {
      var chartData = [
        { date: new Date(2012, 11), value: 0},
        { date: new Date(2013, 0), value: 15000},
        { date: new Date(2013, 1), value: 30000},

        { date: new Date(2013, 2), value: 25000},
        { date: new Date(2013, 3), value: 21000},
        { date: new Date(2013, 4), value: 24000},
        { date: new Date(2013, 5), value: 31000},
        { date: new Date(2013, 6), value: 40000},
        { date: new Date(2013, 7), value: 37000},
        { date: new Date(2013, 8), value: 20000},
        { date: new Date(2013, 9), value: 5000},
        { date: new Date(2013, 10), value: 40000},
        { date: new Date(2013, 11), value: 20000},
        { date: new Date(2014, 0), value: 5000},

        { date: new Date(2014, 1), value: 3000},
        { date: new Date(2014, 2), value: 1800},
        { date: new Date(2014, 3), value: 10400},
        { date: new Date(2014, 4), value: 25500},
        { date: new Date(2014, 5), value: 2100},
        { date: new Date(2014, 6), value: 6500},
        { date: new Date(2014, 7), value: 1100},
        { date: new Date(2014, 8), value: 17200},
        { date: new Date(2014, 9), value: 26900},
        { date: new Date(2014, 10), value: 14100},
        { date: new Date(2014, 11), value: 35300},
        { date: new Date(2015, 0), value: 54800},
        { date: new Date(2015, 1), value: 49800}
      ];

      var chart = AmCharts.makeChart('amchart', {
        type: 'serial',
        theme: 'blur',
        marginTop: 0,
        marginRight: 15,
        dataProvider: chartData,
        valueAxes: [
          {
            gridAlpha: 0
          }
        ],
        graphs: [
          {
            id: 'g1',
            bullet: 'round',
            bulletSize: 8,
            useLineColorForBulletBorder: true,
            lineColor: colorPrimary,
            lineThickness: 1,
            negativeLineColor: colorDanger,
            type: 'smoothedLine',
            valueField: 'value',
            fillAlphas: 1,
            fillColorsField: 'lineColor'
          }
        ],
        chartScrollbar: {
          graph: 'g1',
          gridAlpha: 0,
          color: '#888888',
          scrollbarHeight: 55,
          backgroundAlpha: 0,
          selectedBackgroundAlpha: 0.1,
          selectedBackgroundColor: '#ffffff',
          graphFillAlpha: 0,
          autoGridCount: true,
          selectedGraphFillAlpha: 0,
          graphLineAlpha: 0.2,
          graphLineColor: '#c2c2c2',
          selectedGraphLineColor: '#888888',
          selectedGraphLineAlpha: 1
        },
        chartCursor: {
          categoryBalloonDateFormat: 'MM YYYY',
          categoryBalloonColor: '#4285F4',
          categoryBalloonAlpha: 0.7,
          cursorAlpha: 0,
          valueLineEnabled: true,
          valueLineBalloonEnabled: true,
          valueLineAlpha: 0.5
        },
        dataDateFormat: 'MM YYYY',
        categoryField: 'date',
        categoryAxis: {
          parseDates: true,
          gridAlpha: 0
        },
        export: {
          enabled: true
        },
        creditsPosition: 'bottom-right',
        zoomOutButton: {
          backgroundColor: '#fff',
          backgroundAlpha: 0
        },
        zoomOutText: '',
        pathToImages: 'img/'
      });

      function zoomChart() {
        chart.zoomToDates(new Date(2013, 3), new Date(2014, 0));
      }

      chart.addListener('rendered', zoomChart);
      zoomChart();
      if (chart.zoomChart) {
        chart.zoomChart();
      }
    }],
    templateUrl: 'app/pages/dashboard/widgets/amChart/amChart.html'
  };
});<|endoftext|>


<commit_before>function extend(childInstance, parentInstance){
	var name;
	for (name in parentInstance){
	    if(!(name in childInstance)){
	        childInstance[name] = parentInstance[name];
	    }
	}
}

// SportsCar extends Car
function SportsCar(car){
	if(typeof(car) === "undefined" || car.getName !== "Car"){
		car = new Car();
	}

	extend(this, car);
	this.init(car);
}

SportsCar.prototype = (function(){
	var legalGuardian;

	return {
		getName: "SportsCar",
		hasSpoiler: false,

		init: function(car){
			legalGuardian = car;
		},

		// override
		determinePrice: function(){
			console.log("legal: " + legalGuardian.determinePrice());
			return 25;
		}
	};
})();<commit_msg>unprotect super<commit_after>function extend(childInstance, parentInstance){
	var name;
	for (name in parentInstance){
	    if(!(name in childInstance)){
	        childInstance[name] = parentInstance[name];
	    }
	}
}

// SportsCar extends Car
function SportsCar(car){
	if(typeof(car) === "undefined" || car.getName !== "Car"){
		car = new Car();
	}

	this.super = car;
	extend(this, car);
}

SportsCar.prototype = (function(){
	var legalGuardian;

	return {
		getName: "SportsCar",
		hasSpoiler: false,

		// override
		determinePrice: function(){
			console.log("legal: " + this.super.determinePrice());
			return 25;
		}
	};
})();<|endoftext|>


<commit_before>'use strict';

module.exports = (function() {
  var months = ['january','february','march','april','may','june','july',
  'august','september','october','november','december'];
  var shortMonths = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
  'sep', 'oct', 'nov', 'dec'];
  var weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
  'friday', 'saturday'];
  var shortWeekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

  function convertMonthName(expression, items){
    for(var i = 0; i < items.length; i++){
      expression = expression.replace(new RegExp(items[i], 'gi'), parseInt(i, 10) + 1);
    }
    return expression;
  }

  function convertWeekDayName(expression, items){
    for(var i = 0; i < items.length; i++){
      expression = expression.replace(new RegExp(items[i], 'gi'), parseInt(i, 10));
    }
    return expression;
  }

  function replaceWithRange(expression, text, init, end) {
    var numbers = [];
    for(var i = init; i <= end; i++) {
      numbers.push(i);
    }
    return expression.replace(new RegExp(text, 'gi'), numbers.join());
  }

  function convertRanges(expression){
    var rangeRegEx = /(\d+)\-(\d+)/;
    var match = rangeRegEx.exec(expression);
    while(match !== null && match.length > 0){
      expression = replaceWithRange(expression, match[0], match[1], match[2]);
      match = rangeRegEx.exec(expression);
    }
    return expression;
  }

  function convertAsteriskToRange(expression){
    var expressions = expression.split(' ');
    if(expressions.length == 5){
      expressions = ['0'].concat(expressions);
    }

    if(expressions[0] === '*'){
      expressions[0] = '0-59';
    }

    if(expressions[1] === '*'){
      expressions[1] = '0-59';
    }

    if(expressions[2] === '*'){
      expressions[2] = '0-23';
    }

    if(expressions[3] === '*'){
      expressions[3] = '1-31';
    }

    if(expressions[4] === '*'){
      expressions[4] = '1-12';
    }

    if(expressions[5] === '*'){
      expressions[5] = '0-6';
    }

    return expressions.join(' ');
  }

  /*
   * The node-cron core allows only numbers (including multiple numbers e.g 1,2).
   * This module is going to translate the month names, week day names and ranges
   * to integers relatives.
   *
   * Month names example:
   *  - expression 0 1 1 January,Sep *
   *  - Will be translated to 0 1 1 1,9 *
   *
   * Week day names example:
   *  - expression 0 1 1 2 Monday,Sat
   *  - Will be translated to 0 1 1 1,5 *
   *
   * Ranges example:
   *  - expression 1-5 * * * *
   *  - Will be translated to 1,2,3,4,5 * * * *
   */
   function interpretExpression(expression){
    expression = convertMonthName(expression, months);
    expression = convertMonthName(expression, shortMonths);
    expression = convertWeekDayName(expression, weekDays);
    expression = convertWeekDayName(expression, shortWeekDays);
    expression = convertAsteriskToRange(expression);
    expression = convertRanges(expression);
    return expression;
  }

  return interpretExpression;
}());

<commit_msg>refactor on interpreter<commit_after>'use strict';

module.exports = (function() {
  var months = ['january','february','march','april','may','june','july',
  'august','september','october','november','december'];
  var shortMonths = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
  'sep', 'oct', 'nov', 'dec'];
  var weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
  'friday', 'saturday'];
  var shortWeekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

  function convertMonthName(expression, items){
    for(var i = 0; i < items.length; i++){
      expression = expression.replace(new RegExp(items[i], 'gi'), parseInt(i, 10) + 1);
    }
    return expression;
  }

  function convertWeekDayName(expression, items){
    for(var i = 0; i < items.length; i++){
      expression = expression.replace(new RegExp(items[i], 'gi'), parseInt(i, 10));
    }
    return expression;
  }

  function replaceWithRange(expression, text, init, end) {
    var numbers = [];
    for(var i = init; i <= end; i++) {
      numbers.push(i);
    }
    return expression.replace(new RegExp(text, 'gi'), numbers.join());
  }

  function convertRanges(expression){
    var rangeRegEx = /(\d+)\-(\d+)/;
    var match = rangeRegEx.exec(expression);
    while(match !== null && match.length > 0){
      expression = replaceWithRange(expression, match[0], match[1], match[2]);
      match = rangeRegEx.exec(expression);
    }
    return expression;
  }

  function convertAsterisk(expression, index, replecement){
    var expressions = expression.split(' ');
    if(expressions.length == 5){
      expressions = ['0'].concat(expressions);
    }
    if(expressions[index] === '*'){
      expressions[index] = replecement;
    }
    return expressions.join(' ');
  }

  function convertAsteriskToRange(expression){
    expression = convertAsterisk(expression, 0, '0-59');
    expression = convertAsterisk(expression, 1, '0-59');
    expression = convertAsterisk(expression, 2, '0-23');
    expression = convertAsterisk(expression, 3, '1-31');
    expression = convertAsterisk(expression, 4, '1-12');
    expression = convertAsterisk(expression, 5, '0-6');
    return expression;
  }

  /*
   * The node-cron core allows only numbers (including multiple numbers e.g 1,2).
   * This module is going to translate the month names, week day names and ranges
   * to integers relatives.
   *
   * Month names example:
   *  - expression 0 1 1 January,Sep *
   *  - Will be translated to 0 1 1 1,9 *
   *
   * Week day names example:
   *  - expression 0 1 1 2 Monday,Sat
   *  - Will be translated to 0 1 1 1,5 *
   *
   * Ranges example:
   *  - expression 1-5 * * * *
   *  - Will be translated to 1,2,3,4,5 * * * *
   */
   function interpretExpression(expression){
    expression = convertMonthName(expression, months);
    expression = convertMonthName(expression, shortMonths);
    expression = convertWeekDayName(expression, weekDays);
    expression = convertWeekDayName(expression, shortWeekDays);
    expression = convertAsteriskToRange(expression);
    expression = convertRanges(expression);
    return expression;
  }

  return interpretExpression;
}());

<|endoftext|>


<commit_before>define([
    'require',
    '../logging'
], function(require) {
    var log = require('../logging').getLogger('navigation');

    // var match = function(curpath, path) {
    //     if (!path) {
    //         log.debug('path empty');
    //         return false;
    //     }

    //     // current path needs to end in the anchor's path
    //     if (path !== curpath.slice(- path.length)) {
    //         log.debug(curpath, 'does not end in', path);
    //         return false;
    //     }

    //     // XXX: we might need more exclusion tests
    //     return true;
    // };

    // var pathfromurl = function(url) {
    //     var path = url.split('#')[0].split('://');
    //     if (path.length > 2) {
    //         log.error('weird url', url);
    //         return '';
    //     }
    //     if (path.length === 1) return path[0];
    //     return path[1].split('/').slice(1).join('/');
    // };

    var init = function($el, opts) {
        var curpath = window.location.pathname;
        log.debug('current path:', curpath);

        // check whether to load
        if ($el.hasClass('navigation-load-current')) {
            $el.find('a.current, .current a').click();
            // check for current elements injected here
            $el.on('inject', function(ev) {
                var $target = $(ev.target);
                $target.find('a.current, .current a').click();
            });
        }

        // An element within this navigation triggered injection
        $el.on('patterns-inject-triggered', function(ev) {
            var $target = $(ev.target);

            // remove all set current classes
            $el.find('.current').removeClass('current');

            // set .current on target
            $target.addClass('current');

            // If target's parent is an LI, also set current there
            $target.parent('li').addClass('current');
        });

        // XXX: this code adjusted the current tag of newly page, this
        // should not happen client side but is the responsibility of
        // the server-side template. Client-side only for ajax
        // injections which is handled in the inject pattern
        //
        // $el.find('li a').each(function() {
        //     var $a = $(this),
        //         $li = $a.parents('li:first'),
        //         url = $a.attr('href'),
        //         path = pathfromurl(url);
        //     log.debug('checking url:', url, 'extracted path:', path);
        //     if (!match(curpath, path)) {
        //         $li.removeClass('current');
        //         return;
        //     }
        //     log.debug('found match', $li);
        //     $li.addClass('current');
        // });

        // TODO: bind handler to url changes ?

        return $el;
    };

    var pattern = {
        markup_trigger: 'nav, .navigation',
        init: init
    };
    return pattern;
});<commit_msg>fix navigation-load-current, but inject is not loaded yet<commit_after>define([
    'require',
    '../logging'
], function(require) {
    var log = require('../logging').getLogger('navigation');

    // var match = function(curpath, path) {
    //     if (!path) {
    //         log.debug('path empty');
    //         return false;
    //     }

    //     // current path needs to end in the anchor's path
    //     if (path !== curpath.slice(- path.length)) {
    //         log.debug(curpath, 'does not end in', path);
    //         return false;
    //     }

    //     // XXX: we might need more exclusion tests
    //     return true;
    // };

    // var pathfromurl = function(url) {
    //     var path = url.split('#')[0].split('://');
    //     if (path.length > 2) {
    //         log.error('weird url', url);
    //         return '';
    //     }
    //     if (path.length === 1) return path[0];
    //     return path[1].split('/').slice(1).join('/');
    // };

    var init = function($el, opts) {
        var curpath = window.location.pathname;
        log.debug('current path:', curpath);

        // check whether to load
        if ($el.hasClass('navigation-load-current')) {
            $el.find('a.current, .current a').click();
            // check for current elements injected here
            $el.on('inject', function(ev) {
                var $target = $(ev.target);
                $target.is('a.current') && $target.click();
                $target.is('.current') && $target.find('a').click();
            });
        }

        // An element within this navigation triggered injection
        $el.on('patterns-inject-triggered', function(ev) {
            var $target = $(ev.target);

            // remove all set current classes
            $el.find('.current').removeClass('current');

            // set .current on target
            $target.addClass('current');

            // If target's parent is an LI, also set current there
            $target.parent('li').addClass('current');
        });

        // XXX: this code adjusted the current tag of newly page, this
        // should not happen client side but is the responsibility of
        // the server-side template. Client-side only for ajax
        // injections which is handled in the inject pattern
        //
        // $el.find('li a').each(function() {
        //     var $a = $(this),
        //         $li = $a.parents('li:first'),
        //         url = $a.attr('href'),
        //         path = pathfromurl(url);
        //     log.debug('checking url:', url, 'extracted path:', path);
        //     if (!match(curpath, path)) {
        //         $li.removeClass('current');
        //         return;
        //     }
        //     log.debug('found match', $li);
        //     $li.addClass('current');
        // });

        // TODO: bind handler to url changes ?

        return $el;
    };

    var pattern = {
        markup_trigger: 'nav, .navigation',
        init: init
    };
    return pattern;
});<|endoftext|>


<commit_before>window.Models = {};
window.Collections = {};
window.Views = {};

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

Models.NLCDocumentGroup = Backbone.Model.extend({
  initialize: function() {}
});

Models.NLCDocument = Backbone.Model.extend({
  initialize: function() {}
});

Collections.NLCDocuments = Backbone.Collection.extend({
  model: Models.NLCDocument,
  initialize: function() {}
});

Collections.NLCDocumentGroups = Backbone.Collection.extend({
  model: Models.NLCDocumentGroup,
  initialize: function() {}
});

Views.NLCDocument = Backbone.View.extend({
  model: Models.NLCDocument,
  template: null,
  initialize: function() {
    this.template = _.template($('#link').html());
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    this.$el.find("input").prop('checked', this.model.get("isSelected"));
    return this;
  },
  events:
  {
    "click .list-group-item" : "toggleSelected"
  },
  toggleSelected: function() {
    if(this.model.get("isSelected")){
      this.model.set("isSelected", false);
      this.$el.find("input").prop('checked', false);
    } else {
      this.model.set("isSelected", true);
      this.$el.find("input").prop('checked', true);
    }
  }
});

Views.NLCDocumentGroup = Backbone.View.extend({
  model: Models.NLCDocumentGroup,
  template: null,
  initialize: function() {
    this.template = _.template($('#docGroup').html());
    this.collection = new Collections.NLCDocuments(this.model.get("links"));
  },
  render: function(filterMails) {
    this.$el.html(this.template(this.model.toJSON()));
    var $links = this.$el.find(".list-group");
    $links.empty();
    this.collection.each(function(model) {
      if(filterMails && !model.get("mail"))
      {
        return;
      }
      var nlcDocument = new Views.NLCDocument({
        model: model
      });
      $links.append(nlcDocument.render().el);
    });
    return this;
  },
  events:
  {
    "click .panel-heading" : "toggleList"
  },
  toggleList: function(){
    this.$el.find(".list-group").slideToggle();
  }
});

Views.NLC = Backbone.View.extend({
  collection: null,
  initialize: function() {
    this.collection = new Collections.NLCDocumentGroups(this.getLinksFromCSV());
    this.subviews = [];
    var that = this;
    this.collection.each(function(group) {
      var nlcDocumentGroup = new Views.NLCDocumentGroup({
        model: group
      });
      that.subviews.push(nlcDocumentGroup);
    });
    this.mode = "email";
    this.render();
  },
  render: function() {
    var $main = this.$el.find("#main");
    $main.empty();
    var that = this;
    if(this.mode == "email")
    {
      this.$el.find("#mailButton").removeClass("active");
      this.$el.find("#emailButton").addClass("active");
      this.$el.find("#mailForm").hide("");
      this.$el.find("#emailForm").show("");
    }
    else
    {
      this.$el.find("#emailButton").removeClass("active");
      this.$el.find("#mailButton").addClass("active");
      this.$el.find("#emailForm").hide("");
      this.$el.find("#mailForm").show("");
    }
    _.each(this.subviews, function(view)
    {
      $main.append(view.render(that.mode == "mail").el);
    });
  },
  events:
  {
    "click #emailButton": "emailMode",
    "click #mailButton": "mailMode",
    "click #send": "send"
  },
  emailMode: function() {
    this.mode = "email";
    this.render();
  },
  mailMode: function() {
    this.mode = "mail";
    this.render();
  },
  send: function() {
    var sendables =  [];
    var that = this;
    _.each(this.subviews, function(view) {
      sendables.push(new Collections.NLCDocuments(view.collection.where({isSelected: true})).toJSON());
    });
    console.log(_.flatten(sendables));
  },
  getLinksFromCSV : function() {
    //Where we parse the csv and then return the Array of JSON
    // $.ajax({ //my ajax request
    //         url: "http://www.kcba.org/pbs/pdf/NLCMap.csv",
    //         type: "GET",
    //         dataType: "text",
    //         success : function(response){
    //          // csvToArray(response);
    //          arr1 = csvToArray(str1);
    //          console.log(arr1);
    //         }
    // });

    var str1 = "Document Title,Document Category,Link,Available to receive by mail\r\n" +
          "Client Intake Form - English,ADMINISTRATION,http://www.kcba.org/pbs/pdf/NLClinks/intakesheet.pdf,FALSE\r\nClient Intake Form—Spanish,ADMINISTRATION,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—Spanish,CATEGORY,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—English,CATEGORY2,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—English,CATEGORY,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-English.pdf,FALSE";

    var arr1 = csvToArray(str1);
    // console.log(arr1);
    var links = arrToJson(arr1);
    console.log(links);

    //convert array to json
    function arrToJson(arr){
      console.log(arr);
      var arr2 = {};
      for(var i=1; i<arr.length; i++){
        var obj1 = {};
        if(!arr2[arr[i][1]]){
          arr2[arr[i][1]] = {};
        }
        arr2[arr[i][1]]["groupName"] = arr[i][1];
        if(!arr2[arr[i][1]]["links"]){
          arr2[arr[i][1]]["links"] = [];
        }

        obj1["linkName"] = arr[i][0];
        obj1["linkURL"] = arr[i][2];
        obj1["mail"] = Boolean.valueOf(arr[i][3])();
        arr2[arr[i][1]]["links"].push(obj1);
      }
      var arr3 = [];
      for(var i in arr2){
        arr3.push(arr2[i]);
      }
      return arr3;
    }

    //Convert CSV to Array
    function csvToArray (strData, strDelimiter){
        // Check to see if the delimiter is defined. If not,
        // then default to comma.
        strDelimiter = (strDelimiter || ",");

        // Create a regular expression to parse the CSV values.
        var objPattern = new RegExp(
            (
                // Delimiters.
                "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                // Quoted fields.
                "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                // Standard fields.
                "([^\"\\" + strDelimiter + "\\r\\n]*))"
            ),
            "gi"
            );
        // Create an array to hold our data. Give the array
        // a default empty first row.
        var arrData = [[]];

        // Create an array to hold our individual pattern
        // matching groups.
        var arrMatches = null;

        // Keep looping over the regular expression matches
        // until we can no longer find a match.
        while (arrMatches = objPattern.exec(strData)) {

            // Get the delimiter that was found.
            var strMatchedDelimiter = arrMatches[1];

            // Check to see if the given delimiter has a length
            // (is not the start of string) and if it matches
            // field delimiter. If id does not, then we know
            // that this delimiter is a row delimiter.
            if (
                strMatchedDelimiter.length &&
                strMatchedDelimiter !== strDelimiter
                ) {

                // Since we have reached a new row of data,
                // add an empty row to our data array.
                arrData.push([]);

            }

            var strMatchedValue;

            // Now that we have our delimiter out of the way,
            // let's check to see which kind of value we
            // captured (quoted or unquoted).
            if (arrMatches[2]) {

                // We found a quoted value. When we capture
                // this value, unescape any double quotes.
                strMatchedValue = arrMatches[2].replace(
                    new RegExp("\"\"", "g"),
                    "\""
                    );

            } else {

                // We found a non-quoted value.
                strMatchedValue = arrMatches[3];

            }

            // Now that we have our value string, let's add
            // it to the data array.
            arrData[arrData.length - 1].push(strMatchedValue);
        }

        // Return the parsed data.
        return (arrData);
    };

    return links;
  }
});

$(function() {
  var documentGroup = new Views.NLC({
    el: $("body")
  });
});
<commit_msg>adjusted to live ajax call<commit_after>window.Models = {};
window.Collections = {};
window.Views = {};

_.templateSettings = {
  interpolate: /\{\{(.+?)\}\}/g
};

Models.NLCDocumentGroup = Backbone.Model.extend({
  initialize: function() {}
});

Models.NLCDocument = Backbone.Model.extend({
  initialize: function() {}
});

Collections.NLCDocuments = Backbone.Collection.extend({
  model: Models.NLCDocument,
  initialize: function() {}
});

Collections.NLCDocumentGroups = Backbone.Collection.extend({
  model: Models.NLCDocumentGroup,
  initialize: function() {}
});

Views.NLCDocument = Backbone.View.extend({
  model: Models.NLCDocument,
  template: null,
  initialize: function() {
    this.template = _.template($('#link').html());
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    this.$el.find("input").prop('checked', this.model.get("isSelected"));
    return this;
  },
  events:
  {
    "click .list-group-item" : "toggleSelected"
  },
  toggleSelected: function() {
    if(this.model.get("isSelected")){
      this.model.set("isSelected", false);
      this.$el.find("input").prop('checked', false);
    } else {
      this.model.set("isSelected", true);
      this.$el.find("input").prop('checked', true);
    }
  }
});

Views.NLCDocumentGroup = Backbone.View.extend({
  model: Models.NLCDocumentGroup,
  template: null,
  initialize: function() {
    this.template = _.template($('#docGroup').html());
    this.collection = new Collections.NLCDocuments(this.model.get("links"));
  },
  render: function(filterMails) {
    this.$el.html(this.template(this.model.toJSON()));
    var $links = this.$el.find(".list-group");
    $links.empty();
    this.collection.each(function(model) {
      if(filterMails && !model.get("mail"))
      {
        return;
      }
      var nlcDocument = new Views.NLCDocument({
        model: model
      });
      $links.append(nlcDocument.render().el);
    });
    return this;
  },
  events:
  {
    "click .panel-heading" : "toggleList"
  },
  toggleList: function(){
    this.$el.find(".list-group").slideToggle();
  }
});

Views.NLC = Backbone.View.extend({
  collection: null,
  initialize: function() {
    this.collection = new Collections.NLCDocumentGroups(this.getLinksFromCSV());
    this.subviews = [];
    var that = this;
    this.collection.each(function(group) {
      var nlcDocumentGroup = new Views.NLCDocumentGroup({
        model: group
      });
      that.subviews.push(nlcDocumentGroup);
    });
    this.mode = "email";
    this.render();
  },
  render: function() {
    var $main = this.$el.find("#main");
    $main.empty();
    var that = this;
    if(this.mode == "email")
    {
      this.$el.find("#mailButton").removeClass("active");
      this.$el.find("#emailButton").addClass("active");
      this.$el.find("#mailForm").hide("");
      this.$el.find("#emailForm").show("");
    }
    else
    {
      this.$el.find("#emailButton").removeClass("active");
      this.$el.find("#mailButton").addClass("active");
      this.$el.find("#emailForm").hide("");
      this.$el.find("#mailForm").show("");
    }
    _.each(this.subviews, function(view)
    {
      $main.append(view.render(that.mode == "mail").el);
    });
  },
  events:
  {
    "click #emailButton": "emailMode",
    "click #mailButton": "mailMode",
    "click #send": "send"
  },
  emailMode: function() {
    this.mode = "email";
    this.render();
  },
  mailMode: function() {
    this.mode = "mail";
    this.render();
  },
  send: function() {
    var sendables =  [];
    var that = this;
    _.each(this.subviews, function(view) {
      sendables.push(new Collections.NLCDocuments(view.collection.where({isSelected: true})).toJSON());
    });
    console.log(_.flatten(sendables));
  },
  getLinksFromCSV : function() {
    //Where we parse the csv and then return the Array of JSON
    var arr1;
    $.ajax({ //my ajax request
            url: "../NLCMap.csv",
            type: "GET",
            dataType: "text",
            async: false,
            success : function(response){
             console.log("ajax response: "+response);
             arr1 = csvToArray(response);
             console.log("arr1 "+arr1);
            }
    });

    // sample data
    // var str1 = "Document Title,Document Category,Link,Available to receive by mail\r\n" +
    //       "Client Intake Form - English,ADMINISTRATION,http://www.kcba.org/pbs/pdf/NLClinks/intakesheet.pdf,FALSE\r\nClient Intake Form—Spanish,ADMINISTRATION,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—Spanish,CATEGORY,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—English,CATEGORY2,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-Spanish.pdf,FALSE\r\nClient Intake Form—English,CATEGORY,http://www.kcba.org/pbs/pdf/NLClinks/IntakeSheet-English.pdf,FALSE";

    var links = arrToJson(arr1);
    console.log("Links: "+links);

    //convert array to json
    function arrToJson(arr){
      console.log(arr);
      var arr2 = {};
      for(var i=1; i<arr.length; i++){
        var obj1 = {};
        if(!arr2[arr[i][1]]){
          arr2[arr[i][1]] = {};
        }
        arr2[arr[i][1]]["groupName"] = arr[i][1];
        if(!arr2[arr[i][1]]["links"]){
          arr2[arr[i][1]]["links"] = [];
        }

        obj1["linkName"] = arr[i][0];
        obj1["linkURL"] = arr[i][2];
        obj1["mail"] = Boolean.valueOf(arr[i][3])();
        arr2[arr[i][1]]["links"].push(obj1);
      }
      var arr3 = [];
      for(var i in arr2){
        arr3.push(arr2[i]);
      }
      return arr3;
    }

    //Convert CSV to Array
    function csvToArray (strData, strDelimiter){
        // Check to see if the delimiter is defined. If not,
        // then default to comma.
        strDelimiter = (strDelimiter || ",");

        // Create a regular expression to parse the CSV values.
        var objPattern = new RegExp(
            (
                // Delimiters.
                "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

                // Quoted fields.
                "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

                // Standard fields.
                "([^\"\\" + strDelimiter + "\\r\\n]*))"
            ),
            "gi"
            );
        // Create an array to hold our data. Give the array
        // a default empty first row.
        var arrData = [[]];

        // Create an array to hold our individual pattern
        // matching groups.
        var arrMatches = null;

        // Keep looping over the regular expression matches
        // until we can no longer find a match.
        while (arrMatches = objPattern.exec(strData)) {
            // Get the delimiter that was found.
            var strMatchedDelimiter = arrMatches[1];

            // Check to see if the given delimiter has a length
            // (is not the start of string) and if it matches
            // field delimiter. If id does not, then we know
            // that this delimiter is a row delimiter.
            if (
                strMatchedDelimiter.length &&
                strMatchedDelimiter !== strDelimiter
                ) {
                // Since we have reached a new row of data,
                // add an empty row to our data array.
                arrData.push([]);
            }

            var strMatchedValue;

            // Now that we have our delimiter out of the way,
            // let's check to see which kind of value we
            // captured (quoted or unquoted).
            if (arrMatches[2]) {

                // We found a quoted value. When we capture
                // this value, unescape any double quotes.
                strMatchedValue = arrMatches[2].replace(
                    new RegExp("\"\"", "g"),
                    "\""
                    );

            } else {

                // We found a non-quoted value.
                strMatchedValue = arrMatches[3];

            }

            // Now that we have our value string, let's add
            // it to the data array.
            arrData[arrData.length - 1].push(strMatchedValue);
        }

        // Return the parsed data.
        return (arrData);
    }; //Convert CSV to Array

    return links;
  }
});

$(function() {
  var documentGroup = new Views.NLC({
    el: $("body")
  });
});
<|endoftext|>