<commit_before>describe('wrapper', function () {
  beforeEach(function () {
    jasmine.Ajax.install();
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('should make an http request', function (done) {
    var request;

    axios({
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.url).toBe('/foo');
      done();
    }, 0);
  });

  it('should default common headers', function (done) {
    var request;
    var headers = axios.defaults.headers.common;

    axios({
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      for (var key in headers) {
        if (headers.hasOwnProperty(key)) {
          expect(request.requestHeaders[key]).toEqual(headers[key]);
        }
      }
      done();
    }, 0);
  });

  it('should add extra headers for post', function (done) {
    var request;
    var headers = axios.defaults.headers.common;

    axios({
      method: 'post',
      url: '/foo',
      data: 'fizz=buzz'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      for (var key in headers) {
        if (headers.hasOwnProperty(key)) {
          expect(request.requestHeaders[key]).toEqual(headers[key]);
        }
      }
      done();
    }, 0);
  });

  it('should use application/json when posting an object', function (done) {
    var request;

    axios({
      url: '/foo/bar',
      method: 'post',
      data: {
        firstName: 'foo',
        lastName: 'bar'
      }
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.requestHeaders['Content-Type']).toEqual('application/json;charset=utf-8');
      done();
    }, 0);
  });

  it('should support binary data as array buffer', function (done) {
    var request;
    var input = new Int8Array(2);
    input[0] = 1;
    input[1] = 2;

    axios({
      method: 'post',
      url: '/foo',
      data: input.buffer
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      var output = new Int8Array(request.params.buffer);
      expect(output.length).toEqual(2);
      expect(output[0]).toEqual(1);
      expect(output[1]).toEqual(2);
      done();
    }, 0);
  });

  it('should support binary data as array buffer view', function (done) {
    var request;
    var input = new Int8Array(2);
    input[0] = 1;
    input[1] = 2;

    axios({
      method: 'post',
      url: '/foo',
      data: input
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      var output = new Int8Array(request.params.buffer);
      expect(output.length).toEqual(2);
      expect(output[0]).toEqual(1);
      expect(output[1]).toEqual(2);
      done();
    }, 0);
  });

  it('should remove content-type if data is empty', function (done) {
    var request;

    axios({
      method: 'post',
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.requestHeaders['content-type']).toEqual(undefined);
      done();
    }, 0);
  });

  // TODO this won't work until karma-jasmine updates to jasmine-ajax 3.0.0
  /*
  it('should support array buffer response', function (done) {
    var request, response;

    function str2ab(str) {
      var buff = new ArrayBuffer(str.length * 2);
      var view = new Uint16Array(buff);
      for ( var i=0, l=str.length; i<l; i++) {
        view[i] = str.charCodeAt(i);
      }
      return buff;
    }

    axios({
      url: '/foo',
      responseType: 'arraybuffer'
    }).then(function (data) {
      response = data;
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      request.respondWith({
        status: 200,
        response: str2ab('Hello world')
      });

      setTimeout(function () {
        expect(response.data.byteLength).toBe(22);
        done();
      }, 0);
    }, 0);
  });
  //*/

});
<commit_msg>Test passing now<commit_after>describe('wrapper', function () {
  beforeEach(function () {
    jasmine.Ajax.install();
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('should make an http request', function (done) {
    var request;

    axios({
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.url).toBe('/foo');
      done();
    }, 0);
  });

  it('should default common headers', function (done) {
    var request;
    var headers = axios.defaults.headers.common;

    axios({
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      for (var key in headers) {
        if (headers.hasOwnProperty(key)) {
          expect(request.requestHeaders[key]).toEqual(headers[key]);
        }
      }
      done();
    }, 0);
  });

  it('should add extra headers for post', function (done) {
    var request;
    var headers = axios.defaults.headers.common;

    axios({
      method: 'post',
      url: '/foo',
      data: 'fizz=buzz'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      for (var key in headers) {
        if (headers.hasOwnProperty(key)) {
          expect(request.requestHeaders[key]).toEqual(headers[key]);
        }
      }
      done();
    }, 0);
  });

  it('should use application/json when posting an object', function (done) {
    var request;

    axios({
      url: '/foo/bar',
      method: 'post',
      data: {
        firstName: 'foo',
        lastName: 'bar'
      }
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.requestHeaders['Content-Type']).toEqual('application/json;charset=utf-8');
      done();
    }, 0);
  });

  it('should support binary data as array buffer', function (done) {
    var request;
    var input = new Int8Array(2);
    input[0] = 1;
    input[1] = 2;

    axios({
      method: 'post',
      url: '/foo',
      data: input.buffer
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      var output = new Int8Array(request.params.buffer);
      expect(output.length).toEqual(2);
      expect(output[0]).toEqual(1);
      expect(output[1]).toEqual(2);
      done();
    }, 0);
  });

  it('should support binary data as array buffer view', function (done) {
    var request;
    var input = new Int8Array(2);
    input[0] = 1;
    input[1] = 2;

    axios({
      method: 'post',
      url: '/foo',
      data: input
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      var output = new Int8Array(request.params.buffer);
      expect(output.length).toEqual(2);
      expect(output[0]).toEqual(1);
      expect(output[1]).toEqual(2);
      done();
    }, 0);
  });

  it('should remove content-type if data is empty', function (done) {
    var request;

    axios({
      method: 'post',
      url: '/foo'
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      expect(request.requestHeaders['content-type']).toEqual(undefined);
      done();
    }, 0);
  });

  it('should support array buffer response', function (done) {
    var request, response;

    function str2ab(str) {
      var buff = new ArrayBuffer(str.length * 2);
      var view = new Uint16Array(buff);
      for ( var i=0, l=str.length; i<l; i++) {
        view[i] = str.charCodeAt(i);
      }
      return buff;
    }

    axios({
      url: '/foo',
      responseType: 'arraybuffer'
    }).then(function (data) {
      response = data;
    });

    setTimeout(function () {
      request = jasmine.Ajax.requests.mostRecent();

      request.respondWith({
        status: 200,
        response: str2ab('Hello world')
      });

      setTimeout(function () {
        expect(response.data.byteLength).toBe(22);
        done();
      }, 0);
    }, 0);
  });

});
<|endoftext|>


<commit_before>function setStyle(id,style,value)
{
    id.style[style] = value;
}
function opacity(el,opacity)
{
        setStyle(el,"filter:","alpha(opacity="+opacity+")");
        setStyle(el,"-moz-opacity",opacity/0);
        setStyle(el,"-khtml-opacity",opacity/0);
        setStyle(el,"opacity",opacity/0);
}
function calendar()
{
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth();
        var year = date.getYear();
        if(year<=200)
        {
                year += 1900;
        }
        months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
        days_in_month = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        if(year%4 == 0 && year!=1900)
        {
                days_in_month[1]=29;
        }
        total = days_in_month[month];
        var date_today = day+' '+months[month]+' '+year;
        beg_j = date;
        beg_j.setDate(1);
        if(beg_j.getDate()==2)
        {
                beg_j=setDate(0);
        }
        beg_j = beg_j.getDay();
        document.write('

'+date_today+'
');
        document.write('
Sun	Mon	Tue	Wed	Thu	Fri	Sat

');
        week = 0;
        for(i=1;i<=beg_j;i++)
        {
                document.write(''+(days_in_month[month-1]-beg_j+i)+'	');
                week++;
        }
        for(i=1;i<=total;i++)
        {
                if(week==0)
                {
                        document.write('
');
                }
                if(day==i)
                {
                        document.write(''+i+'	');
                }
                else
                {
                        document.write(''+i+'	');
                }
                week++;
                if(week==7)
                {
                        document.write('
');
                        week=0;
                }
        }
        for(i=1;week!=0;i++)
        {
                document.write(''+i+'	');
                week++;
                if(week==7)
                {
                        document.write('
');
                        week=0;
                }
        }
        document.write('

');
        opacity(document.getElementById('cal_body'),255);
        return true;
}<commit_msg>Delete calendar.js<commit_after><|endoftext|>


<commit_before>/**
 * Created by Ehbraheem on 14/03/2017.
 */

(function () {

    "use strict";

    angular
        .module("pay.product")
        .service("pay.product.Products", ProductService);

    ProductService.$inject = [];

    function ProductService() {

        var service = this;
        service.products = [

            {
                "Core Lab": [
                    {
                        "name": "App Lab",
                        "price": 200000,
                        "duration": "4 months"
                    },
                    {
                        "name": "Workforce Lab",
                        "price": 400000,
                        "duration": "4 months"
                    }
                ]
            },
            {"S.T.E.M" : [
                {
                    "name" : "Robotics",
                    "price" : 35000,
                    "duration": "1 Week"
                },
                {
                    "name" : "Creative Computing",
                    "price" : 35000,
                    "duration": "1 Week"
                },
                {
                    "name": "Science Lab (Python)",
                    "price": 50000,
                    "duration": "2 Weeks"
                }
            ]
            } ,
            {
                "Corporate training": [
                    {
                        "name": "Social media & marketing",
                        "price": 50000,
                        "duration": "1 Week"
                    },
                    {
                        "name": "Business intelligent",
                        "price": 50000,
                        "duration": "1 Week"
                    }
                ]
            }
        ];

        service.allProducts = allProducts;

        service.getProductList = getProductList;

        service.getSingleProduct = getSingleProduct;

        return;
        ///////////////////////

        function allProducts() {
            return service.products;
        }

        function getProductList(index) {
            return service.products[key];
        }

        function getSingleProduct(topIndex, productIndex) {
            return service.products[topIndex][productIndex];
        }
    }
})();<commit_msg>Fixed typo<commit_after>/**
 * Created by Ehbraheem on 14/03/2017.
 */

(function () {

    "use strict";

    angular
        .module("pay.product")
        .service("pay.product.Products", ProductService);

    ProductService.$inject = [];

    function ProductService() {

        var service = this;
        service.products = [

            {
                "Core Lab": [
                    {
                        "name": "App Lab",
                        "price": 200000,
                        "duration": "4 months"
                    },
                    {
                        "name": "Workforce Lab",
                        "price": 400000,
                        "duration": "4 months"
                    }
                ]
            },
            {"S.T.E.M" : [
                {
                    "name" : "Robotics",
                    "price" : 35000,
                    "duration": "1 Week"
                },
                {
                    "name" : "Creative Computing",
                    "price" : 35000,
                    "duration": "1 Week"
                },
                {
                    "name": "Science Lab (Python)",
                    "price": 50000,
                    "duration": "2 Weeks"
                }
            ]
            } ,
            {
                "Corporate training": [
                    {
                        "name": "Social media & marketing",
                        "price": 50000,
                        "duration": "1 Week"
                    },
                    {
                        "name": "Business intelligent",
                        "price": 50000,
                        "duration": "1 Week"
                    }
                ]
            }
        ];

        service.allProducts = allProducts;

        service.getProductList = getProductList;

        service.getSingleProduct = getSingleProduct;

        return;
        ///////////////////////

        function allProducts() {
            return service.products;
        }

        function getProductList(index) {
            return service.products[key];
        }

        function getSingleProduct(topIndex, productIndex) {
            return service.products[topIndex][productIndex];
        }
    }
})();<|endoftext|>


<commit_before>var path = require('path');
var angular = require('angular');

function isNode(node) {
  if( typeof Node === 'object' && node instanceof Node ) return true;
  if( typeof node.nodeType === 'number' && node.nodeName ) return true;
  return false;
}

function isElement(node) {
  if( typeof Element === 'object' && node instanceof Element ) return true;
  if( node.nodeType === 1 && node.tagName && typeof node.setAttribute === 'function' ) return true;
  return false;
}

function isArrayLike(o) {
  if( o && typeof o === 'object' && typeof o.length === 'number' ) return true;
  return false;
}

var container = document.createElement('div');
function evalhtml(html) {
  container.innerHTML = html;
  var children = [].slice.call(container.childNodes);
  container.innerHTML = '';
  return children;
}

function ajax(src, done) {
  if( !src ) throw new Error('missing src');

  var text, error;
  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('GET', src, true);
  xhr.onreadystatechange = function(e) {
    if( this.readyState == 4 ) {
      if( this.status == 0 || (this.status >= 200 && this.status < 300) ) done(null, this.responseText);
      else done(new Error('[' + this.status + '] ' + this.responseText));
    }
  };
  xhr.send();
}

module.exports = function(options) {
  options = options || {};

  var base = options.base || '/';
  var parent = options.parent || document.documentElement;
  var defaultTarget = options.target || options.defaultTarget;
  var onload = options.onload;
  var onrender = options.onrender;
  var onpack = options.onpack;

  return function(req, res, next) {
    res.apply = function(scope, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( isNode(scope) ) scope = angular.element(scope).scope();
      if( !scope ) return done(new TypeError('not found angular scope'));
      if( !scope.$root ) return done(new TypeError('invalid angular scope (scope.$root not found)'));
      if( !scope.$apply ) return done(new TypeError('invalid angular scope (scope.$apply not found)'));

      if( scope.$root.$$phase != '$digest' && scope.$root.$$phase != '$apply' ) {
        scope.$apply(function() {done && done(null, scope);});
      } else {
        done && done(null, scope);
      }

      return this;
    };

    res.pack = function(target, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( !target ) return done(new TypeError('missing target'));
      if( isNode(target) ) target = [target];
      if( !isArrayLike(target) ) return done(new TypeError('unknwon type of target: ' +  target));

      var root = angular.element(parent);
      var injector = root.injector();

      [].forEach.call(target, function(el) {
        if( el.__packed__ ) return;
        el.__packed__ = true;

        injector.invoke(function($compile, $rootScope) {
          $compile(el)($rootScope);
          $rootScope.$digest();
        });
      });

      onpack && onpack(null, target);
      done(null, target);
      return this;
    };

    res.scope = function(el) {
      if( el.length ) return angular.element(el[0]).scope();
      return angular.element(el).scope();
    };

    res.render = function(src, options, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( !src ) return done(new TypeError('missing src'));
      if( typeof options === 'string' ) options = {target:options};
      if( typeof options === 'function' ) done = options, options = null;

      options = options || {};
      var controller = options.controller;
      var target = options.target || defaultTarget;
      var targetel = document.querySelector(target);
      if( typeof controller !== 'string' ) return done(new TypeError('controller must be a string'));
      if( !targetel ) return done(new TypeError('undefined target:' + target));

      function render(els) {
        if( controller ) [].forEach.call(els, function(node) {
          if( isElement(node) && !node.hasAttribute('ng-controller') )
            node.setAttribute('ng-controller', controller);
        })

        res.pack(els, function(err) {
          if( err ) return done(err);

          targetel.innerHTML = '';
          [].forEach.call(els, function(node) {

            targetel.appendChild(node);
          });

          onrender && onrender(null, els);
          done(null, els);
        });
      }

      if( typeof src === 'string' ) ajax(path.join(base, src), function(err, html) {
        if( err ) return done(err), onload && onload(err);
        var els = evalhtml(html);
        onload && onload(null, els);
        render(els);
      });
      else if( isNode(src) ) render([src]);
      else if( isArrayLike(src) ) render(src);
      else return done(new TypeError('unknwon type of src: ' + src));
    };

    next();
    return this;
  };
};<commit_msg>Fix res.render options:controller<commit_after>var path = require('path');
var angular = require('angular');

function isNode(node) {
  if( typeof Node === 'object' && node instanceof Node ) return true;
  if( typeof node.nodeType === 'number' && node.nodeName ) return true;
  return false;
}

function isElement(node) {
  if( typeof Element === 'object' && node instanceof Element ) return true;
  if( node.nodeType === 1 && node.tagName && typeof node.setAttribute === 'function' ) return true;
  return false;
}

function isArrayLike(o) {
  if( o && typeof o === 'object' && typeof o.length === 'number' ) return true;
  return false;
}

var container = document.createElement('div');
function evalhtml(html) {
  container.innerHTML = html;
  var children = [].slice.call(container.childNodes);
  container.innerHTML = '';
  return children;
}

function ajax(src, done) {
  if( !src ) throw new Error('missing src');

  var text, error;
  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  xhr.open('GET', src, true);
  xhr.onreadystatechange = function(e) {
    if( this.readyState == 4 ) {
      if( this.status == 0 || (this.status >= 200 && this.status < 300) ) done(null, this.responseText);
      else done(new Error('[' + this.status + '] ' + this.responseText));
    }
  };
  xhr.send();
}

module.exports = function(options) {
  options = options || {};

  var base = options.base || '/';
  var parent = options.parent || document.documentElement;
  var defaultTarget = options.target || options.defaultTarget;
  var onload = options.onload;
  var onrender = options.onrender;
  var onpack = options.onpack;

  return function(req, res, next) {
    res.apply = function(scope, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( isNode(scope) ) scope = angular.element(scope).scope();
      if( !scope ) return done(new TypeError('not found angular scope'));
      if( !scope.$root ) return done(new TypeError('invalid angular scope (scope.$root not found)'));
      if( !scope.$apply ) return done(new TypeError('invalid angular scope (scope.$apply not found)'));

      if( scope.$root.$$phase != '$digest' && scope.$root.$$phase != '$apply' ) {
        scope.$apply(function() {done && done(null, scope);});
      } else {
        done && done(null, scope);
      }

      return this;
    };

    res.pack = function(target, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( !target ) return done(new TypeError('missing target'));
      if( isNode(target) ) target = [target];
      if( !isArrayLike(target) ) return done(new TypeError('unknwon type of target: ' +  target));

      var root = angular.element(parent);
      var injector = root.injector();

      [].forEach.call(target, function(el) {
        if( el.__packed__ ) return;
        el.__packed__ = true;

        injector.invoke(function($compile, $rootScope) {
          $compile(el)($rootScope);
          $rootScope.$digest();
        });
      });

      onpack && onpack(null, target);
      done(null, target);
      return this;
    };

    res.scope = function(el) {
      if( el.length ) return angular.element(el[0]).scope();
      return angular.element(el).scope();
    };

    res.render = function(src, options, done) {
      done = done || function(err) { if( err ) console.error(err) };
      if( !src ) return done(new TypeError('missing src'));
      if( typeof options === 'string' ) options = {target:options};
      if( typeof options === 'function' ) done = options, options = null;

      options = options || {};
      var controller = options.controller;
      var target = options.target || defaultTarget;
      var targetel = document.querySelector(target);
      if( controller && typeof controller !== 'string' ) return done(new TypeError('controller must be a string'));
      if( !targetel ) return done(new TypeError('undefined target:' + target));

      function render(els) {
        if( controller ) [].forEach.call(els, function(node) {
          if( isElement(node) && !node.hasAttribute('ng-controller') )
            node.setAttribute('ng-controller', controller);
        })

        res.pack(els, function(err) {
          if( err ) return done(err);

          targetel.innerHTML = '';
          [].forEach.call(els, function(node) {

            targetel.appendChild(node);
          });

          onrender && onrender(null, els);
          done(null, els);
        });
      }

      if( typeof src === 'string' ) ajax(path.join(base, src), function(err, html) {
        if( err ) return done(err), onload && onload(err);
        var els = evalhtml(html);
        onload && onload(null, els);
        render(els);
      });
      else if( isNode(src) ) render([src]);
      else if( isArrayLike(src) ) render(src);
      else return done(new TypeError('unknwon type of src: ' + src));
    };

    next();
    return this;
  };
};<|endoftext|>


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

import {join, relative, sep} from 'path'
import {getProjectDir} from '../../../paths'

const PROJECT_DIR = getProjectDir()

function fileName(file) {
  const RELATIVE = relative(PROJECT_DIR, file)
  let nodes = RELATIVE.split(sep)

  if (nodes[0] === 'src')
    nodes.shift()

  return nodes.join(sep)
}

export default function () {
  return {
    exclude: /\.(css|jsx?|mjs)$/,
    use: [{
      loader: 'file-loader',
      options: {
        name: fileName,
      },
    }],
  }
}
<commit_msg>Include hash on file name<commit_after>// Licensed under the Apache License, Version 2.0 (the “License”); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an “AS IS” BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import {join, relative, sep} from 'path'
import {getProjectDir} from '../../../paths'

const PROJECT_DIR = getProjectDir()

function fileName(file) {
  const RELATIVE = relative(PROJECT_DIR, file)
  let nodes = RELATIVE.split(sep)

  if (nodes[0] === 'src')
    nodes.shift()

  return `${nodes.join(sep)}?[sha512:hash:base64:8]`
}

export default function () {
  return {
    exclude: /\.(css|jsx?|mjs)$/,
    use: [{
      loader: 'file-loader',
      options: {
        name: fileName,
      },
    }],
  }
}
<|endoftext|>


<commit_before><commit_msg>Add evaluation checks<commit_after><|endoftext|>


<commit_before>require('../src');
require('./lib/init');

// make runtime available in core-level
Fire.Runtime = require('../src/runtime');

var PageLevel = false;
var CoreLevel = true;

describe('Editor.getNodeDump', function () {
    if (PageLevel && Fire.isEditorCore) {
        // only test in page-level
        var spawnRunner = require('./lib/spawn-runner');
        spawnRunner(this.title, __filename);
        if (!CoreLevel) {
            return;
        }
    }

    function test (object, expectedDump) {
        var dump = Editor.getNodeDump(object);
        expect(dump).to.deep.equal(expectedDump);
    }

    var node;

    before(function () {
        function Node () {}
        Node.prototype.getAge = function () {};

        var NodeWrapper = Fire.Class({
            name: 'MyNodeWrapper',
            extends: Fire.Runtime.NodeWrapper,
            properties: {
                id: {
                    get: function () {
                        return 554;
                    }
                },
                parentNode: {
                    get: function () {
                        return null;
                    }
                },
                childNodes: {
                    get: function () {
                        return [];
                    }
                },
                position: {
                    get: function () {
                        return Fire.v2(123, 456);
                    }
                },
                worldPosition: {
                    get: function () {
                        return Fire.Vec2.zero;
                    }
                },
                rotation: {
                    get: function () {
                        return 0;
                    }
                },
                worldRotation: {
                    get: function () {
                        return 0;
                    }
                },
                scale: {
                    get: function () {
                        return Fire.Vec2.one;
                    }
                },
                worldScale: {
                    get: function () {
                        return Fire.Vec2.one;
                    }
                }
            }
        });
        Fire.Runtime.registerNodeType(Node, NodeWrapper);

        node = new Node();

        var FilterMode = Fire.defineEnum({
            Point: -1,
            Bilinear: -1,
            Trilinear: -1
        });

        var Script = Fire.Class({
            name: '2154648724566',
            extends: Fire.Class({
                constructor: function () {
                    this.realAge = 30;
                },
                properties: {
                    age: {
                        default: 40,
                        tooltip: 'Age'
                    }
                },
                getAge: function () {
                    return this.age;
                }
            }),
            constructor: function () {
                this._name = 'ha';
            },
            properties: {
                name: {
                    get: function () {
                        return this._name;
                    },
                    displayName: 'Name'
                },
                wrapMode: {
                    default: FilterMode.Bilinear,
                    type: FilterMode
                },
                texture: {
                    default: null,
                    type: Fire.Texture
                }
            },
            getName: function () {
                return this.name;
            }
        });

        Fire.mixin(node, Script);
    });

    //describe('Smoke testing', function () {
    //    it('should pass if null', function () {
    //        test(null, {
    //            types: {},
    //            value: null
    //        });
    //    });
    //    it('should pass if empty', function () {
    //        test({}, {
    //            types: {},
    //            value: {}
    //        });
    //    });
    //});

    describe('dump result', function () {

        var dump;
        before(function () {
            // test wrong type
            node.texture = new Fire.Sprite();
            node.texture._uuid = '43728e743120';
            //
            dump = Editor.getNodeDump(node);
        });

        it('should contain types', function () {
            expect(dump.types).to.deep.equal({
                'MyNodeWrapper': {
                    properties: {
                        _name: {
                            visible: false
                        },
                        _objFlags: {
                            visible: false
                        },
                        childNodes: {
                            visible: false
                        },
                        id: {
                            "visible": false
                        },
                        name: {},
                        parentNode: {
                            visible: false
                        },
                        position: {},
                        rotation: {
                            tooltip: "The counterclockwise degrees of rotation relative to the parent"
                        },
                        scale: {},
                        scaleX: {
                            visible: false
                        },
                        scaleY: {
                            visible: false
                        },
                        worldPosition: {
                            visible: false
                        },
                        worldRotation: {
                            visible: false
                        },
                        worldScale: {
                            visible: false
                        },
                        worldX: {
                            visible: false
                        },
                        worldY: {
                            visible: false
                        },
                        x: {
                            visible: false
                        },
                        y: {
                            visible: false
                        },
                    }
                },
                '2154648724566': {
                    properties: {
                        age: {
                            default: 40,
                            tooltip: 'Age'
                        },
                        name: {
                            displayName: 'Name'
                        },
                        "wrapMode": {
                            "default": 1,
                            "type": "Enum",
                            "enumList": [
                                {
                                    "name": "Point",
                                    "value": 0
                                },
                                {
                                    "name": "Bilinear",
                                    "value": 1
                                },
                                {
                                    "name": "Trilinear",
                                    "value": 2
                                }
                            ]
                        },
                        texture: {
                            default: null,
                            type: 'Fire.Texture'
                        }
                    }
                }
            });
        });
        it('should contain value', function () {
            expect(dump.value).to.deep.equal({
                __type__: 'MyNodeWrapper',
                _name: '',
                name: '',
                _objFlags: 0,
                id: 554,
                childNodes: null,
                parentNode: null,
                position: {
                    __type__: 'Fire.Vec2',
                    x: 123,
                    y: 456
                },
                rotation: 0,
                scale: {
                    __type__: 'Fire.Vec2',
                    x: 1,
                    y: 1
                },
                scaleX: 1,
                scaleY: 1,
                worldPosition: {
                    __type__: 'Fire.Vec2',
                    x: 0,
                    y: 0
                },
                worldRotation: 0,
                worldScale: {
                    __type__: 'Fire.Vec2',
                    x: 1,
                    y: 1
                },
                worldX: 0,
                worldY: 0,
                x: 123,
                y: 456,

                __mixins__: [{
                    __type__: '2154648724566',
                    age: 40,
                    name: 'ha',
                    wrapMode: 1,
                    texture: {
                        __type__: 'Fire.Sprite',
                        uuid: node.texture._uuid
                    }
                }]
            });
        });
    });
});
<commit_msg>rename node to runtime (fireball-x/fireball/#68)<commit_after>require('../src');
require('./lib/init');

// make runtime available in core-level
Fire.Runtime = require('../src/runtime');

var PageLevel = false;
var CoreLevel = true;

describe('Editor.getNodeDump', function () {
    if (PageLevel && Fire.isEditorCore) {
        // only test in page-level
        var spawnRunner = require('./lib/spawn-runner');
        spawnRunner(this.title, __filename);
        if (!CoreLevel) {
            return;
        }
    }

    function test (object, expectedDump) {
        var dump = Editor.getNodeDump(object);
        expect(dump).to.deep.equal(expectedDump);
    }

    var node;

    before(function () {
        function Node () {}
        Node.prototype.getAge = function () {};

        var NodeWrapper = Fire.Class({
            name: 'MyNodeWrapper',
            extends: Fire.Runtime.NodeWrapper,
            properties: {
                id: {
                    get: function () {
                        return 554;
                    }
                },
                runtimeParent: {
                    get: function () {
                        return null;
                    }
                },
                runtimeChildren: {
                    get: function () {
                        return [];
                    }
                },
                position: {
                    get: function () {
                        return Fire.v2(123, 456);
                    }
                },
                worldPosition: {
                    get: function () {
                        return Fire.Vec2.zero;
                    }
                },
                rotation: {
                    get: function () {
                        return 0;
                    }
                },
                worldRotation: {
                    get: function () {
                        return 0;
                    }
                },
                scale: {
                    get: function () {
                        return Fire.Vec2.one;
                    }
                },
                worldScale: {
                    get: function () {
                        return Fire.Vec2.one;
                    }
                }
            }
        });
        Fire.Runtime.registerNodeType(Node, NodeWrapper);

        node = new Node();

        var FilterMode = Fire.defineEnum({
            Point: -1,
            Bilinear: -1,
            Trilinear: -1
        });

        var Script = Fire.Class({
            name: '2154648724566',
            extends: Fire.Class({
                constructor: function () {
                    this.realAge = 30;
                },
                properties: {
                    age: {
                        default: 40,
                        tooltip: 'Age'
                    }
                },
                getAge: function () {
                    return this.age;
                }
            }),
            constructor: function () {
                this._name = 'ha';
            },
            properties: {
                name: {
                    get: function () {
                        return this._name;
                    },
                    displayName: 'Name'
                },
                wrapMode: {
                    default: FilterMode.Bilinear,
                    type: FilterMode
                },
                texture: {
                    default: null,
                    type: Fire.Texture
                }
            },
            getName: function () {
                return this.name;
            }
        });

        Fire.mixin(node, Script);
    });

    //describe('Smoke testing', function () {
    //    it('should pass if null', function () {
    //        test(null, {
    //            types: {},
    //            value: null
    //        });
    //    });
    //    it('should pass if empty', function () {
    //        test({}, {
    //            types: {},
    //            value: {}
    //        });
    //    });
    //});

    describe('dump result', function () {

        var dump;
        before(function () {
            // test wrong type
            node.texture = new Fire.Sprite();
            node.texture._uuid = '43728e743120';
            //
            dump = Editor.getNodeDump(node);
        });

        it('should contain types', function () {
            expect(dump.types).to.deep.equal({
                'MyNodeWrapper': {
                    properties: {
                        _name: {
                            visible: false
                        },
                        _objFlags: {
                            visible: false
                        },
                        runtimeChildren: {
                            visible: false
                        },
                        id: {
                            "visible": false
                        },
                        name: {},
                        runtimeParent: {
                            visible: false
                        },
                        position: {},
                        rotation: {
                            tooltip: "The counterclockwise degrees of rotation relative to the parent"
                        },
                        scale: {},
                        scaleX: {
                            visible: false
                        },
                        scaleY: {
                            visible: false
                        },
                        worldPosition: {
                            visible: false
                        },
                        worldRotation: {
                            visible: false
                        },
                        worldScale: {
                            visible: false
                        },
                        worldX: {
                            visible: false
                        },
                        worldY: {
                            visible: false
                        },
                        x: {
                            visible: false
                        },
                        y: {
                            visible: false
                        },
                    }
                },
                '2154648724566': {
                    properties: {
                        age: {
                            default: 40,
                            tooltip: 'Age'
                        },
                        name: {
                            displayName: 'Name'
                        },
                        "wrapMode": {
                            "default": 1,
                            "type": "Enum",
                            "enumList": [
                                {
                                    "name": "Point",
                                    "value": 0
                                },
                                {
                                    "name": "Bilinear",
                                    "value": 1
                                },
                                {
                                    "name": "Trilinear",
                                    "value": 2
                                }
                            ]
                        },
                        texture: {
                            default: null,
                            type: 'Fire.Texture'
                        }
                    }
                }
            });
        });
        it('should contain value', function () {
            expect(dump.value).to.deep.equal({
                __type__: 'MyNodeWrapper',
                _name: '',
                name: '',
                _objFlags: 0,
                id: 554,
                runtimeChildren: null,
                runtimeParent: null,
                position: {
                    __type__: 'Fire.Vec2',
                    x: 123,
                    y: 456
                },
                rotation: 0,
                scale: {
                    __type__: 'Fire.Vec2',
                    x: 1,
                    y: 1
                },
                scaleX: 1,
                scaleY: 1,
                worldPosition: {
                    __type__: 'Fire.Vec2',
                    x: 0,
                    y: 0
                },
                worldRotation: 0,
                worldScale: {
                    __type__: 'Fire.Vec2',
                    x: 1,
                    y: 1
                },
                worldX: 0,
                worldY: 0,
                x: 123,
                y: 456,

                __mixins__: [{
                    __type__: '2154648724566',
                    age: 40,
                    name: 'ha',
                    wrapMode: 1,
                    texture: {
                        __type__: 'Fire.Sprite',
                        uuid: node.texture._uuid
                    }
                }]
            });
        });
    });
});
<|endoftext|>


<commit_before>const { inspect } = require('util');

require('../util/prototypes');
const ArgumentParser = require('./ArgumentParser');

class CommandController {
	constructor() {
		this.disabledCommands = require('../data/disabledCommands.json');
		this.tags = require('../data/tags.js');
		this.tagRegex = /\[([^[\]:]*)(?::?\s*(.*))\]/g;
	}

	async handleCommand(message) { // eslint-disable-line complexity
		if (message.author.id !== message.client.user.id) return;

		if (!message.content.startsWith(message.client.config.commandPrefix) && this.tagRegex.test(message.content)) {
			const tagCall = message.content.match(this.tagRegex)[0];
			// save original call to replace in message later
			const tag = tagCall.split(/:(?![^{]*[}])/).map(t => {
				// split by colon if not inside json
				t = t.trim();
				if (t[t.length - 1] === ']') t = t.replace(t[t.length - 1], '');
				if (t[0] === '[') t = t.replace(t[0], '');
				// filter out brackets from beginning and end
				if (this.tags[t] || t === 'eval') return t;
				// don't eval tag keywords or the eval keyword
				t = t.split(/,(?![^([{]*[\])}])/g).map(p => typeof p === 'string' ? p.trim() : null).map(tagValue => {
					// split by comma if not inside object, array, etc
					try {
						if (tagValue.match(/^["'`]\d*["'`]$/)) return tagValue = tagValue.replace(/["'`]/g, '');
						// don't evaluate if number enclosed by strings and remove extra quotes
						return eval(tagValue);
						// try evaluating to get references to existing objects like message or client
					}
					catch (e) {
						return tagValue;
						// return plain value if evaluating yielded no result (e.g. value is a non-quoted string)
					}
				});
				return t.length === 1 ? t[0] : t;
				// avoid nesting array too deep cause it's annoying
			});

			let tagged, evaled, tagError;

			try {
				if (tag[0] === 'eval' && tag[1]) {
					evaled = eval(tag[1]);
					// eval again to properly be able to return errors etc
				}
				else if (typeof this.tags[tag[0]] === 'function') {
					evaled = await this.tags[tag[0]](...tag[1] || '');
				}
				else {
					evaled = this.tags[tag[0]];
				}
			}
			catch (e) {
				if (this.tags.hasOwnProperty(tag[0]) || tag[0] === 'eval') {
					evaled = '[<Tag errored>]';
					message.client.logger.error(`Tag '${tag[0]}' errored!:\n${tagError || e}\nWere you trying to use more than 1 tag at once?`);
				} // only record error if the tag actually exists or is an eval tag
			}

			if (evaled) tagged = (tagged || message.content).replace(tagCall, evaled);

			return tagged !== message.content ? message.edit(tagged) : null;
		} // tags

		else if (!message.content.startsWith(message.client.config.commandPrefix)) { return; }
		// no tag + no prefix

		const { commands, aliases, config, logger } = message.client;

		const [name, ...args] = message.content.replace(config.commandPrefix, '').trim().split(/ +/g);
		const command = commands.get(name.toLowerCase()) || commands.get(aliases.get(name.toLowerCase()));

		if (!command) return;

		if (command.guildOnly && message.channel.type !== 'text') {
			return message.edit(`The ${command.name} command is only available on servers.`).then(msg => msg.delete(3000));
		}

		if (this.disabledCommands.includes(command.name)) return;

		if (command.args.length && args.length < command.args.length && !('defaultVal' in command.args.last())) {
			const correctSyntax = `${config.commandPrefix}${command.name} ${command.args.map(a => `<${a.name}>`).join(' ')}`;
			return message.edit(`you didn't provide enough arguments! The correct format would be:\n\`${correctSyntax}\``)
				.then(msg => msg.delete(3000));
		}

		const parsedArgs = command.args.length ? await this.parseArguments(args, command, message) : args;

		if (!parsedArgs) return;

		const userData = ['addquote', 'addquote-id', 'sendquote', 'delquote', 'listquotes'].includes(command.name)
			? { savedQuotes: require('../data/savedQuotes.json') }
			: ['emote', 'addfav', 'delfav', 'listfavs'].includes(command.name)
				? { favoriteEmotes: require('../data/favoriteEmotes.json') }
				: command.name === 'managetags'
					? { tags: this.tags }
					: null;

		return command.run(message, parsedArgs, userData).catch(e => {
			logger.error(inspect(e));
			return message.edit(`An error occurred while executing the \`${command.name}\` command.`).then(msg => msg.delete(3000));
		});
	}

	async parseArguments(args, command, message) {
		const parsedArgs = {};
		const beginning = args.slice(0, command.args.length - 1);
		const end = args.slice(beginning.length, args.length).join(' ');
		const entries = beginning.concat(end).entries();

		for (const [i, arg] of entries) {
			const { name, type, defaultVal } = command.args[i];
			if (!name) throw Error(`No argument name supplied at command: ${command.name}`);
			if (!type) throw Error(`No argument type supplied at command: ${command.name}`);

			parsedArgs[name] = 'defaultVal' in command.args[i] && !arg ? defaultVal : ArgumentParser.parse(type, message, arg);

			if (parsedArgs[name] instanceof Promise) {
				parsedArgs[name] = await parsedArgs[name];
			}

			if (parsedArgs[name] === null) {
				message.edit(`invalid input for the \`${name}\` argument! Expected \`${type}\`.`).then(msg => msg.delete(3000));
				return undefined;
			}
		}

		return parsedArgs;
	}
}

module.exports = CommandController;<commit_msg>Changes to tags, including always passing message to funcs & attach userData to this<commit_after>const { inspect } = require('util');

require('../util/prototypes');
const ArgumentParser = require('./ArgumentParser');

class CommandController {
	constructor() {
		this.disabledCommands = require('../data/disabledCommands.json');
		this.tags = require('../data/tags.js');
		this.tagRegex = /\[([^[\]:]*)(?::?\s*(.*))\]/g;
		this.userData = {
			savedQuotes: require('../data/savedQuotes.json'),
			favoriteEmotes: require('../data/favoriteEmotes.json'),
			tags: this.tags
		};
	}

	async handleCommand(message) { // eslint-disable-line complexity
		if (message.author.id !== message.client.user.id) return;

		if (!message.content.startsWith(message.client.config.commandPrefix) && this.tagRegex.test(message.content)) {
			const tagCall = message.content.match(this.tagRegex)[0];
			// save original call to replace in message later
			const tag = tagCall.split(/:(?![^{]*[}])/).map(t => {
				// split by colon if not inside json
				t = t.trim();
				if (t[t.length - 1] === ']') t = t.replace(t[t.length - 1], '');
				if (t[0] === '[') t = t.replace(t[0], '');
				// filter out brackets from beginning and end
				if (this.tags.hasOwnProperty(t) || t === 'eval') return t;
				// don't eval tag keywords or the eval keyword
				t = t.split(/,(?![^([{]*[\])}])/g).map(p => typeof p === 'string' ? p.trim() : null).map(tagValue => {
					// split by comma if not inside object, array, etc
					try {
						if (tagValue.match(/^["'`]\d*["'`]$/)) return tagValue = tagValue.replace(/["'`]/g, '');
						// don't evaluate if number enclosed by strings and remove extra quotes
						return eval(tagValue);
						// try evaluating to get references to existing objects like message or client
					}
					catch (e) {
						return tagValue;
						// return plain value if evaluating yielded no result (e.g. value is a non-quoted string)
					}
				});
				return t.length === 1 ? t[0] : t;
				// avoid nesting array too deep cause it's annoying
			});

			let tagged, evaled, tagError;

			try {
				if (tag[0] === 'eval' && tag[1]) {
					evaled = eval(tag[1]);
					// eval again to properly be able to return errors etc
				}
				else if (typeof this.tags[tag[0]] === 'function') {
					evaled = tag[1]
						? await this.tags[tag[0]](message, ...tag[1])
						: await this.tags[tag[0]](message);
				}
				else {
					evaled = this.tags[tag[0]];
				}
			}
			catch (e) {
				if (this.tags.hasOwnProperty(tag[0]) || tag[0] === 'eval') {
					evaled = '[<Tag errored>]';
					message.client.logger.error(`Tag '${tag[0]}' errored!:\n${tagError || e}\nWere you trying to use more than 1 tag at once?`);
				} // only record error if the tag actually exists or is an eval tag
			}

			if (evaled) tagged = (tagged || message.content).replace(tagCall, evaled);

			return tagged !== message.content ? message.edit(tagged) : null;
		} // tags

		else if (!message.content.startsWith(message.client.config.commandPrefix)) { return; }
		// no tag + no prefix

		const { commands, aliases, config, logger } = message.client;

		const [name, ...args] = message.content.replace(config.commandPrefix, '').trim().split(/ +/g);
		const command = commands.get(name.toLowerCase()) || commands.get(aliases.get(name.toLowerCase()));

		if (!command) return;

		if (command.guildOnly && message.channel.type !== 'text') {
			return message.edit(`The ${command.name} command is only available on servers.`).then(msg => msg.delete(3000));
		}

		if (this.disabledCommands.includes(command.name)) return;

		if (command.args.length && args.length < command.args.length && !('defaultVal' in command.args.last())) {
			const correctSyntax = `${config.commandPrefix}${command.name} ${command.args.map(a => `<${a.name}>`).join(' ')}`;
			return message.edit(`you didn't provide enough arguments! The correct format would be:\n\`${correctSyntax}\``)
				.then(msg => msg.delete(3000));
		}

		const parsedArgs = command.args.length ? await this.parseArguments(args, command, message) : args;

		if (!parsedArgs) return;

		return command.run(message, parsedArgs, this.userData).catch(e => {
			logger.error(inspect(e));
			return message.edit(`An error occurred while executing the \`${command.name}\` command.`).then(msg => msg.delete(3000));
		});
	}

	async parseArguments(args, command, message) {
		const parsedArgs = {};
		const beginning = args.slice(0, command.args.length - 1);
		const end = args.slice(beginning.length, args.length).join(' ');
		const entries = beginning.concat(end).entries();

		for (const [i, arg] of entries) {
			const { name, type, defaultVal } = command.args[i];
			if (!name) throw Error(`No argument name supplied at command: ${command.name}`);
			if (!type) throw Error(`No argument type supplied at command: ${command.name}`);

			parsedArgs[name] = 'defaultVal' in command.args[i] && !arg ? defaultVal : ArgumentParser.parse(type, message, arg);

			if (parsedArgs[name] instanceof Promise) {
				parsedArgs[name] = await parsedArgs[name];
			}

			if (parsedArgs[name] === null) {
				message.edit(`invalid input for the \`${name}\` argument! Expected \`${type}\`.`).then(msg => msg.delete(3000));
				return undefined;
			}
		}

		return parsedArgs;
	}
}

module.exports = CommandController;<|endoftext|>


<commit_before>/**
 * Node class.
 *
 * @copyright   copyright (c) 2015 by Harald Lapp
 * @author      Harald Lapp <harald@octris.org>
 */

define(function(require) {
    var connector = require('./connector');

    var id = 0;

    /**
     * Constructor.
     *
     * @param   diagram         diagram             Diagram instance.
     * @param   object          data                Node configuration.
     */
    function node(dia, data)
    {
        this.diagram = dia;

        this.data = $.extend({}, data);
        this.node = null;

        this.registry = [];

        if (!('id' in this.data)) {
            this.data.id = 'node-' + (++id);
        }

        // register input connectors
        this.node_input.forEach(function(data, idx) {
            var cn = new connector('input', this, data);

            this.registry.push(this.diagram.wire.registerConnector(cn));
        }, this);

        // register output connectors
        this.node_output.forEach(function(data, idx) {
            var cn = new connector('output', this, data);

            this.registry.push(this.diagram.wire.registerConnector(cn));
        }, this);
    }

    /**
     * Input connectors.
     *
     * @type    array
     */
    node.prototype.node_input = [];

    /**
     * Output connectors.
     *
     * @type    array
     */
    node.prototype.node_output = [];

    /**
     * Width.
     *
     * @type    int
     */
    node.prototype.node_width = 250;

    /**
     * Default node height.
     *
     * @type    int
     */
    node.prototype.node_height = 40;

    /**
     * Line height for title and connectors in node.
     *
     * @type    int
     */
    node.prototype.node_line_height = 15;

    /**
     * Default node color.
     *
     * @type    string
     */
    node.prototype.node_color = '#000055';

    /**
     * Default node opacity.
     *
     * @type    string
     */
    node.prototype.node_opacity = 0.75;

    /**
     * Default connector radius.
     *
     * @type    int
     */
    node.prototype.connector_radius = 5;

    /**
     * Destroy node.
     */
    node.prototype.destroy = function()
    {
        this.registry = this.registry.filter(function(id) {
            this.diagram.wire.unregisterConnector(id);

            return false;
        }, this);

        this.node.remove();
    }

    /**
     * Return ID of node.
     *
     * @return  string                              ID of node.
     */
    node.prototype.getId = function()
    {
        return this.data.id;
    }

    /**
     * Return node data.
     *
     * @return  object                              Node data.
     */
    node.prototype.getData = function()
    {
        return $.extend({}, this.data);
    }

    /**
     * Return rectangle of node (x, y, width, height).
     *
     * @return  object                              Rectangle.
     */
    node.prototype.getRect = function()
    {
        var cn = Math.max(this.node_input.length, this.node_output.length);

        return {
            'x':      (isNaN(this.data.x) ? null : this.data.x),
            'y':      (isNaN(this.data.y) ? null : this.data.y),
            'width':  this.node_width,
            'height': this.node_height + cn * this.node_line_height
        };
    }

    /**
     * Render node.
     */
    node.prototype.render = function(pos)
    {
        // render node
        var layer = this.diagram.getLayer('nodes');

        var cn = Math.max(this.node_input.length, this.node_output.length);
        var me = this;
        var drag = false;
        var rect;

        var pos = {
            x: this.data.x,
            y: this.data.y
        };

        this.node = new paper.Group();
        this.node.onMouseDown = function(event) {
            if ((drag = !event.event.shiftKey)) {
                this.bringToFront();
            }
        }
        this.node.onMouseDrag = function(event) {
            if (drag) {
                pos.x += event.delta.x;
                pos.y += event.delta.y;

                if (me.diagram.options.raster > 0) {
                    var x = Math.round(pos.x / me.diagram.options.raster) * me.diagram.options.raster;
                    var y = Math.round(pos.y / me.diagram.options.raster) * me.diagram.options.raster;

                    this.translate(x - me.data.x, y - me.data.y);

                    me.data.x = x;
                    me.data.y = y;
                } else {
                    this.translate(event.delta.x, event.delta.y);

                    me.data.x = pos.x;
                    me.data.y = pos.y;
                }

                me.diagram.wire.redrawWires(me.registry);
            }
        }

        rect = new paper.Path.Rectangle({
            point: [0, 0],
            size: [this.node_width, this.node_height + cn * this.node_line_height],
            radius: 5,
            strokeColor: 'black',
            fillColor: this.node_color,
            opacity: this.node_opacity
        });

        this.node.addChild(rect);

        rect.onClick = function(event) {
            me.onClick(event);
        }
        rect.onDoubleClick = function(event) {
            me.onDblClick(event);
        }

        var text = new paper.PointText({
            point: [5, 15],
            content: this.data.label,
            fillColor: 'white',
            fontFamily: 'Verdana, Arial, Helvetica, Sans-Serif',
            fontSize: 12
        });

        this.node.addChild(text);

        var bclose = new paper.PointText({
            point: [this.node_width - 5, 15],
            content: '\u00D7',
            fillColor: 'white',
            fontFamily: 'Verdana, Arial, Helvetica, Sans-Serif',
            fontSize: 12,
            justification: 'right',
            opacity: 0.5
        });

        this.node.addChild(bclose);

        bclose.onMouseEnter = function() {
            this.set({opacity: 1});
        }
        bclose.onMouseLeave = function() {
            this.set({opacity: 0.5});
        }
        bclose.onClick = function() {
            me.diagram.removeNode(me.data.id);
        }

        // render connectors
        var idx = {'input': 0, 'output': 0};

        this.registry.forEach(function(id) {
            var cn = this.diagram.wire.getConnector(id);

            if (cn.getType() == 'input') {
                cn.render(this.node, 10, this.node_height + idx.input * this.node_line_height);
                ++idx.input;
            } else {
                cn.render(this.node, this.node_width - 10, this.node_height + idx.output * this.node_line_height);
                ++idx.output;
            }
        }, this);

        this.node.translate(this.data.x, this.data.y);
    }

    /*
     * Event handlers to be overwritten by child classes.
     */
    node.prototype.onClick = function(d) {
    }
    node.prototype.onDblClick = function(d) {
    }

    return node;
});
<commit_msg>show pointer if mouse cursor is over the "close" button<commit_after>/**
 * Node class.
 *
 * @copyright   copyright (c) 2015 by Harald Lapp
 * @author      Harald Lapp <harald@octris.org>
 */

define(function(require) {
    var connector = require('./connector');

    var id = 0;

    /**
     * Constructor.
     *
     * @param   diagram         diagram             Diagram instance.
     * @param   object          data                Node configuration.
     */
    function node(dia, data)
    {
        this.diagram = dia;

        this.data = $.extend({}, data);
        this.node = null;

        this.registry = [];

        if (!('id' in this.data)) {
            this.data.id = 'node-' + (++id);
        }

        // register input connectors
        this.node_input.forEach(function(data, idx) {
            var cn = new connector('input', this, data);

            this.registry.push(this.diagram.wire.registerConnector(cn));
        }, this);

        // register output connectors
        this.node_output.forEach(function(data, idx) {
            var cn = new connector('output', this, data);

            this.registry.push(this.diagram.wire.registerConnector(cn));
        }, this);
    }

    /**
     * Input connectors.
     *
     * @type    array
     */
    node.prototype.node_input = [];

    /**
     * Output connectors.
     *
     * @type    array
     */
    node.prototype.node_output = [];

    /**
     * Width.
     *
     * @type    int
     */
    node.prototype.node_width = 250;

    /**
     * Default node height.
     *
     * @type    int
     */
    node.prototype.node_height = 40;

    /**
     * Line height for title and connectors in node.
     *
     * @type    int
     */
    node.prototype.node_line_height = 15;

    /**
     * Default node color.
     *
     * @type    string
     */
    node.prototype.node_color = '#000055';

    /**
     * Default node opacity.
     *
     * @type    string
     */
    node.prototype.node_opacity = 0.75;

    /**
     * Default connector radius.
     *
     * @type    int
     */
    node.prototype.connector_radius = 5;

    /**
     * Destroy node.
     */
    node.prototype.destroy = function()
    {
        this.registry = this.registry.filter(function(id) {
            this.diagram.wire.unregisterConnector(id);

            return false;
        }, this);

        this.node.remove();
    }

    /**
     * Return ID of node.
     *
     * @return  string                              ID of node.
     */
    node.prototype.getId = function()
    {
        return this.data.id;
    }

    /**
     * Return node data.
     *
     * @return  object                              Node data.
     */
    node.prototype.getData = function()
    {
        return $.extend({}, this.data);
    }

    /**
     * Return rectangle of node (x, y, width, height).
     *
     * @return  object                              Rectangle.
     */
    node.prototype.getRect = function()
    {
        var cn = Math.max(this.node_input.length, this.node_output.length);

        return {
            'x':      (isNaN(this.data.x) ? null : this.data.x),
            'y':      (isNaN(this.data.y) ? null : this.data.y),
            'width':  this.node_width,
            'height': this.node_height + cn * this.node_line_height
        };
    }

    /**
     * Render node.
     */
    node.prototype.render = function(pos)
    {
        // render node
        var layer = this.diagram.getLayer('nodes');

        var cn = Math.max(this.node_input.length, this.node_output.length);
        var me = this;
        var drag = false;
        var rect;

        var pos = {
            x: this.data.x,
            y: this.data.y
        };

        this.node = new paper.Group();
        this.node.onMouseDown = function(event) {
            if ((drag = !event.event.shiftKey)) {
                this.bringToFront();
            }
        }
        this.node.onMouseDrag = function(event) {
            if (drag) {
                pos.x += event.delta.x;
                pos.y += event.delta.y;

                if (me.diagram.options.raster > 0) {
                    var x = Math.round(pos.x / me.diagram.options.raster) * me.diagram.options.raster;
                    var y = Math.round(pos.y / me.diagram.options.raster) * me.diagram.options.raster;

                    this.translate(x - me.data.x, y - me.data.y);

                    me.data.x = x;
                    me.data.y = y;
                } else {
                    this.translate(event.delta.x, event.delta.y);

                    me.data.x = pos.x;
                    me.data.y = pos.y;
                }

                me.diagram.wire.redrawWires(me.registry);
            }
        }

        rect = new paper.Path.Rectangle({
            point: [0, 0],
            size: [this.node_width, this.node_height + cn * this.node_line_height],
            radius: 5,
            strokeColor: 'black',
            fillColor: this.node_color,
            opacity: this.node_opacity
        });

        this.node.addChild(rect);

        rect.onClick = function(event) {
            me.onClick(event);
        }
        rect.onDoubleClick = function(event) {
            me.onDblClick(event);
        }

        var text = new paper.PointText({
            point: [5, 15],
            content: this.data.label,
            fillColor: 'white',
            fontFamily: 'Verdana, Arial, Helvetica, Sans-Serif',
            fontSize: 12
        });

        this.node.addChild(text);

        var bclose = new paper.PointText({
            point: [this.node_width - 5, 15],
            content: '\u00D7',
            fillColor: 'white',
            fontFamily: 'Verdana, Arial, Helvetica, Sans-Serif',
            fontSize: 12,
            justification: 'right',
            opacity: 0.5
        });

        this.node.addChild(bclose);

        bclose.onMouseEnter = function() {
            this.set({opacity: 1});
            document.body.style.cursor = 'pointer';
        }
        bclose.onMouseLeave = function() {
            this.set({opacity: 0.5});
            document.body.style.cursor = 'default';
        }
        bclose.onClick = function() {
            me.diagram.removeNode(me.data.id);
        }

        // render connectors
        var idx = {'input': 0, 'output': 0};

        this.registry.forEach(function(id) {
            var cn = this.diagram.wire.getConnector(id);

            if (cn.getType() == 'input') {
                cn.render(this.node, 10, this.node_height + idx.input * this.node_line_height);
                ++idx.input;
            } else {
                cn.render(this.node, this.node_width - 10, this.node_height + idx.output * this.node_line_height);
                ++idx.output;
            }
        }, this);

        this.node.translate(this.data.x, this.data.y);
    }

    /*
     * Event handlers to be overwritten by child classes.
     */
    node.prototype.onClick = function(d) {
    }
    node.prototype.onDblClick = function(d) {
    }

    return node;
});
<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var zlib = require('zlib');

var mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick;

var decompress = function(output, encoding, cb) {
    if(encoding === 'gzip') {
        zlib.gunzip(output, cb);
    } else if(encoding === 'deflate') {
        zlib.inflate(output, function(err, out) {
            if(err) {
                return zlib.inflateRaw(output, cb);
            }
            cb(null, out);
        });
    } else if(encoding === 'identity') {
        process.nextTick(function() {
            cb(null, output);
        });
    } else {
        process.nextTick(function() {
            cb(new Error('unsupported encoding ' + encoding));
        });
    }
};

// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
var forbiddenInputHeaders = ['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];
var validateInputHeaders = function(headers) {
    for(var header in headers) {
        if(headers.hasOwnProperty(header)) {
            var headerl = header.toLowerCase();
            if(forbiddenInputHeaders.indexOf(headerl) >= 0) {
                throw new Error('Input header ' + header + ' is forbidden to be set programmatically');
            }
            if(headerl.substr(0, 'proxy-'.length) === 'proxy-') {
                throw new Error('Input header ' + header + ' (to be precise, all Proxy-*) is forbidden to be set programmatically');
            }
            if(headerl.substr(0, 'sec-'.length) === 'sec-') {
                throw new Error('Input header ' + header + ' (to be precise, all Sec-*) is forbidden to be set programmatically');
            }
        }
    }
};

var copy = function(from, to) {
    Object.keys(from).forEach(function(key) {
        to[key] = from[key];
    });
    return to;
};

var httpinvoke = function(uri, method, options, cb) {
    var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
    /*************** initialize helper variables **************/
    try {
        validateInputHeaders(inputHeaders);
    } catch(err) {
        return failWithoutRequest(cb, err);
    }
    inputHeaders = copy(inputHeaders, {});
    inputHeaders['Accept-Encoding'] = 'gzip, deflate, identity';

    var ignorantlyConsume = function(res) {
        res.on('data', pass);
        res.on('end', pass);
    };
    uri = url.parse(uri);
    var req = http.request({
        hostname: uri.hostname,
        port: Number(uri.port),
        path: uri.path,
        method: method,
        headers: inputHeaders
    }, function(res) {
        var contentEncoding;
        if(!cb) {
            return ignorantlyConsume(res);
        }

        outputHeaders = res.headers;
        if('content-encoding' in outputHeaders) {
            contentEncoding = outputHeaders['content-encoding'];
            delete outputHeaders['content-encoding'];
        } else {
            contentEncoding = 'identity';
        }

        status = res.statusCode;

        uploadProgressCb(inputLength, inputLength);
        if(!cb) {
            return ignorantlyConsume(res);
        }

        statusCb(status, outputHeaders);
        if(!cb) {
            return ignorantlyConsume(res);
        }

        if('content-length' in outputHeaders) {
            outputLength = Number(outputHeaders['content-length']);
        }

        downloadProgressCb(0, outputLength);
        if(!cb) {
            return ignorantlyConsume(res);
        }
        if(method === 'HEAD') {
            ignorantlyConsume(res);
            downloadProgressCb(0, 0);
            return cb && cb(null, _undefined, status, outputHeaders);
        }

        var output = [], downloaded = 0;
        res.on('data', function(chunk) {
            if(!cb) {
                return;
            }
            downloaded += chunk.length;
            output.push(chunk);
            downloadProgressCb(downloaded, outputLength);
        });
        res.on('end', function() {
            if(!cb) {
                return;
            }

            if(typeof outputLength === 'undefined') {
                outputLength = downloaded;
            }

            if(downloaded !== outputLength) {
                return cb(new Error('network error'));
            }

            downloadProgressCb(outputLength, outputLength);
            if(!cb) {
                return;
            }

            if(outputLength === 0 && typeof outputHeaders['content-type'] === 'undefined') {
                return cb(null, _undefined, status, outputHeaders);
            }

            decompress(Buffer.concat(output, downloaded), contentEncoding, function(err, output) {
                if(!cb) {
                    return;
                }
                if(err) {
                    return cb(new Error('network error'));
                }
                if(!outputBinary) {
                    output = output.toString('utf8');
                }
                try {
                    cb(null, outputConverter(output), status, outputHeaders);
                } catch(err) {
                    cb(err);
                }
            });
        });
    });

    nextTick(function() {
        cb && uploadProgressCb(0, inputLength);
    });
    if(typeof input !== 'undefined') {
        input = new Buffer(input);
        inputLength = input.length;
        req.write(input);
    }
    req.on('error', function(e) {
        cb && cb(new Error('network error'));
    });
    req.end();
    promise = function() {
        cb && cb(new Error('abort'));
    };
    return mixInPromise(promise);
};
httpinvoke.corsResponseContentTypeOnly = false;
httpinvoke.corsRequestHeaders = true;
httpinvoke.corsCredentials = true;
httpinvoke.cors = true;
httpinvoke.corsDELETE = true;
httpinvoke.corsHEAD = true;
httpinvoke.corsPATCH = true;
httpinvoke.corsPUT = true;
httpinvoke.corsStatus = true;
httpinvoke.corsResponseTextOnly = false;
httpinvoke.requestTextOnly = false;
httpinvoke.PATCH = true;
httpinvoke.corsFineGrainedTimeouts = true;

module.exports = httpinvoke;
<commit_msg>node.js: set inputLength to zero when no input is sent<commit_after>var http = require('http');
var url = require('url');
var zlib = require('zlib');

var mixInPromise, pass, isArray, isArrayBufferView, _undefined, nextTick;

var decompress = function(output, encoding, cb) {
    if(encoding === 'gzip') {
        zlib.gunzip(output, cb);
    } else if(encoding === 'deflate') {
        zlib.inflate(output, function(err, out) {
            if(err) {
                return zlib.inflateRaw(output, cb);
            }
            cb(null, out);
        });
    } else if(encoding === 'identity') {
        process.nextTick(function() {
            cb(null, output);
        });
    } else {
        process.nextTick(function() {
            cb(new Error('unsupported encoding ' + encoding));
        });
    }
};

// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
var forbiddenInputHeaders = ['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'content-transfer-encoding', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];
var validateInputHeaders = function(headers) {
    for(var header in headers) {
        if(headers.hasOwnProperty(header)) {
            var headerl = header.toLowerCase();
            if(forbiddenInputHeaders.indexOf(headerl) >= 0) {
                throw new Error('Input header ' + header + ' is forbidden to be set programmatically');
            }
            if(headerl.substr(0, 'proxy-'.length) === 'proxy-') {
                throw new Error('Input header ' + header + ' (to be precise, all Proxy-*) is forbidden to be set programmatically');
            }
            if(headerl.substr(0, 'sec-'.length) === 'sec-') {
                throw new Error('Input header ' + header + ' (to be precise, all Sec-*) is forbidden to be set programmatically');
            }
        }
    }
};

var copy = function(from, to) {
    Object.keys(from).forEach(function(key) {
        to[key] = from[key];
    });
    return to;
};

var httpinvoke = function(uri, method, options, cb) {
    var promise, failWithoutRequest, uploadProgressCb, downloadProgressCb, inputLength, inputHeaders, statusCb, outputHeaders, exposedHeaders, status, outputBinary, input, outputLength, outputConverter;
    /*************** initialize helper variables **************/
    try {
        validateInputHeaders(inputHeaders);
    } catch(err) {
        return failWithoutRequest(cb, err);
    }
    inputHeaders = copy(inputHeaders, {});
    inputHeaders['Accept-Encoding'] = 'gzip, deflate, identity';

    var ignorantlyConsume = function(res) {
        res.on('data', pass);
        res.on('end', pass);
    };
    uri = url.parse(uri);
    var req = http.request({
        hostname: uri.hostname,
        port: Number(uri.port),
        path: uri.path,
        method: method,
        headers: inputHeaders
    }, function(res) {
        var contentEncoding;
        if(!cb) {
            return ignorantlyConsume(res);
        }

        outputHeaders = res.headers;
        if('content-encoding' in outputHeaders) {
            contentEncoding = outputHeaders['content-encoding'];
            delete outputHeaders['content-encoding'];
        } else {
            contentEncoding = 'identity';
        }

        status = res.statusCode;

        uploadProgressCb(inputLength, inputLength);
        if(!cb) {
            return ignorantlyConsume(res);
        }

        statusCb(status, outputHeaders);
        if(!cb) {
            return ignorantlyConsume(res);
        }

        if('content-length' in outputHeaders) {
            outputLength = Number(outputHeaders['content-length']);
        }

        downloadProgressCb(0, outputLength);
        if(!cb) {
            return ignorantlyConsume(res);
        }
        if(method === 'HEAD') {
            ignorantlyConsume(res);
            downloadProgressCb(0, 0);
            return cb && cb(null, _undefined, status, outputHeaders);
        }

        var output = [], downloaded = 0;
        res.on('data', function(chunk) {
            if(!cb) {
                return;
            }
            downloaded += chunk.length;
            output.push(chunk);
            downloadProgressCb(downloaded, outputLength);
        });
        res.on('end', function() {
            if(!cb) {
                return;
            }

            if(typeof outputLength === 'undefined') {
                outputLength = downloaded;
            }

            if(downloaded !== outputLength) {
                return cb(new Error('network error'));
            }

            downloadProgressCb(outputLength, outputLength);
            if(!cb) {
                return;
            }

            if(outputLength === 0 && typeof outputHeaders['content-type'] === 'undefined') {
                return cb(null, _undefined, status, outputHeaders);
            }

            decompress(Buffer.concat(output, downloaded), contentEncoding, function(err, output) {
                if(!cb) {
                    return;
                }
                if(err) {
                    return cb(new Error('network error'));
                }
                if(!outputBinary) {
                    output = output.toString('utf8');
                }
                try {
                    cb(null, outputConverter(output), status, outputHeaders);
                } catch(err) {
                    cb(err);
                }
            });
        });
    });

    nextTick(function() {
        cb && uploadProgressCb(0, inputLength);
    });
    if(typeof input !== 'undefined') {
        input = new Buffer(input);
        inputLength = input.length;
        req.write(input);
    } else {
        inputLength = 0;
    }
    req.on('error', function(e) {
        cb && cb(new Error('network error'));
    });
    req.end();
    promise = function() {
        cb && cb(new Error('abort'));
    };
    return mixInPromise(promise);
};
httpinvoke.corsResponseContentTypeOnly = false;
httpinvoke.corsRequestHeaders = true;
httpinvoke.corsCredentials = true;
httpinvoke.cors = true;
httpinvoke.corsDELETE = true;
httpinvoke.corsHEAD = true;
httpinvoke.corsPATCH = true;
httpinvoke.corsPUT = true;
httpinvoke.corsStatus = true;
httpinvoke.corsResponseTextOnly = false;
httpinvoke.requestTextOnly = false;
httpinvoke.PATCH = true;
httpinvoke.corsFineGrainedTimeouts = true;

module.exports = httpinvoke;
<|endoftext|>


<commit_before>controller = new BasicController({
  supports: {
    playpause: true,
    next: true,
    previous: true
  },
  useLazyObserving: true,
  frameSelector: '#main',
  playStateSelector: '#play',
  playStateClass: 'playing',
  playPauseSelector: '#play',
  nextSelector: '#next',
  previousSelector: '#previous',
  titleSelector: '.caption .track',
  artistSelector: '.caption .artist'
});

controller.override('getAlbumArt', function() {
  return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1);
});
<commit_msg>Try supporting both versions of spotify<commit_after>controller = new BasicController({
  supports: {
    playpause: true,
    next: true,
    previous: true
  },
  useLazyObserving: true,
  frameSelector: '#main, #app-player',
  playStateSelector: '#play, #play-pause',
  playStateClass: 'playing',
  playPauseSelector: '#play, #play-pause',
  nextSelector: '#next',
  previousSelector: '#previous',
  titleSelector: '.caption .track, #track-name',
  artistSelector: '.caption .artist, #track-artist'
});

controller.override('getAlbumArt', function() {
  return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image, #cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
});
<|endoftext|>


<commit_before>var NODE_TYPE_FILE = require('./constants.js').NODE_TYPE_FILE;
var NODE_TYPE_DIRECTORY = require('./constants.js').NODE_TYPE_DIRECTORY;
var NODE_TYPE_SYMBOLIC_LINK = require('./constants.js').NODE_TYPE_SYMBOLIC_LINK;
var NODE_TYPE_META = require('./constants.js').NODE_TYPE_META;

var ROOT_DIRECTORY_NAME = require('./constants.js').ROOT_DIRECTORY_NAME;

var S_IFREG = require('./constants.js').S_IFREG;
var S_IFDIR = require('./constants.js').S_IFDIR;
var S_IFLNK = require('./constants.js').S_IFLNK;

var DEFAULT_FILE_PERMISSIONS = require('./constants.js').DEFAULT_FILE_PERMISSIONS;
var DEFAULT_DIR_PERMISSIONS = require('./constants.js').DEFAULT_DIR_PERMISSIONS;

function getMode(type, mode) {
  switch(type) {
  case NODE_TYPE_DIRECTORY:
    return (mode || DEFAULT_DIR_PERMISSIONS) | S_IFDIR;
  case NODE_TYPE_SYMBOLIC_LINK:
    return (mode || DEFAULT_FILE_PERMISSIONS) | S_IFLNK;
    /* jshint -W086 */
  case NODE_TYPE_FILE:
    // falls through
  default:
    return (mode || DEFAULT_FILE_PERMISSIONS) | S_IFREG;
  }
}

function Node(options) {
  var now = Date.now();

  this.id = options.id;
  this.type = options.type || NODE_TYPE_FILE;  // node type (file, directory, etc)
  this.size = options.size || 0; // size (bytes for files, entries for directories)
  this.atime = options.atime || now; // access time (will mirror ctime after creation)
  this.ctime = options.ctime || now; // creation/change time
  this.mtime = options.mtime || now; // modified time
  this.flags = options.flags || []; // file flags
  this.xattrs = options.xattrs || {}; // extended attributes
  this.nlinks = options.nlinks || 0; // links count
  this.data = options.data; // id for data object
  this.version = options.version || 1;

  // permissions and flags
  this.mode = options.mode || (getMode(this.type));
  this.uid = options.uid || 0x0; // owner name
  this.gid = options.gid || 0x0; // group name
}

// Make sure the options object has an id on property,
// either from caller or one we generate using supplied guid fn.
function ensureID(options, prop, callback) {
  if(options[prop]) {
    callback(null);
  } else {
    options.guid(function(err, id) {
      options[prop] = id;
      callback(err);
    });
  }
}

Node.create = function(options, callback) {
  // We expect both options.id and options.data to be provided/generated.
  ensureID(options, 'id', function(err) {
    if(err) {
      callback(err);
      return;
    }

    ensureID(options, 'data', function(err) {
      if(err) {
        callback(err);
        return;
      }

      callback(null, new Node(options));
    });
  });
};

// Update the node's mode (permissions), taking file type bits into account.
Node.setMode = function(mode, node) {
  node.mode = getMode(node.type, mode);
};

module.exports = Node;
<commit_msg>Fix lint issues in node.js<commit_after>var NODE_TYPE_FILE = require('./constants.js').NODE_TYPE_FILE;
var NODE_TYPE_DIRECTORY = require('./constants.js').NODE_TYPE_DIRECTORY;
var NODE_TYPE_SYMBOLIC_LINK = require('./constants.js').NODE_TYPE_SYMBOLIC_LINK;

var S_IFREG = require('./constants.js').S_IFREG;
var S_IFDIR = require('./constants.js').S_IFDIR;
var S_IFLNK = require('./constants.js').S_IFLNK;

var DEFAULT_FILE_PERMISSIONS = require('./constants.js').DEFAULT_FILE_PERMISSIONS;
var DEFAULT_DIR_PERMISSIONS = require('./constants.js').DEFAULT_DIR_PERMISSIONS;

function getMode(type, mode) {
  switch(type) {
  case NODE_TYPE_DIRECTORY:
    return (mode || DEFAULT_DIR_PERMISSIONS) | S_IFDIR;
  case NODE_TYPE_SYMBOLIC_LINK:
    return (mode || DEFAULT_FILE_PERMISSIONS) | S_IFLNK;
    /* jshint -W086 */
  case NODE_TYPE_FILE:
    // falls through
  default:
    return (mode || DEFAULT_FILE_PERMISSIONS) | S_IFREG;
  }
}

function Node(options) {
  var now = Date.now();

  this.id = options.id;
  this.type = options.type || NODE_TYPE_FILE;  // node type (file, directory, etc)
  this.size = options.size || 0; // size (bytes for files, entries for directories)
  this.atime = options.atime || now; // access time (will mirror ctime after creation)
  this.ctime = options.ctime || now; // creation/change time
  this.mtime = options.mtime || now; // modified time
  this.flags = options.flags || []; // file flags
  this.xattrs = options.xattrs || {}; // extended attributes
  this.nlinks = options.nlinks || 0; // links count
  this.data = options.data; // id for data object
  this.version = options.version || 1;

  // permissions and flags
  this.mode = options.mode || (getMode(this.type));
  this.uid = options.uid || 0x0; // owner name
  this.gid = options.gid || 0x0; // group name
}

// Make sure the options object has an id on property,
// either from caller or one we generate using supplied guid fn.
function ensureID(options, prop, callback) {
  if(options[prop]) {
    callback(null);
  } else {
    options.guid(function(err, id) {
      options[prop] = id;
      callback(err);
    });
  }
}

Node.create = function(options, callback) {
  // We expect both options.id and options.data to be provided/generated.
  ensureID(options, 'id', function(err) {
    if(err) {
      callback(err);
      return;
    }

    ensureID(options, 'data', function(err) {
      if(err) {
        callback(err);
        return;
      }

      callback(null, new Node(options));
    });
  });
};

// Update the node's mode (permissions), taking file type bits into account.
Node.setMode = function(mode, node) {
  node.mode = getMode(node.type, mode);
};

module.exports = Node;
<|endoftext|>


<commit_before>exports.newGame = function (req, res) {
    // console.log(req.params.level);
    res.setHeader('Content-Type', 'application/json');
    var arrayOfObjects = [{ "q": "1 + 0", "a": "1" },
    { "q": "1 + 0", "a": "1" },
    { "q": "1 + 1", "a": "2" },
    { "q": "1 + 2", "a": "3" },
    { "q": "1 + 3", "a": "4" },
    { "q": "1 + 4", "a": "5" },
    { "q": "1 + 5", "a": "6" },
    { "q": "1 + 6", "a": "7" },
    { "q": "1 + 7", "a": "8" },
    { "q": "1 + 8", "a": "9" },
    { "q": "1 + 9", "a": "10" },
    { "q": "1 + 10", "a": "11" }];

    res.send(JSON.stringify(arrayOfObjects, null, 3));
    // switch (req.params.level) {
    //     case 1:
    // // res.send(JSON.stringify([{
    // //     "q": "1 + 0",
    // //     "a": "1"
    // // },
    // // {
    // //     "q": "1 + 1",
    // //     "a": "2"
    // // }, null, 2  ));

    //         ]));
    // };
    // res.send(`New add game level:  ${req.params.level}`);
};<commit_msg>update service<commit_after>exports.newGame = function (req, res) {
    // console.log(req.params.level);
    res.setHeader('Content-Type', 'application/json');
    // var arrayOfObjects = [{ "q": "1 + 0", "a": "1" },
    // { "q": "1 + 0", "a": "1" },
    // { "q": "1 + 1", "a": "2" },
    // { "q": "1 + 2", "a": "3" },
    // { "q": "1 + 3", "a": "4" },
    // { "q": "1 + 4", "a": "5" },
    // { "q": "1 + 5", "a": "6" },
    // { "q": "1 + 6", "a": "7" },
    // { "q": "1 + 7", "a": "8" },
    // { "q": "1 + 8", "a": "9" },
    // { "q": "1 + 9", "a": "10" },
    // { "q": "1 + 10", "a": "11" }];
    var arrayOfObjects = [];
    for (var i = 0; i < 11; i++) {
        var obj = {
            q: `${req.params.level} + ${i}`,
            a: i + parseInt(req.params.level)
        };
        arrayOfObjects.push(obj);
    }

    res.send(JSON.stringify(arrayOfObjects, null, 3));
    // switch (req.params.level) {
    //     case 1:
    // // res.send(JSON.stringify([{
    // //     "q": "1 + 0",
    // //     "a": "1"
    // // },
    // // {
    // //     "q": "1 + 1",
    // //     "a": "2"
    // // }, null, 2  ));

    //         ]));
    // };
    // res.send(`New add game level:  ${req.params.level}`);
};<|endoftext|>


<commit_before>import { assert } from 'chai';

import DateConverter from './DateConverter';
import ParseError from './ParseError';

describe('DateConverter', () => {
  it('should convert date to string', () => {
    let dc = new DateConverter('MM/dd/yyyy');

    const date = new Date(2001, 0, 15);
    const dateAsString = dc.valueToString(date);

    assert.equal(dateAsString, '01/15/2001');

    const stringAsDate = dc.stringToValue(dateAsString);
    assert.equal(stringAsDate.toString(), date.toString());

    dc = new DateConverter('dd/MM/yy');
    assert.strictEqual(dc.valueToString(date), '15/01/01');

    assert.throws(() => {
      assert.isNull(dc.stringToValue('aaaa'));
    }, ParseError, 'invalid parsed value [aaaa]');

    assert.throws(() => {
      assert.isNull(dc.stringToValue('11111'));
    }, ParseError, 'invalid parsed value [11111]');
  });
  it('should not throw error if no `format` argument specified', () => {
    assert.doesNotThrow(() => { let dc = new DateConverter(); });
  });
});
<commit_msg>Fixed lint errors.<commit_after>import { assert } from 'chai';

import DateConverter from './DateConverter';
import ParseError from './ParseError';

describe('DateConverter', () => {
  it('should convert date to string', () => {
    let dc = new DateConverter('MM/dd/yyyy');

    const date = new Date(2001, 0, 15);
    const dateAsString = dc.valueToString(date);

    assert.equal(dateAsString, '01/15/2001');

    const stringAsDate = dc.stringToValue(dateAsString);
    assert.equal(stringAsDate.toString(), date.toString());

    dc = new DateConverter('dd/MM/yy');
    assert.strictEqual(dc.valueToString(date), '15/01/01');

    assert.throws(() => {
      assert.isNull(dc.stringToValue('aaaa'));
    }, ParseError, 'invalid parsed value [aaaa]');

    assert.throws(() => {
      assert.isNull(dc.stringToValue('11111'));
    }, ParseError, 'invalid parsed value [11111]');
  });
  it('should not throw error if no `format` argument specified', () => {
    assert.doesNotThrow(() => {
      let dc = new DateConverter(); // eslint-disable-line no-unused-vars
    });
  });
});
<|endoftext|>