<commit_before>import React from 'react';
import $ from 'jquery';

import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormControl from 'react-bootstrap/lib/FormControl';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';

import WizardStart from './WizardStart';
import NameStep from './steps/NameStep';
import AddressStep from './steps/AddressStep';
import SummaryStep from './steps/SummaryStep';
import WizardFinish from './WizardFinish';
import Progress from './WizardProgress';
import Controls from './Controls';

export default class CreatePageWizard extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      step: 0,
      page: {
        name: '',
        addr: ''
      }
    };

    this.handleStartWizard = this.handleStartWizard.bind(this);
    this.submitWizard = this.submitWizard.bind(this);
    this.next = this.next.bind(this);
    this.previous = this.previous.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.validateNotEmpty = this.validateNotEmpty.bind(this);
    this.resetWizard = this.resetWizard.bind(this);
  }

  getNameValidationState() {
    let name = this.state.page.name;
    if (name) {
      const length = name.length;
      if (length < 5) {
        return 'error';
      } else {
        return 'success';
      }
    } else {
      return 'error';
    }
  }

  handleStartWizard() {
    this.setState({
      step: 1
    });
  }

  submitWizard() {
    const self = this;
    console.log('send to server', this.state.page);
    $.post('/api/pages', this.state.page).done(function (data) {
      if (data.success) {
        self.setState({
          step: self.state.step + 1,
          url: '/' + data.result.nameslug
        });
      }
    });
  }

  next() {
    this.setState({
      step: this.state.step + 1
    });
  }

  previous() {
    this.setState({
      step: this.state.step - 1
    });
  }

  resetWizard() {
    this.setState({
      step: 0
    });
  }

  handleChange(e) {
    let target = e.target;
    let name = target.getAttribute('data-name');
    let obj = this.state.page;
    obj[name] = target.value;
    if (name) {
      this.setState({
        page: obj
      });
    }
  }

  validateNotEmpty(field) {
    const page = this.state.page;
    if (!page[field]) {
      return 'error';
    }
    return 'success';
  }

  render() {
    switch (this.state.step) {
    case 0:
      return (
        <WizardStart startWizard={this.handleStartWizard}/>
      );
    case 1:
      return (

          <Progress step={this.state.step}/>
          <NameStep
            validationState={this.getNameValidationState()}
            value={this.state.page.name}
            handleChange={this.handleChange}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.next}
            disabled={this.getNameValidationState()  !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 2:
      return (

          <Progress step={this.state.step}/>
          <AddressStep
            page={this.state.page}
            handleChange={this.handleChange}
            validateNotEmpty={this.validateNotEmpty}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.next}
            disabled={this.validateNotEmpty('addr') !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 3:
      return (

          <Progress step={this.state.step}/>
          <SummaryStep
            page={this.state.page}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.submitWizard}
            nextText='Submit'
            disabled={this.validateNotEmpty('addr') !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 4:
      return (
        <WizardFinish page={this.state.page} url={this.state.url} closeWizard={this.resetWizard}/>
      );
    default:
      return (
        <WizardStart startWizard={this.handleStartWizard}/>
      );
    }
  }
}
<commit_msg>remove unused import<commit_after>import React from 'react';
import $ from 'jquery';

import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';

import WizardStart from './WizardStart';
import NameStep from './steps/NameStep';
import AddressStep from './steps/AddressStep';
import SummaryStep from './steps/SummaryStep';
import WizardFinish from './WizardFinish';
import Progress from './WizardProgress';
import Controls from './Controls';

export default class CreatePageWizard extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      step: 0,
      page: {
        name: '',
        addr: ''
      }
    };

    this.handleStartWizard = this.handleStartWizard.bind(this);
    this.submitWizard = this.submitWizard.bind(this);
    this.next = this.next.bind(this);
    this.previous = this.previous.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.validateNotEmpty = this.validateNotEmpty.bind(this);
    this.resetWizard = this.resetWizard.bind(this);
  }

  getNameValidationState() {
    let name = this.state.page.name;
    if (name) {
      const length = name.length;
      if (length < 5) {
        return 'error';
      } else {
        return 'success';
      }
    } else {
      return 'error';
    }
  }

  handleStartWizard() {
    this.setState({
      step: 1
    });
  }

  submitWizard() {
    const self = this;
    console.log('send to server', this.state.page);
    $.post('/api/pages', this.state.page).done(function (data) {
      if (data.success) {
        self.setState({
          step: self.state.step + 1,
          url: '/' + data.result.nameslug
        });
      }
    });
  }

  next() {
    this.setState({
      step: this.state.step + 1
    });
  }

  previous() {
    this.setState({
      step: this.state.step - 1
    });
  }

  resetWizard() {
    this.setState({
      step: 0
    });
  }

  handleChange(e) {
    let target = e.target;
    let name = target.getAttribute('data-name');
    let obj = this.state.page;
    obj[name] = target.value;
    if (name) {
      this.setState({
        page: obj
      });
    }
  }

  validateNotEmpty(field) {
    const page = this.state.page;
    if (!page[field]) {
      return 'error';
    }
    return 'success';
  }

  render() {
    switch (this.state.step) {
    case 0:
      return (
        <WizardStart startWizard={this.handleStartWizard}/>
      );
    case 1:
      return (

          <Progress step={this.state.step}/>
          <NameStep
            validationState={this.getNameValidationState()}
            value={this.state.page.name}
            handleChange={this.handleChange}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.next}
            disabled={this.getNameValidationState()  !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 2:
      return (

          <Progress step={this.state.step}/>
          <AddressStep
            page={this.state.page}
            handleChange={this.handleChange}
            validateNotEmpty={this.validateNotEmpty}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.next}
            disabled={this.validateNotEmpty('addr') !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 3:
      return (

          <Progress step={this.state.step}/>
          <SummaryStep
            page={this.state.page}
          />
          <Controls
            handlePrevious={this.previous}
            handleNext={this.submitWizard}
            nextText='Submit'
            disabled={this.validateNotEmpty('addr') !== 'success'}
            resetWizard={this.resetWizard}
          />

      );
    case 4:
      return (
        <WizardFinish page={this.state.page} url={this.state.url} closeWizard={this.resetWizard}/>
      );
    default:
      return (
        <WizardStart startWizard={this.handleStartWizard}/>
      );
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var connect     = require('connect');
var node_path     = require('path');

var USER_HOME = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var root = node_path.join(USER_HOME, '.cortex', 'built_modules');
var cwd = process.cwd();

module.exports = function(options, callback) {
    var app = connect();
    if(options.local){
        app.use("/" + options.local,connect.static(cwd));
        app.use("/" + options.local,connect.directory(cwd));
    }
    app.use("/",connect.static(root));
    app.use("/",connect.directory(root));
    app.listen(options.port, function() {
        var url = 'http://localhost:' + options.port;

        process.stdout.write('Cortex server started at ' + url + '\n');
        options.open && require('child_process').exec('open ' + url);
        callback && callback()
    });
};<commit_msg>migrate conf to cortex-profile<commit_after>'use strict';

var connect         = require('connect');
var node_path       = require('path');
var profile         = require('cortex-profile');

var cwd = process.cwd();

module.exports = function(options, callback) {
    var SERVER_ROOT = profile.option('built_root');
    var SERVER_PATH = '/' + profile.option('server_path');

    var app = connect();
    if(options.local){
        app.use("/" + options.local,connect.static(cwd));
        app.use("/" + options.local,connect.directory(cwd));
    }
    app.use(SERVER_PATH, connect.static(SERVER_ROOT));
    app.use(SERVER_PATH, connect.directory(SERVER_ROOT));

    app.listen(options.port, function() {
        var url = 'http://localhost:' + options.port + SERVER_PATH;

        process.stdout.write('Cortex server started at ' + url + '\n');
        options.open && require('child_process').exec('open ' + url);
        callback && callback()
    });
};<|endoftext|>


<commit_before>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];

 $http.get("level2.json")
    .then(function(response) {
        $scope.items = response.data;
    });

 $http.get("level1.json")
    .then(function(response) {
        $scope.level1 = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<commit_msg>Update app.js<commit_after>// Code goes here

var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);

function MyController($scope, $http) {

  $scope.currentPage = 1;
  $scope.pageSize = 20;
  $scope.items = [];
  $scope.level1 = [];
 $http.get("level2.json")
    .then(function(response) {
        $scope.items = response.data;
    });

 $http.get("level1.json")
    .then(function(response) {
        $scope.level1 = response.data;
    });

  $scope.pageChangeHandler = function(num) {

  };
}

function OtherController($scope) {
  $scope.pageChangeHandler = function(num) {

  };
}

myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
<|endoftext|>


<commit_before>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = require('../color/attributes');

module.exports = {
    bgcolor: {
        valType: 'color',
        dflt: colorAttributes.background,
        role: 'style',
        description: 'Sets the background color of the range slider.'
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttributes.defaultLine,
        role: 'style',
        description: 'Sets the border color of the range slider.'
    },
    borderwidth: {
        valType: 'integer',
        dflt: 0,
        role: 'style',
        description: 'Sets the border color of the range slider.'
    },
    thickness: {
        valType: 'number',
        dflt: 0.15,
        min: 0,
        max: 1,
        role: 'style',
        description: [
            'The height of the range slider as a fraction of the',
            'total plot area height.'
        ].join(' ')
    },
    visible: {
        valType: 'boolean',
        dflt: true,
        role: 'style',
        description: [
            'Determines whether or not the range slider will be visible.',
            'If visible, perpendicular axes will be set to `fixedrange`'
        ].join(' ')
    }
};
<commit_msg>Change role style->info<commit_after>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = require('../color/attributes');

module.exports = {
    bgcolor: {
        valType: 'color',
        dflt: colorAttributes.background,
        role: 'style',
        description: 'Sets the background color of the range slider.'
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttributes.defaultLine,
        role: 'style',
        description: 'Sets the border color of the range slider.'
    },
    borderwidth: {
        valType: 'integer',
        dflt: 0,
        role: 'style',
        description: 'Sets the border color of the range slider.'
    },
    thickness: {
        valType: 'number',
        dflt: 0.15,
        min: 0,
        max: 1,
        role: 'style',
        description: [
            'The height of the range slider as a fraction of the',
            'total plot area height.'
        ].join(' ')
    },
    visible: {
        valType: 'boolean',
        dflt: true,
        role: 'info',
        description: [
            'Determines whether or not the range slider will be visible.',
            'If visible, perpendicular axes will be set to `fixedrange`'
        ].join(' ')
    }
};
<|endoftext|>


<commit_before>'use strict';

// ext. libs
var Q = require('q');
var fs = require('fs');
var PNG = require('node-pngjs').PNG;

/**
 * Execute related methods
 *
 * @module Driver
 * @class Image
 * @namespace Dalek.DriverNative.Image
 */

var Image = {
  imagecompare : function (opts, expected, makediff, hash) {
    this.actionQueue.push(this._imagecompareCb.bind(this, opts, expected, makediff, hash));
    return this;
  },
  imagecut : function (opts, hash) {
    var position = {},
      path = opts.realpath;

    this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, opts.selector));
    this.actionQueue.push(this.webdriverClient.location.bind(this.webdriverClient, opts.selector));

    /* get left top positions of element*/
    this.actionQueue.push(function (result) {
      var value = JSON.parse(result).value;
      position.x = value.x;
      position.y = value.y;
    });

    this.actionQueue.push(this.webdriverClient.size.bind(this.webdriverClient, opts.selector));
    this.actionQueue.push(this._imagecutCb.bind(this, opts, hash, opts.selector, position));

    return this;
  },
  _imagecutCb: function (opts, hash, selector, position, result) {
    var rect,
      size = JSON.parse(result),
      deferred = Q.defer();
      rect = this._convertToRect(position, size.value);
    var cb = function () {
      this.events.emit('driver:message', {key: 'imagecut', value: selector, uuid: hash, hash: hash});
      deferred.resolve();
    };

    this._doImagecut(opts.realpath, opts.selector, rect, cb.bind(this));

    return deferred.promise;
   },
   _doImagecut: function (path, element, rect, cb) {
    this._parsePNG(path).then(function (image) {
      var pngDst = new PNG({
        width: rect.width,
        height:rect.height
      });

      image.png.bitblt(pngDst, rect.x, rect.y, rect.width, rect.height, 0, 0);
      this._savePNG(pngDst, image.path).then(cb);

    }.bind(this));
   },
  _imagecompareCb: function (opts, expected, makediff, hash) {
    var current = opts.realpath;
    var deferred = Q.defer();

    var cb = function (result) {
      this.events.emit('driver:message', {key: 'imagecompare', value: result, uuid: hash, hash: hash});
      deferred.resolve();
    };

    this._doImagecompare(current, expected, makediff, cb.bind(this));

    return deferred.promise;
  },
  _doImagecompare: function (image_a, image_b, makediff, cb) {
    var promises = [this._parsePNG(image_a), this._parsePNG(image_b)];
    Q.all(promises)
    .then(function (images) {
      var result = this._checkIfImagesTheSameAndMakeDiff(images[0], images[1], makediff);
      if (result === 'Images are different' && makediff) {
        var imageDiffPath = images[1].path.replace('.png', '.diff.png');
        this._savePNG(images[1].png, imageDiffPath)
        .then(function () {
          var cbresult = result + '. See differences by path ' + imageDiffPath;
          cb(cbresult);
        },
        function (error) {
          cb('error ' + JSON.stringify(error));
        });
      } else {
        cb(result);
      }
    }.bind(this),
    function (errors) {
      cb(errors);
    });
  },
  _checkIfImagesTheSameAndMakeDiff : function (a, b, makediff) {

    if (a.data.length !== b.data.length) {
      return 'Images have different sizes';
    }

    var result = 'equal';

    for (var i = 0, len = a.data.length; i < len; i += 4) {
      if (a.data[i]     !== b.data[i] ||
          a.data[i + 1] !== b.data[i + 1] ||
          a.data[i + 2] !== b.data[i + 2]) {
        result = 'Images are different';
        if (makediff) {
          this._setErrorPixel(b.data, i);
        } else {
          return result;
        }
      }
    }

    return result;
  },
  _parsePNG: function (path) {
    var deferred = Q.defer();
    fs.createReadStream(path)
    .pipe(new PNG({
        filterType: 1
    }))
    .on('parsed', function() {
      var paresedImage = {
        path   : path,
        data   : this.data,
        png    : this
      };

      deferred.resolve(paresedImage);
    })
    .on('error', function (event) {
      deferred.reject(event);
    });

    return deferred.promise;
  },
  _savePNG : function (png, filePath) {
    var deferred = Q.defer();
    png
    .pack()
    .pipe(fs.createWriteStream(filePath, {flags: 'w'}))
    .on('error', function (errors) {
      deferred.reject(errors);
    })
    .on('close', function () {
      deferred.resolve();
    });

    return deferred.promise;
  },
  _setErrorPixel : function (dst, index) {
    var errorPixelColor = { // Color for Error Pixels. Between 0 and 255.
      red: 255,
      green: 0,
      blue: 255,
      alpha: 255
    };

    dst[index]     = errorPixelColor.red;
    dst[index + 1] = errorPixelColor.green;
    dst[index + 2] = errorPixelColor.blue;
    dst[index + 3] = errorPixelColor.alpha;
  },
  _convertToRect: function (position, size) {
    return {
      x:position.x,
      y:position.y,
      width : size.width,
      height: size.height
    };
   }
};

module.exports = function (DalekNative) {
  // mixin methods

  Object.keys(Image).forEach(function (fn) {
    DalekNative.prototype[fn] = Image[fn];
  });

  return DalekNative;
};

<commit_msg>Refactoring. Inrease readability<commit_after>'use strict';

// ext. libs
var Q = require('q');
var fs = require('fs');
var PNG = require('node-pngjs').PNG;

/**
 * Execute related methods
 *
 * @module Driver
 * @class Image
 * @namespace Dalek.DriverNative.Image
 */

var Image = {
  imagecompareResults : {
    equal         : 'equal',
    sizeDifferent : 'images have different sizes',
    imageDiffent  : 'images are different'
  },
  imagecompare : function (opts, expected, makediff, hash) {
    this.actionQueue.push(this._imagecompareCb.bind(this, opts, expected, makediff, hash));
    return this;
  },
  imagecut : function (opts, hash) {
    var position = {},
      path = opts.realpath;

    this.actionQueue.push(this.webdriverClient.element.bind(this.webdriverClient, opts.selector));
    this.actionQueue.push(this.webdriverClient.location.bind(this.webdriverClient, opts.selector));

    /* get left top positions of element*/
    this.actionQueue.push(function (result) {
      var value = JSON.parse(result).value;
      position.x = value.x;
      position.y = value.y;
    });

    this.actionQueue.push(this.webdriverClient.size.bind(this.webdriverClient, opts.selector));
    this.actionQueue.push(this._imagecutCb.bind(this, opts, hash, opts.selector, position));

    return this;
  },
  _imagecutCb: function (opts, hash, selector, position, result) {
    var rect,
      size = JSON.parse(result),
      deferred = Q.defer();
      rect = this._convertToRect(position, size.value);
    var cb = function () {
      this.events.emit('driver:message', {key: 'imagecut', value: selector, uuid: hash, hash: hash});
      deferred.resolve();
    };

    this._doImagecut(opts.realpath, opts.selector, rect, cb.bind(this));

    return deferred.promise;
   },
   _doImagecut: function (path, element, rect, cb) {
    this._parsePNG(path).then(function (image) {
      var pngDst = new PNG({
        width: rect.width,
        height:rect.height
      });

      image.png.bitblt(pngDst, rect.x, rect.y, rect.width, rect.height, 0, 0);
      this._savePNG(pngDst, image.path).then(cb);

    }.bind(this));
   },
  _imagecompareCb: function (opts, expected, makediff, hash) {
    var current = opts.realpath;
    var deferred = Q.defer();

    var cb = function (result) {
      this.events.emit('driver:message', {key: 'imagecompare', value: result, uuid: hash, hash: hash});
      deferred.resolve();
    };

    this._doImagecompare(current, expected, makediff, cb.bind(this));

    return deferred.promise;
  },
  _doImagecompare: function (actualPath, etalonPath, makediff, cb) {
    var promises = [this._parsePNG(actualPath), this._parsePNG(etalonPath)];

    Q.all(promises)
    .spread(function (parsedImageA, parsedImageB) {
      var result = this._checkIfImagesTheSameAndMakeDiff(parsedImageA, parsedImageB, makediff);
      if (result === this.imagecompareResults.imageDiffent && makediff) {
        this._doSaveImageDiff(parsedImageB, result)
        .then(function (filePath) {
          cb(result + '. See differences by path ' + filePath);
        },
        cb);
      } else {
        cb(result);
      }
    }.bind(this),
    cb);
  },
  _doSaveImageDiff : function (image) {
    var imageDiffPath = image.path.replace('.png', '.diff.png');

    return this._savePNG(image.png, imageDiffPath);
  },
  _checkIfImagesTheSameAndMakeDiff : function (a, b, makediff) {

    if (a.data.length !== b.data.length) {
      return this.imagecompareResults.sizeDifferent;
    }

    var result = this.imagecompareResults.equal;

    for (var i = 0, len = a.data.length; i < len; i += 4) {
      if (a.data[i]     !== b.data[i] ||
          a.data[i + 1] !== b.data[i + 1] ||
          a.data[i + 2] !== b.data[i + 2]) {
        result = this.imagecompareResults.imageDiffent;
        if (makediff) {
          this._setErrorPixel(b.data, i);
        } else {
          return result;
        }
      }
    }

    return result;
  },
  _parsePNG: function (path) {
    var deferred = Q.defer();

    fs.createReadStream(path)
    .pipe(new PNG({
        filterType: 1
    }))
    .on('parsed', function() {
      var parsedImage = {
        path   : path,
        data   : this.data,
        png    : this
      };

      deferred.resolve(parsedImage);
    })
    .on('error', function (event) {
      deferred.reject(event);
    });

    return deferred.promise;
  },
  _savePNG : function (png, filePath) {
    var deferred = Q.defer();

    png
    .pack()
    .pipe(fs.createWriteStream(filePath, {flags: 'w'}))
    .on('error', function (errors) {
      deferred.reject(errors);
    })
    .on('close', function () {
      deferred.resolve(filePath);
    });

    return deferred.promise;
  },
  _setErrorPixel : function (dst, index) {
    var errorPixelColor = { // Color for Error Pixels. Between 0 and 255.
      red: 255,
      green: 0,
      blue: 255,
      alpha: 255
    };

    dst[index]     = errorPixelColor.red;
    dst[index + 1] = errorPixelColor.green;
    dst[index + 2] = errorPixelColor.blue;
    dst[index + 3] = errorPixelColor.alpha;
  },
  _convertToRect: function (position, size) {
    return {
      x:position.x,
      y:position.y,
      width : size.width,
      height: size.height
    };
  }
};

module.exports = function (DalekNative) {
  // mixin methods

  Object.keys(Image).forEach(function (fn) {
    DalekNative.prototype[fn] = Image[fn];
  });

  return DalekNative;
};

<|endoftext|>


<commit_before>var Observable = require('../../../lib/observable')

var Emitter = require('../../../lib/emitter')

var Base = require('../../../lib/base')

//$ChildConstructor
var ARandomConstructor = new Base({
  hello:true
})
var bla = new Observable({
  $define: {
    $ChildConstructor: ARandomConstructor.$Constructor
  }
})

// Object.defineProperty( bla, '$ChildConstructor', {
//   value: ARandomConstructor.$Constructor,
//   configurable: true
// })
// console.log( bla, Object.getPrototypeOf( bla ) === ARandomConstructor )
var blaInstance = new bla.$Constructor({
  specialField: true
})

console.log(blaInstance)<commit_msg>added custom emitters in examples<commit_after>var Observable = require('../../../lib/observable')
var Emitter = require('../../../lib/emitter')

var Event = require('../../../lib/event')

var emit = Emitter.prototype.$emit

var blurfEmitter = new Emitter({
  $define: {
    $emit: function( event, bind, context ) {
      console.log('hey an emit in blurfEmitter', arguments)

      // var metaObj = arguments

      return emit.call(this, event, bind, context, arguments )
    }
  }
})

var a = new Observable({
  $define: {
    $val: {
      set: function( val ) {
        var event = new Event( this )
        console.log('???')
        this.$emit( '$blurfEmitter', event, val, 'x', 'y', 'z' )
        this.$set( val )
      }
    }
  },
  $on: {
    $flags: {
      $blurfEmitter : blurfEmitter
    }
  }
})

var b = new a.$Constructor({
  $on: {
    $blurfEmitter: function() {
      console.log( arguments )
    }
  }
})

b.$val = 'xxxx'
<|endoftext|>


<commit_before>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

'use strict';

var Request = require('./request').Request;
var util = require('util');

exports.UserEntitiesRequest = module.exports.UserEntitiesRequest = UserEntitiesRequest;

util.inherits(UserEntitiesRequest, Request);

function UserEntitiesRequest(application, user_entities, options) {
    var self = this;

    self.user_entities = user_entities

    UserEntitiesRequest.super_.apply(this, [application, options]);
}

UserEntitiesRequest.prototype._headers = function() {
    var headers = UserEntitiesRequest.super_.prototype._headers.apply(this, arguments);

    headers['Content-Type'] = 'application/json; charset=utf-8';

    return headers;
};

UserEntitiesRequest.prototype._requestOptions = function() {
    var request_options = UserEntitiesRequest.super_.prototype._requestOptions.apply(this, arguments);

    request_options.path = this.endpoint + 'userEntities'
    request_options.method = 'POST'

    return request_options
};

UserEntitiesRequest.prototype.end = function() {
    var self = this;

    self.write(JSON.stringify(self.user_entities));

    UserEntitiesRequest.super_.prototype.end.apply(this, arguments);
};
<commit_msg>Added more missing ';'<commit_after>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

'use strict';

var Request = require('./request').Request;
var util = require('util');

exports.UserEntitiesRequest = module.exports.UserEntitiesRequest = UserEntitiesRequest;

util.inherits(UserEntitiesRequest, Request);

function UserEntitiesRequest(application, user_entities, options) {
    var self = this;

    self.user_entities = user_entities;

    UserEntitiesRequest.super_.apply(this, [application, options]);
}

UserEntitiesRequest.prototype._headers = function() {
    var headers = UserEntitiesRequest.super_.prototype._headers.apply(this, arguments);

    headers['Content-Type'] = 'application/json; charset=utf-8';

    return headers;
};

UserEntitiesRequest.prototype._requestOptions = function() {
    var request_options = UserEntitiesRequest.super_.prototype._requestOptions.apply(this, arguments);

    request_options.path = this.endpoint + 'userEntities';
    request_options.method = 'POST';

    return request_options
};

UserEntitiesRequest.prototype.end = function() {
    var self = this;

    self.write(JSON.stringify(self.user_entities));

    UserEntitiesRequest.super_.prototype.end.apply(this, arguments);
};
<|endoftext|>


<commit_before>/* jshint node: true, esnext: true */
'use strict';

var sha1 = require('git-sha1');
var codec = require('js-git/lib/object-codec');
var inflate = require('js-git/lib/inflate');
var deflate = require('js-git/lib/deflate');

module.exports = (cache, central, types) => {

  function isCached(type) {
    return types.indexOf(type) >= 0;
  }

  function encode(type, body) {
    return Promise.resolve(body)
      .then(b => codec.encoders[type](b))
      .then(binary => codec.frame({ type : type, body : binary }));
  }

  function decode(type, buffer) {
    return Promise.resolve(buffer)
      .then(raw => codec.deframe(raw))
      .then(deframed => {
        if (deframed.type === type) {
          return deframed.body;
        } else {
          throw new TypeError('Expected a git ' + type + ', found a ' + deframed.type);
        }
      })
      .then(body => codec.decoders[type](body));
  }

  function saveAs(type, body) {
    return encode(type, body)
      .then(raw => {
        var p, hash = sha1(raw), buffer = deflate(raw);
        if (isCached(type)) {
          p = Promise.all([central.saveRaw(hash, buffer), cache.saveRaw(hash, buffer)]);
        } else {
          p = central.saveRaw(hash, buffer);
        }
        return p.then(() => hash);
      });
  }

  function hash(type, body) {
    return encode(type, body).then(sha1);
  }

  function inStore(hash) {
    return cache.exists(hash)
      .then(ex => {
        if (ex) {
          return true;
        } else {
          return central.exists(hash);
        }
      });
  }

  function loadAs(type, hash) {
    var promise;
    if (isCached(type)) {
      promise = cache.loadRaw(hash)
        .then(buffer => {
          if (buffer) {
            return buffer;
          } else {
            return central.loadRaw(hash)
              .then(raw => {
                cache.saveRaw(hash, raw).then(() => raw);
              });
          }
        });
    } else {
      promise = central.loadRaw(hash);
    }
    return promise.then(inflate).then(buffer => decode(type, buffer));
  }

  return {
    saveAs,
    loadAs,
    hash,
    inStore,
    readRef : central.readRef.bind(central),
    updateRef : central.updateRef.bind(central)
  };
};
<commit_msg>Store in cache only if central is successfully updated<commit_after>/* jshint node: true, esnext: true */
'use strict';

var sha1 = require('git-sha1');
var codec = require('js-git/lib/object-codec');
var inflate = require('js-git/lib/inflate');
var deflate = require('js-git/lib/deflate');

module.exports = (cache, central, types) => {

  function isCached(type) {
    return types.indexOf(type) >= 0;
  }

  function encode(type, body) {
    return Promise.resolve(body)
      .then(b => codec.encoders[type](b))
      .then(binary => codec.frame({ type : type, body : binary }));
  }

  function decode(type, buffer) {
    return Promise.resolve(buffer)
      .then(raw => codec.deframe(raw))
      .then(deframed => {
        if (deframed.type === type) {
          return deframed.body;
        } else {
          throw new TypeError('Expected a git ' + type + ', found a ' + deframed.type);
        }
      })
      .then(body => codec.decoders[type](body));
  }

  function saveAs(type, body) {
    return encode(type, body)
      .then(raw => {
        var hash = sha1(raw);
        var buffer = deflate(raw);
        var p = central.saveRaw(hash, buffer);
        if (isCached(type)) {
          p = p.then(() => cache.saveRaw(hash, buffer));
        }
        return p.then(() => hash);
      });
  }

  function hash(type, body) {
    return encode(type, body).then(sha1);
  }

  function inStore(hash) {
    return cache.exists(hash)
      .then(ex => {
        if (ex) {
          return true;
        } else {
          return central.exists(hash);
        }
      });
  }

  function loadAs(type, hash) {
    var promise;
    if (isCached(type)) {
      promise = cache.loadRaw(hash)
        .then(buffer => {
          if (buffer) {
            return buffer;
          } else {
            return central.loadRaw(hash)
              .then(raw => {
                cache.saveRaw(hash, raw).then(() => raw);
              });
          }
        });
    } else {
      promise = central.loadRaw(hash);
    }
    return promise.then(inflate).then(buffer => decode(type, buffer));
  }

  return {
    saveAs,
    loadAs,
    hash,
    inStore,
    readRef : central.readRef.bind(central),
    updateRef : central.updateRef.bind(central)
  };
};
<|endoftext|>


<commit_before>/* jshint node: true, esnext: true */
'use strict';

var sha1 = require('git-sha1');
var codec = require('js-git/lib/object-codec');
var inflate = require('js-git/lib/inflate');
var deflate = require('js-git/lib/deflate');

module.exports = (cache, central, types) => {

  function isCached(type) {
    return types.indexOf(type) >= 0;
  }

  function encode(type, body) {
    try {
      var binary = codec.encoders[type](body);
      var frame = codec.frame({ type : type, body : binary });
      var raw = deflate(frame);
      return Promise.resolve(raw);
    } catch (err) {
      return Promise.reject(err);
    }
  }

  function saveAs(type, body) {
    return encode(type, body)
      .then(raw => {
        var p, hash = sha1(raw);
        if (isCached(type)) {
          p = Promise.all([central.saveRaw(hash, raw), cache.saveRaw(hash, raw)]);
        } else {
          p = central.saveRaw(hash, raw);
        }
        return p.then(() => hash);
      });
  }

  function hash(type, body) {
    return encode(type, body).then(sha1);
  }

  function inStore(hash) {
    return cache.exists(hash)
      .then(ex => {
        if (ex) {
          return true;
        } else {
          return central.exists(hash);
        }
      });
  }

  function loadAs(type, hash) {
    var promise;
    if (isCached(type)) {
      promise = cache.loadRaw(hash)
        .then(buffer => {
          if (!buffer) {
            return central.loadRaw(hash)
              .then(raw => {
                cache.saveRaw(hash, raw).then(() => raw);
              });
          }
        });
    } else {
      promise = central.loadRaw(hash);
    }
    return promise.then(inflate);
  }

  return {
    saveAs,
    loadAs,
    hash,
    inStore,
    readRef : central.readRef.bind(central),
    updateRef : central.updateRef.bind(central)
  };
};
<commit_msg>Deflate after computing hash<commit_after>/* jshint node: true, esnext: true */
'use strict';

var sha1 = require('git-sha1');
var codec = require('js-git/lib/object-codec');
var inflate = require('js-git/lib/inflate');
var deflate = require('js-git/lib/deflate');

module.exports = (cache, central, types) => {

  function isCached(type) {
    return types.indexOf(type) >= 0;
  }

  function encode(type, body) {
    try {
      var binary = codec.encoders[type](body);
      var raw = codec.frame({ type : type, body : binary });
      return Promise.resolve(raw);
    } catch (err) {
      return Promise.reject(err);
    }
  }

  function saveAs(type, body) {
    return encode(type, body)
      .then(raw => {
        var p, hash = sha1(raw), buffer = deflate(raw);
        if (isCached(type)) {
          p = Promise.all([central.saveRaw(hash, buffer), cache.saveRaw(hash, buffer)]);
        } else {
          p = central.saveRaw(hash, buffer);
        }
        return p.then(() => hash);
      });
  }

  function hash(type, body) {
    return encode(type, body).then(sha1);
  }

  function inStore(hash) {
    return cache.exists(hash)
      .then(ex => {
        if (ex) {
          return true;
        } else {
          return central.exists(hash);
        }
      });
  }

  function loadAs(type, hash) {
    var promise;
    if (isCached(type)) {
      promise = cache.loadRaw(hash)
        .then(buffer => {
          if (!buffer) {
            return central.loadRaw(hash)
              .then(raw => {
                cache.saveRaw(hash, raw).then(() => raw);
              });
          }
        });
    } else {
      promise = central.loadRaw(hash);
    }
    return promise.then(inflate);
  }

  return {
    saveAs,
    loadAs,
    hash,
    inStore,
    readRef : central.readRef.bind(central),
    updateRef : central.updateRef.bind(central)
  };
};
<|endoftext|>


<commit_before>"use strict";

var clc = require('cli-color');
var read = require('read')
var sys = require('sys')
var spawn = require('child_process').spawn;
var rek = require('rekuire');

var linksUtils = rek('linksUtils');

var phase = "dry";
var currentLink = null;

module.exports = {
    run: run
};

function run(link) {
    if (currentLink) return console.log(clc.red("Error! Haven't finished running the previous link."))
    currentLink = link;
    if (!linksUtils.varify(currentLink)) {
        return console.log(clc.red("Link invalid!"));
    }
    promptForExecution();
}

function promptForExecution() {
    var commandArgs = [currentLink.source, currentLink.target, "-Phavyx", "--delete-after", "--dry-run"];
    if (phase == "wet") {
        removeDryRun(commandArgs);
    }

    read({prompt: parsePrompt(phase, commandArgs)}, function(error, input, isDefault) {
        if (error) {
            return console.log(clc.red("Error handling input, or input invalid!"));
        } else if (isAnswerPositive(phase, input)) {
          execute(commandArgs);
        }
    });
}

function execute(commandArgs) {
    var command = spawn('rsync', commandArgs);
    command.stdout.on('data', outputBuffer);
    command.stderr.on('data', outputBuffer);
    command.on('exit', function (code) {
      if (code !== 0) {
        return console.log('child process exited with code ' + code);
      }
      if (phase == "wet") {
        currentLink = null;
        return;
      }
      phase = "wet";
      promptForExecution();
    });
}

function outputBuffer(data) {
    console.log(data.toString().replace("\n",""));
}

function removeDryRun(args) {
    var dryIndex = args.indexOf("--dry-run");
    if (~dryIndex) {
      args.splice(dryIndex, 1);
    }
}

function parsePrompt(phase, commandArgs) {
  var outputColorFunction = (~commandArgs.indexOf("--dry-run")) ? clc.yellow : clc.red;
  var prompt = outputColorFunction("rsync " + commandArgs.join(" ")) + "\nExecute command? : " + ((phase == "wet") ? "[N/yes]" : "[N/y]") + "\n";
  return prompt;
}

function isAnswerPositive(phase, input) {
  return (phase == "wet" && input.toLowerCase() == "yes") || (phase == "dry" &&  input.toLowerCase() == "y");
}
////////////////////////////////////////////////////////////////////////////////

<commit_msg>removed the phase var<commit_after>"use strict";

var clc = require('cli-color');
var read = require('read')
var sys = require('sys')
var spawn = require('child_process').spawn;
var rek = require('rekuire');

var linksUtils = rek('linksUtils');

var currentLink = null;

module.exports = {
    run: run
};

function run(link) {
    if (currentLink) return console.log(clc.red("Error! Haven't finished running the previous link."))
    currentLink = link;
    if (!linksUtils.varify(currentLink)) {
        return console.log(clc.red("Link invalid!"));
    }
    promptForExecution();
}

function promptForExecution(wet) {
    var commandArgs = [currentLink.source, currentLink.target, "-Phavyx", "--delete-after", "--dry-run"];
    if (wet) {
        removeDryRun(commandArgs);
    }

    read({prompt: parsePrompt(commandArgs, wet)}, function(error, input, isDefault) {
        if (error) {
            return console.log(clc.red("Error handling input, or input invalid!"));
        } else if (isAnswerPositive(input, wet)) {
          execute(commandArgs, wet);
        }
    });
}

function execute(commandArgs, wet) {
    var command = spawn('rsync', commandArgs);
    command.stdout.on('data', outputBuffer);
    command.stderr.on('data', outputBuffer);
    command.on('exit', function (code) {
      if (code !== 0) {
        return console.log('child process exited with code ' + code);
      }
      if (wet) {
        currentLink = null;
      } else {
        promptForExecution(true);
      }
    });
}

function outputBuffer(data) {
    console.log(data.toString().replace("\n",""));
}

function removeDryRun(args) {
    var dryIndex = args.indexOf("--dry-run");
    if (~dryIndex) {
      args.splice(dryIndex, 1);
    }
}

function parsePrompt(commandArgs, wet) {
  var outputColorFunction = wet ? clc.red : clc.yellow;
  var prompt = outputColorFunction("rsync " + commandArgs.join(" ")) + "\nExecute command? : " + (wet ? "[N/yes]" : "[N/y]") + "\n";
  return prompt;
}

function isAnswerPositive(input, wet) {
  return (wet && input.toLowerCase() == "yes") || (!wet &&  input.toLowerCase() == "y");
}
////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>import forEach from 'lodash.foreach';
import merge from 'lodash.merge';
import union from 'lodash.union';
import warning from 'warning';

import actionTypes from '../actions/types';
import connectors from './connectors';
import processNode from './process-node';
import store from './store';

// Default state
// state will be composed of connectors data, e.g.
// {
//   connector_1: {
//     pages: [{...}, {...}]
//   },
//   connector_2: {
//     page: {...}
//   }
// }
const defaultState = {};

export default function graphqlReducer (state = defaultState, action = {}) {
  if ((action.type === actionTypes.query || action.type === actionTypes.mutation) &&
      action.data &&
      action.fragments) {
    const isMutation = action.type === actionTypes.mutation;
    const isRemoveMutation = isMutation && action.mutationType === 'REMOVE';
    let connectorsToUpdate = action.connectors && Object.keys(action.connectors) || [];
    let nodes = [];

    if (isRemoveMutation) {
      forEach(action.fragments, (fragment, queryName) => {
        if (fragment._id) {
          const queryData = action.data[queryName];
          if (queryData && queryData._id) {
            // Remove from store
            store.removeNode(queryData._id);

            // Remove from connectors
            connectorsToUpdate = connectors.removeNode(queryData._id);

            // Check connectors listening to this mutation
            connectorsToUpdate = union(
              connectorsToUpdate,
              connectors.checkMutationListeners(queryName, [], [])
            );
          } else {
            warning(false, 'RELATE: Remove action failed');
            // TODO handle error in some way?
          }
        }
      });
    } else {
      forEach(action.fragments, (fragment, queryName) => {
        const nodesProcessed = processNode(
          action.data[queryName],
          fragment
        ); // { relativeNodes: [], nodes: [], changes: {} }

        // DB changes
        store.updateNodes(nodesProcessed.changes);

        // Save nodes changed to later check which connectors to update
        nodes = union(nodes, nodesProcessed.nodes);

        // Connectors
        if (action.connectors) {
          connectors.processConnectors(
            action.connectors,
            queryName,
            nodesProcessed.relativeNodes,
            nodesProcessed.nodes
          );
        }

        // Mutations
        if (isMutation) {
          connectorsToUpdate = union(
            connectorsToUpdate,
            connectors.checkMutationListeners(queryName, nodesProcessed.relativeNodes, nodesProcessed.nodes)
          );
        }
      });
    }

    // Check more connectors than need to update
    connectorsToUpdate = connectorsToUpdate.concat(
      connectors.getConnectorsToUpdate(nodes, connectorsToUpdate)
    );

    // Calculate connectors data
    const changes = {};
    forEach(connectorsToUpdate, (connectorId) => {
      changes[connectorId] = connectors.generateConnectorData(connectorId);
    });

    return merge({}, state, changes);
  }

  if (action.type === actionTypes.removeConnector) {
    const newState = Object.assign({}, state);
    delete newState[action.id];
    connectors.deleteConnector(action.id);
    // TODO Delete no longer needed data from state? or maintain for future cache?
    return newState;
  }

  return state;
}
<commit_msg>fixed merge issue on reducer<commit_after>import forEach from 'lodash.foreach';
import union from 'lodash.union';
import warning from 'warning';

import actionTypes from '../actions/types';
import connectors from './connectors';
import processNode from './process-node';
import store from './store';

// Default state
// state will be composed of connectors data, e.g.
// {
//   connector_1: {
//     pages: [{...}, {...}]
//   },
//   connector_2: {
//     page: {...}
//   }
// }
const defaultState = {};

export default function graphqlReducer (state = defaultState, action = {}) {
  if ((action.type === actionTypes.query || action.type === actionTypes.mutation) &&
      action.data &&
      action.fragments) {
    const isMutation = action.type === actionTypes.mutation;
    const isRemoveMutation = isMutation && action.mutationType === 'REMOVE';
    let connectorsToUpdate = action.connectors && Object.keys(action.connectors) || [];
    let nodes = [];

    if (isRemoveMutation) {
      forEach(action.fragments, (fragment, queryName) => {
        if (fragment._id) {
          const queryData = action.data[queryName];
          if (queryData && queryData._id) {
            // Remove from store
            store.removeNode(queryData._id);

            // Remove from connectors
            connectorsToUpdate = connectors.removeNode(queryData._id);

            // Check connectors listening to this mutation
            connectorsToUpdate = union(
              connectorsToUpdate,
              connectors.checkMutationListeners(queryName, [], [])
            );
          } else {
            warning(false, 'RELATE: Remove action failed');
            // TODO handle error in some way?
          }
        }
      });
    } else {
      forEach(action.fragments, (fragment, queryName) => {
        const nodesProcessed = processNode(
          action.data[queryName],
          fragment
        ); // { relativeNodes: [], nodes: [], changes: {} }

        // DB changes
        store.updateNodes(nodesProcessed.changes);

        // Save nodes changed to later check which connectors to update
        nodes = union(nodes, nodesProcessed.nodes);

        // Connectors
        if (action.connectors) {
          connectors.processConnectors(
            action.connectors,
            queryName,
            nodesProcessed.relativeNodes,
            nodesProcessed.nodes
          );
        }

        // Mutations
        if (isMutation) {
          connectorsToUpdate = union(
            connectorsToUpdate,
            connectors.checkMutationListeners(queryName, nodesProcessed.relativeNodes, nodesProcessed.nodes)
          );
        }
      });
    }

    // Check more connectors than need to update
    connectorsToUpdate = connectorsToUpdate.concat(
      connectors.getConnectorsToUpdate(nodes, connectorsToUpdate)
    );

    // Calculate connectors data
    const changes = {};
    forEach(connectorsToUpdate, (connectorId) => {
      changes[connectorId] = connectors.generateConnectorData(connectorId);
    });

    return Object.assign({}, state, changes);
  }

  if (action.type === actionTypes.removeConnector) {
    const newState = Object.assign({}, state);
    delete newState[action.id];
    connectors.deleteConnector(action.id);
    // TODO Delete no longer needed data from state? or maintain for future cache?
    return newState;
  }

  return state;
}
<|endoftext|>


<commit_before>"use strict"; // strict mode syntax
//Creates a set of audio data from the provided arrayinfo
function AudioPlayer() {
  this.duration = 0.5; //default duration of a single note
  this.timeStep = 0.5;
  this.maxFreq = 64;
  this.minFreq = 28;
  this.audio = [];
  this.infoCollection = new ArrayCollection([]);
  this.isDirty = false;
  this.timeoutQueue = [];
  this.playing = false;
}

//Add a line to the collection used to calculate audio lines
AudioPlayer.prototype.addLine = function(arrayInfo) {
  this.infoCollection.addLine(arrayInfo);
}

//Add a single line to the audio player
AudioPlayer.prototype.addAudioLine = function(arrayInfo) {
  this.audio.push(jsfxlib.createWaves(this.genWaves(arrayInfo)));
}

//Using an arrayCollection object you can add a group of lines to the audio object
AudioPlayer.prototype.setCollection = function(collection) {
  var dropdownString ="";
  this.infoCollection.setCollection(collection);
  for(var i = 0; i < collection.length; i++) {
    dropdownString += "<option value="+(i + 1)+">"+(i + 1)+"</option>"
  }
  this.isDirty = true;
  document.getElementById("audioSpan").style.display = "";
  document.getElementById("lineDropdown").innerHTML = dropdownString;
}

//A change was made to a line in the table
AudioPlayer.prototype.changeLine = function(line, index, newValue) {
  if(line != 0) {
    this.infoCollection.changeLine(line,index,newValue);
    this.isDirty = true;
  }
}

//This function causes the audio information to actually be calculated.
//Should be called whenever the audio data changes
AudioPlayer.prototype.recalculateLines = function() {
  this.audio = [];
  for(var i = 0; i < this.infoCollection.collection.length; i++) {
    this.addAudioLine(this.infoCollection.collection[i]);
  }
  this.isDirty = false;
}

//Toggle playing either on or off
AudioPlayer.prototype.playToggle = function(line, startIndex, endIndex) {
  if(!this.playing) {
    this.playLine(line, startIndex, endIndex);
  }
  else {
    this.stopPlaying();
  }
  this.updateIcon();
}

//Play a line. can also have optional parameters for start and ending index
AudioPlayer.prototype.playLine = function(line, startIndex, endIndex) {
  //If the lines have been changed since the last time they
  //were played then recalculate them

  //Reset the timeout queue
  this.timeoutQueue = [];
  this.playing = true;

  if(this.isDirty) {
    this.recalculateLines();
  }
  var multiplier = document.getElementById("bpm").value;
  if(multiplier <= 0) {
    multiplier = 1;
  }
  var speed = this.timeStep/(multiplier || 1);

  var end = (endIndex || this.infoCollection.collection[line].array.length-1);
  var self = this;
  var startIndex = (startIndex || 0);
  //If startIndex or endIndex are undefined they will be set to the start and end of the line respectively
  for(var i = startIndex; i <= end; i++) {
    this.playPointWithDelay(line, i, (i-startIndex)*(speed-speed/8)*1000);

    if(i == end-1) {
      this.timeoutQueue.push(setTimeout(
        function(){self.playing = false; self.updateIcon();},
        ((i+1)-startIndex)*(speed-speed/8)*1000));
    }

  }
}

//PLay multiple lines at the same time. Takes in an array of lines and the start and end index.
//Not used in the application
AudioPlayer.prototype.playLines = function(lines, startIndex, endIndex) {
  if(this.isDirty) {
    this.recalculateLines();
  }

  for (var i = 0; i < lines.length; i++) {
    this.playLine(lines[i], startIndex, endIndex);
  }
}

//Play a single point
AudioPlayer.prototype.playPoint = function(line, point) {
  this.audio[line][point].play();
}

//This function is nessesary so that there is a seperate copy of the
//index for when the function is actualy called
AudioPlayer.prototype.playPointWithDelay = function(line, index, delay) {
  var self = this;
  this.timeoutQueue.push(setTimeout(function() {self.playPoint(line, index);}, delay));
}

//If there is anything left in the timeout queue then stop them from playing
AudioPlayer.prototype.stopPlaying = function() {
  for(var i = 0; i < this.timeoutQueue.length; i++) {
    clearTimeout(this.timeoutQueue[i]);
  }
  this.playing = false;
}

// Updates the play / stop icon.
AudioPlayer.prototype.updateIcon = function() {
  var iList = document.getElementById("icon").classList;
  if(this.playing) {
    iList.remove("fa-play");
    iList.add("fa-stop");
  }
  else {
    iList.remove("fa-stop");
    iList.add("fa-play");
  }
}
//Using the arrayinfo a wave array is created
AudioPlayer.prototype.genWaves = function(arrayInfo) {
  var audioLibParams = {};

  for(var i = 0; i < arrayInfo.array.length; i++) {
    audioLibParams[i] = this.genSoundArray(
      this.calcFrequency(
        arrayInfo.array[i],
        this.infoCollection.min,
        this.infoCollection.max
        ));
  }

  return audioLibParams;
}

//Converts the value to a frquency between the min and max frequnecy.
AudioPlayer.prototype.calcFrequency = function(value, min, max) {
  var freq = (((this.maxFreq-this.minFreq)*(value-min))/(max-min))+this.minFreq;
  freq = Math.pow(2,((freq-40)/12))*440;
  return freq;
}

//Creates a sound object
AudioPlayer.prototype.genSoundArray = function(frequency) {
  return ["sine",
  0.0000, //super sampling quality
  0.1750, //master volume
  this.duration*0.013, //attack time
  this.duration*0.13, //sustain time
  0.0000, //sustain punch
  this.duration*0.86, //decay time
  20.0000, //min frequency
  frequency, //This is the frequency
  2400.0000, //max frequency
  0.0000, //slide
  0.0000, //delta slide
  0.0250, //vibrato slide
  45.0000, //vibrato frequency
  -0.3000, //vibrato depth slide
  -1.0000, //vibrato frequency slide
  0.0000, //change amount
  0.0000, //change speed
  0.0000, //square duty
  0.0000, //square duty sweep
  0.0000, //repeat speed
  0.0080, //phaser offset
  0.0000, //phaser sweep
  1.0000, //lp filter cutoff
  0.0040, //lp filter cutoff sweep
  0.0000, //lp filter resonance
  0.0000, //hp filter cutoff
  0.0100]; //hp filter cutoff sweep
}

//play the input array of audio data
//Used for debugging
var playNotes = function(notes) {
  this.sounds = [];
  for(var i = 0; i < notes.length; i++) {
    sounds[i] = jsfxlib.createWaves(notes);
  }

  for(var i = 0; i < notes.length; i++) {
    sounds[i][0].play();
  }
}
<commit_msg>Tried ethans solution and it didnt work. Lowered volume and increased frequency range instead. #10<commit_after>"use strict"; // strict mode syntax
//Creates a set of audio data from the provided arrayinfo
function AudioPlayer() {
  this.duration = 0.5; //default duration of a single note
  this.timeStep = 0.5;
  this.maxFreq = 64;
  this.minFreq = 16;
  this.audio = [];
  this.infoCollection = new ArrayCollection([]);
  this.isDirty = false;
  this.timeoutQueue = [];
  this.playing = false;
}

//Add a line to the collection used to calculate audio lines
AudioPlayer.prototype.addLine = function(arrayInfo) {
  this.infoCollection.addLine(arrayInfo);
}

//Add a single line to the audio player
AudioPlayer.prototype.addAudioLine = function(arrayInfo) {
  this.audio.push(jsfxlib.createWaves(this.genWaves(arrayInfo)));
}

//Using an arrayCollection object you can add a group of lines to the audio object
AudioPlayer.prototype.setCollection = function(collection) {
  var dropdownString ="";
  this.infoCollection.setCollection(collection);
  for(var i = 0; i < collection.length; i++) {
    dropdownString += "<option value="+(i + 1)+">"+(i + 1)+"</option>"
  }
  this.isDirty = true;
  document.getElementById("audioSpan").style.display = "";
  document.getElementById("lineDropdown").innerHTML = dropdownString;
}

//A change was made to a line in the table
AudioPlayer.prototype.changeLine = function(line, index, newValue) {
  if(line != -1) {
    this.infoCollection.changeLine(line,index,newValue);
    this.isDirty = true;
  }
}

//This function causes the audio information to actually be calculated.
//Should be called whenever the audio data changes
AudioPlayer.prototype.recalculateLines = function() {
  this.audio = [];
  for(var i = 0; i < this.infoCollection.collection.length; i++) {
    this.addAudioLine(this.infoCollection.collection[i]);
  }
  this.isDirty = false;
}

//Toggle playing either on or off
AudioPlayer.prototype.playToggle = function(line, startIndex, endIndex) {
  if(!this.playing) {
    this.playLine(line, startIndex, endIndex);
  }
  else {
    this.stopPlaying();
  }
  this.updateIcon();
}

//Play a line. can also have optional parameters for start and ending index
AudioPlayer.prototype.playLine = function(line, startIndex, endIndex) {
  //If the lines have been changed since the last time they
  //were played then recalculate them

  //Reset the timeout queue
  this.timeoutQueue = [];
  this.playing = true;

  if(this.isDirty) {
    this.recalculateLines();
  }
  var multiplier = document.getElementById("bpm").value;
  if(multiplier <= 0) {
    multiplier = 1;
  }
  var speed = this.timeStep/(multiplier || 1);

  var end = (endIndex || this.infoCollection.collection[line].array.length-1);
  var self = this;
  var startIndex = (startIndex || 0);
  //If startIndex or endIndex are undefined they will be set to the start and end of the line respectively
  for(var i = startIndex; i <= end; i++) {
    this.playPointWithDelay(line, i, (i-startIndex)*(speed-speed/8)*1000);

    if(i == end-1) {
      this.timeoutQueue.push(setTimeout(
        function(){self.playing = false; self.updateIcon();},
        ((i+1)-startIndex)*(speed-speed/8)*1000));
    }

  }
}

//PLay multiple lines at the same time. Takes in an array of lines and the start and end index.
//Not used in the application
AudioPlayer.prototype.playLines = function(lines, startIndex, endIndex) {
  if(this.isDirty) {
    this.recalculateLines();
  }

  for (var i = 0; i < lines.length; i++) {
    this.playLine(lines[i], startIndex, endIndex);
  }
}

//Play a single point
AudioPlayer.prototype.playPoint = function(line, point) {
  this.audio[line][point].play();
}

//This function is nessesary so that there is a seperate copy of the
//index for when the function is actualy called
AudioPlayer.prototype.playPointWithDelay = function(line, index, delay) {
  var self = this;
  this.timeoutQueue.push(setTimeout(function() {self.playPoint(line, index);}, delay));
}

//If there is anything left in the timeout queue then stop them from playing
AudioPlayer.prototype.stopPlaying = function() {
  for(var i = 0; i < this.timeoutQueue.length; i++) {
    clearTimeout(this.timeoutQueue[i]);
  }
  this.playing = false;
}

// Updates the play / stop icon.
AudioPlayer.prototype.updateIcon = function() {
  var iList = document.getElementById("icon").classList;
  if(this.playing) {
    iList.remove("fa-play");
    iList.add("fa-stop");
  }
  else {
    iList.remove("fa-stop");
    iList.add("fa-play");
  }
}
//Using the arrayinfo a wave array is created
AudioPlayer.prototype.genWaves = function(arrayInfo) {
  var audioLibParams = {};

  for(var i = 0; i < arrayInfo.array.length; i++) {
    audioLibParams[i] = this.genSoundArray(
      this.calcFrequency(
        arrayInfo.array[i],
        this.infoCollection.min,
        this.infoCollection.max
        ));
  }

  return audioLibParams;
}

//Converts the value to a frquency between the min and max frequnecy.
AudioPlayer.prototype.calcFrequency = function(value, min, max) {
  var freq = (((this.maxFreq-this.minFreq)*(value-min))/(max-min))+this.minFreq;
  freq = Math.pow(2,((freq-40)/12))*440;
  return freq;
}

//Creates a sound object
AudioPlayer.prototype.genSoundArray = function(frequency) {
  return ["sine",
  0.0000, //super sampling quality
  0.1500, //master volume
  this.duration*0.013, //attack time
  this.duration*0.13, //sustain time
  0.0000, //sustain punch
  this.duration*0.86, //decay time
  20.0000, //min frequency
  frequency, //This is the frequency
  2400.0000, //max frequency
  0.0000, //slide
  0.0000, //delta slide
  0.0250, //vibrato slide
  45.0000, //vibrato frequency
  -0.3000, //vibrato depth slide
  -1.0000, //vibrato frequency slide
  0.0000, //change amount
  0.0000, //change speed
  0.0000, //square duty
  0.0000, //square duty sweep
  0.0000, //repeat speed
  0.0080, //phaser offset
  0.0000, //phaser sweep
  1.0000, //lp filter cutoff
  0.0040, //lp filter cutoff sweep
  0.0000, //lp filter resonance
  0.0000, //hp filter cutoff
  0.0100]; //hp filter cutoff sweep
}

//play the input array of audio data
//Used for debugging
var playNotes = function(notes) {
  this.sounds = [];
  for(var i = 0; i < notes.length; i++) {
    sounds[i] = jsfxlib.createWaves(notes);
  }

  for(var i = 0; i < notes.length; i++) {
    sounds[i][0].play();
  }
}
<|endoftext|>


<commit_before>import extend from '../../utils/extend'

function paginationChanged (oldPag, newPag) {
  for (let prop in newPag) {
    if (newPag[prop] !== oldPag[prop]) {
      return true
    }
  }
  return false
}

function fixPagination (p) {
  if (p.page < 1) {
    p.page = 1
  }
  if (p.rowsPerPage !== void 0 && p.rowsPerPage < 1) {
    p.rowsPerPage = 5
  }
  return p
}

export default {
  props: {
    pagination: Object,
    rowsPerPageOptions: {
      type: Array,
      default: () => [3, 5, 7, 10, 15, 20, 25, 50, 0]
    }
  },
  data () {
    return {
      innerPagination: {
        sortBy: null,
        descending: false,
        page: 1,
        rowsPerPage: 5
      }
    }
  },
  computed: {
    computedPagination () {
      return fixPagination(extend({}, this.innerPagination, this.pagination))
    },
    firstRowIndex () {
      const { page, rowsPerPage } = this.computedPagination
      return (page - 1) * rowsPerPage
    },
    lastRowIndex () {
      const { page, rowsPerPage } = this.computedPagination
      return page * rowsPerPage
    },
    isFirstPage () {
      return this.computedPagination.page === 1
    },
    pagesNumber () {
      return Math.max(
        1,
        Math.ceil(this.computedRowsNumber / this.computedPagination.rowsPerPage)
      )
    },
    isLastPage () {
      if (this.lastRowIndex === 0) {
        return true
      }
      return this.computedPagination.page >= this.pagesNumber
    },
    computedRowsPerPageOptions () {
      return this.rowsPerPageOptions.map(count => ({
        label: count === 0 ? this.$q.i18n.table.allRows : '' + count,
        value: count
      }))
    }
  },
  watch: {
    pagesNumber (lastPage, oldLastPage) {
      if (lastPage === oldLastPage) {
        return
      }

      const currentPage = this.computedPagination.page
      if (lastPage && !currentPage) {
        this.setPagination({ page: 1 })
      }
      else if (lastPage < currentPage) {
        this.setPagination({ page: lastPage })
      }
    }
  },
  methods: {
    setPagination (val) {
      const newPagination = fixPagination(extend({}, this.computedPagination, val))

      if (!paginationChanged(this.computedPagination, newPagination)) {
        return
      }

      if (this.isServerSide) {
        this.requestServerInteraction({
          pagination: newPagination
        })
        return
      }

      if (this.pagination) {
        this.$emit('update:pagination', newPagination)
      }
      else {
        this.innerPagination = newPagination
      }
    },
    prevPage () {
      const { page } = this.computedPagination
      if (page > 1) {
        this.setPagination({page: page - 1})
      }
    },
    nextPage () {
      const { page, rowsPerPage } = this.computedPagination
      if (this.lastRowIndex > 0 && page * rowsPerPage < this.computedRowsNumber) {
        this.setPagination({page: page + 1})
      }
    }
  },
  created () {
    this.$emit('update:pagination', extend({}, this.computedPagination))
  }
}
<commit_msg>fix: Possible loop on datatable with server-side interaction #1834<commit_after>import extend from '../../utils/extend'

function paginationChanged (oldPag, newPag) {
  for (let prop in newPag) {
    if (newPag[prop] !== oldPag[prop]) {
      return true
    }
  }
  return false
}

function fixPagination (p) {
  if (p.page < 1) {
    p.page = 1
  }
  if (p.rowsPerPage !== void 0 && p.rowsPerPage < 1) {
    p.rowsPerPage = 0
  }
  return p
}

export default {
  props: {
    pagination: Object,
    rowsPerPageOptions: {
      type: Array,
      default: () => [3, 5, 7, 10, 15, 20, 25, 50, 0]
    }
  },
  data () {
    return {
      innerPagination: {
        sortBy: null,
        descending: false,
        page: 1,
        rowsPerPage: 5
      }
    }
  },
  computed: {
    computedPagination () {
      return fixPagination(extend({}, this.innerPagination, this.pagination))
    },
    firstRowIndex () {
      const { page, rowsPerPage } = this.computedPagination
      return (page - 1) * rowsPerPage
    },
    lastRowIndex () {
      const { page, rowsPerPage } = this.computedPagination
      return page * rowsPerPage
    },
    isFirstPage () {
      return this.computedPagination.page === 1
    },
    pagesNumber () {
      return Math.max(
        1,
        Math.ceil(this.computedRowsNumber / this.computedPagination.rowsPerPage)
      )
    },
    isLastPage () {
      if (this.lastRowIndex === 0) {
        return true
      }
      return this.computedPagination.page >= this.pagesNumber
    },
    computedRowsPerPageOptions () {
      return this.rowsPerPageOptions.map(count => ({
        label: count === 0 ? this.$q.i18n.table.allRows : '' + count,
        value: count
      }))
    }
  },
  watch: {
    pagesNumber (lastPage, oldLastPage) {
      if (lastPage === oldLastPage) {
        return
      }

      const currentPage = this.computedPagination.page
      if (lastPage && !currentPage) {
        this.setPagination({ page: 1 })
      }
      else if (lastPage < currentPage) {
        this.setPagination({ page: lastPage })
      }
    }
  },
  methods: {
    setPagination (val) {
      const newPagination = fixPagination(extend({}, this.computedPagination, val))

      if (!paginationChanged(this.computedPagination, newPagination)) {
        return
      }

      if (this.isServerSide) {
        this.requestServerInteraction({
          pagination: newPagination
        })
        return
      }

      if (this.pagination) {
        this.$emit('update:pagination', newPagination)
      }
      else {
        this.innerPagination = newPagination
      }
    },
    prevPage () {
      const { page } = this.computedPagination
      if (page > 1) {
        this.setPagination({page: page - 1})
      }
    },
    nextPage () {
      const { page, rowsPerPage } = this.computedPagination
      if (this.lastRowIndex > 0 && page * rowsPerPage < this.computedRowsNumber) {
        this.setPagination({page: page + 1})
      }
    }
  },
  created () {
    this.$emit('update:pagination', extend({}, this.computedPagination))
  }
}
<|endoftext|>


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

module.exports = Action;

function Action(options) {
    const fn = options.execute;
    if (typeof(fn) !== 'function')
        throw new InvalidExecuteFunctionError(fn);

    fn.cache = options.cache;
    fn.validator = options.validator;
    fn.criteriaBuilder = options.criteriaBuilder;

    fn.prepare = function () {
        const self = this;

        return (req, res) => {
            // 1. Generate a context from the middleware, req : res
            const context = new ContextBuilder(self.criteriaBuilder).build(req, res);

            // 2. If the action has been configured with a cache action
            // try to get the cache entry from the req's url.
            if (Action.cache && self.cache && self.cache.store) {
                const entry = Action.cache.get(req.originalUrl);
                if (entry)
                    return context._submit(entry);
            }
            // 3. else if the cache has been configured to bust some entries..
            else if (Action.cache && self.cache && self.cache.bust)
                Action.cache.remove(self.cache.bust);

            // >>> Idylle FLOW :
            // 1. Executing the action
            // 2. Setting a cache entry if configured to do so.
            // 3. Responding to the client.
            // 4. Handling the error and responding to the client.
            self(context)
                .then(setCache)
                .then(context._submit)
                .catch(res.error);

            function setCache(data) {
                if (Action.cache && self.cache && self.cache.store)
                    Action.cache.set(self.cache, req.originalUrl, data);

                return data;
            }
        };
    };

    fn.prepare = fn.prepare.bind(fn);

    return fn
}

function InvalidExecuteFunctionError(fn) {
    this.name = 'InvalidExecuteFunctionError';
    this.message = `expecting function got ${typeof fn}`
}

InvalidExecuteFunctionError.prototype = Object.create(Error.prototype);<commit_msg>renamed prepare() fn to execute()<commit_after>const ContextBuilder = require('./ContextBuilder');

module.exports = Action;

function Action(options) {
    const fn = options.execute;
    if (typeof(fn) !== 'function')
        throw new InvalidExecuteFunctionError(fn);

    fn.cache = options.cache;
    fn.validator = options.validator;
    fn.criteriaBuilder = options.criteriaBuilder;

    fn.expose = function () {
        const self = this;

        return (req, res) => {
            // 1. Generate a context from the middleware, req : res
            const context = new ContextBuilder(self.criteriaBuilder).build(req, res);

            // 2. If the action has been configured with a cache action
            // try to get the cache entry from the req's url.
            if (Action.cache && self.cache && self.cache.store) {
                const entry = Action.cache.get(req.originalUrl);
                if (entry)
                    return context._submit(entry);
            }
            // 3. else if the cache has been configured to bust some entries..
            else if (Action.cache && self.cache && self.cache.bust)
                Action.cache.remove(self.cache.bust);

            // >>> Idylle FLOW :
            // 1. Executing the action
            // 2. Setting a cache entry if configured to do so.
            // 3. Responding to the client.
            // 4. Handling the error and responding to the client.
            self(context)
                .then(setCache)
                .then(context._submit)
                .catch(res.error);

            function setCache(data) {
                if (Action.cache && self.cache && self.cache.store)
                    Action.cache.set(self.cache, req.originalUrl, data);

                return data;
            }
        };
    };

    fn.expose = fn.expose.bind(fn);

    return fn
}

function InvalidExecuteFunctionError(fn) {
    this.name = 'InvalidExecuteFunctionError';
    this.message = `expecting function got ${typeof fn}`
}

InvalidExecuteFunctionError.prototype = Object.create(Error.prototype);<|endoftext|>


<commit_before>/*
 * ------------------------------------------------------------------
	AJAX for using the Open Context API
 * ------------------------------------------------------------------
*/

function OpenContextAPI() {
	/* Object for runing searches + displaying results from Open Context */
	this.name = "opencontext"; //object name, used for DOM-ID prefixes and object labeling
	this.api_url = false;
	this.data = false;
	this.facets_dom_id = 'facets';
	this.filters_dom_id = 'filters';

	/* This is for a Lealet Map, which displays geospatial data from the search */
	this.map_dom_id = 'map';
	map = L.map(this.map_dom_id);
	this.bounds = new L.LatLngBounds();
	var osmTiles = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		attribution: '© OpenStreetMap contributors'
	});
	var ESRISatelliteTiles = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
		attribution: '© ESRI.com '
	});
	var baseMaps = {
		"ESRI-Satellite": ESRISatelliteTiles,
		"OpenStreetMap": osmTiles,
	};
	map._layersMaxZoom = 20;
	var layerControl = L.control.layers(baseMaps).addTo(map);
	map.addLayer(osmTiles);
	map.oc_layer = false;
	map.render_region_layer = function(data){
		// this can get much more elaborate to add style
		// and callouts for map layers, but it's a first stab
		if (map.oc_layer != false) {
			map.removeLayer(map.oc_layer);
		}
		var region_layer = L.geoJson(data);
		map.fitBounds(region_layer.getBounds());
		region_layer.addTo(map);
		map.oc_layer = region_layer;
	}
	this.map = map;
	this.get_data = function() {
		// calls the Open Context API to get data
		var url = this.api_url;
		if (url != false) {
			return $.ajax({
				type: "GET",
				url: url,
				dataType: "json",
				headers: {
					//added to get JSON data (content negotiation)
					Accept : "application/json; charset=utf-8"
				},
				context: this,
				success: this.get_dataDone, //do this when we get data w/o problems
				error: this.get_dataError //error message display
			});
		}
	}
	this.get_dataDone = function(data){
		// function to display results of a request for data
		this.data = data;
		console.log(data);
		// show facets + facet values
		this.show_facets();
		// show filters on the data
		//this.show_filters();
		// now show the geojson data using the Leaflet Map
		this.map.render_region_layer(data);
	}
	this.show_facets = function(){
		var act_dom = this.get_facets_dom();
		if (act_dom != false) {
			var html = '';
			var data = this.data;
			if ('totalResults' in data) {
				// show the total number of records found
				html += '
Open Context Records: ' + data['totalResults'] + '
';
			}
			if ('oc-api:has-facets' in data) {
				// show some search facets
				for (var i = 0, length = data['oc-api:has-facets'].length; i < length; i++) {
					var facet = data['oc-api:has-facets'][i];
					var facet_html = '
'
					facet_html += '
';
					facet_html += '
' + facet.label + '
'
					//use another function to make facet search values
					facet_html += this.make_facet_values_html(facet);
					facet_html += '
';
					facet_html += '
';
					html += facet_html;
				}
			}
			act_dom.innerHTML = html;
		}
	}
	this.make_facet_values_html = function(facet){
		var value_list = [];
		var html_list = [];
		if ('oc-api:has-id-options' in facet) {
			var value_list = facet['oc-api:has-id-options'];
		}
		else{
			var value_list = [];
		}
		for (var i = 0, length = value_list.length; i < length; i++) {
			var val_item = value_list[i];
			var val_html = this.make_facet_val_link(val_item) + ' (' + val_item.count + ')';
			html_list.push(val_html);
		}
		var html = html_list.join(', ');
		return html;
	}
	this.make_facet_val_link = function(val_item){
		var html = '';
		html += val_item.label;
		html += '';
		return html;
	}
	this.show_filters = function(){
		// function to display filers as needed
		var act_dom = this.get_filters_dom();
		if (act_dom != false) {
			// we've got a dom place to add filters too
			var data = this.data;
			if ('oc-api:active-filters' in data) {
				// the data has filters
				html += '
';
				html += '
Filters on the data
';
				html += '
';
				for (var i = 0, length = data['oc-api:active-filters'].length; i < length; i++) {
					var filter = data['oc-api:active-filters'][i];
					html += this.make_filter_html(filter);
				}
				html += '
';
				html += '
';
				act_dom.innerHTML = html;
			}
		}
	}
	this.make_filter_html = function(filter){
		var html = '
';
		html += '';
		html += filter.label;
		html += '
';
		return html;
	}
	this.change = function(change_url){
		// this function is executed when a user clicks on a link
		// to add a filter or remove a filter
		this.change_frag_id(change_url);
		this.api_url = change_url;
		this.get_data();
	}
	this.change_frag_id = function(new_frag){
		window.location.hash = new_frag;
	}
	this.get_dataError = function(){
		var act_dom = this.get_facets_dom();
		if (act_dom != false) {
			var html = [
			'
',
			'',
			'Failed to load valid data from Open Context.',
			'
'
			].join(' ');
			act_dom.innerHTML = html;
		}
	}
	this.get_facets_dom = function(){
		var act_dom = false;
		if (this.facets_dom_id != false) {
			if (document.getElementById(this.facets_dom_id)) {
				act_dom = document.getElementById(this.facets_dom_id);
			}
		}
		return act_dom;
	}
	this.get_filters_dom = function(){
		var act_dom = false;
		if (this.filters_dom_id != false) {
			if (document.getElementById(this.filters_dom_id)) {
				act_dom = document.getElementById(this.filters_dom_id);
			}
		}
		return act_dom;
	}
}
<commit_msg>use state to get api url<commit_after>/*
 * ------------------------------------------------------------------
	AJAX for using the Open Context API
 * ------------------------------------------------------------------
*/

function OpenContextAPI() {
	/* Object for runing searches + displaying results from Open Context */
	this.name = "opencontext"; //object name, used for DOM-ID prefixes and object labeling
	this.api_url = false;
	this.data = false;
	this.facets_dom_id = 'facets';
	this.filters_dom_id = 'filters';

	/* This is for a Lealet Map, which displays geospatial data from the search */
	this.map_dom_id = 'map';
	map = L.map(this.map_dom_id);
	this.bounds = new L.LatLngBounds();
	var osmTiles = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		attribution: '© OpenStreetMap contributors'
	});
	var ESRISatelliteTiles = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
		attribution: '© ESRI.com '
	});
	var baseMaps = {
		"ESRI-Satellite": ESRISatelliteTiles,
		"OpenStreetMap": osmTiles,
	};
	map._layersMaxZoom = 20;
	var layerControl = L.control.layers(baseMaps).addTo(map);
	map.addLayer(osmTiles);
	map.oc_layer = false;
	map.render_region_layer = function(data){
		// this can get much more elaborate to add style
		// and callouts for map layers, but it's a first stab
		if (map.oc_layer != false) {
			map.removeLayer(map.oc_layer);
		}
		var region_layer = L.geoJson(data);
		map.fitBounds(region_layer.getBounds());
		region_layer.addTo(map);
		map.oc_layer = region_layer;
	}
	this.map = map;
	this.get_data = function() {
		// calls the Open Context API to get data
		var url = this.get_api_url();
		if (url != false) {
			return $.ajax({
				type: "GET",
				url: url,
				dataType: "json",
				headers: {
					//added to get JSON data (content negotiation)
					Accept : "application/json; charset=utf-8"
				},
				context: this,
				success: this.get_dataDone, //do this when we get data w/o problems
				error: this.get_dataError //error message display
			});
		}
	}
	this.get_api_url = function(){
		var url = this.api_url;
		var hash = window.location.hash;
		if (hash) {
			url = hash;
		}
		return url;
	}
	this.get_dataDone = function(data){
		// function to display results of a request for data
		this.data = data;
		console.log(data);
		// show facets + facet values
		this.show_facets();
		// show filters on the data
		//this.show_filters();
		// now show the geojson data using the Leaflet Map
		this.map.render_region_layer(data);
	}
	this.show_facets = function(){
		var act_dom = this.get_facets_dom();
		if (act_dom != false) {
			var html = '';
			var data = this.data;
			if ('totalResults' in data) {
				// show the total number of records found
				html += '
Open Context Records: ' + data['totalResults'] + '
';
			}
			if ('oc-api:has-facets' in data) {
				// show some search facets
				for (var i = 0, length = data['oc-api:has-facets'].length; i < length; i++) {
					var facet = data['oc-api:has-facets'][i];
					var facet_html = '
'
					facet_html += '
';
					facet_html += '
' + facet.label + '
'
					//use another function to make facet search values
					facet_html += this.make_facet_values_html(facet);
					facet_html += '
';
					facet_html += '
';
					html += facet_html;
				}
			}
			act_dom.innerHTML = html;
		}
	}
	this.make_facet_values_html = function(facet){
		var value_list = [];
		var html_list = [];
		if ('oc-api:has-id-options' in facet) {
			var value_list = facet['oc-api:has-id-options'];
		}
		else{
			var value_list = [];
		}
		for (var i = 0, length = value_list.length; i < length; i++) {
			var val_item = value_list[i];
			var val_html = this.make_facet_val_link(val_item) + ' (' + val_item.count + ')';
			html_list.push(val_html);
		}
		var html = html_list.join(', ');
		return html;
	}
	this.make_facet_val_link = function(val_item){
		var html = '';
		html += val_item.label;
		html += '';
		return html;
	}
	this.show_filters = function(){
		// function to display filers as needed
		var act_dom = this.get_filters_dom();
		if (act_dom != false) {
			// we've got a dom place to add filters too
			var data = this.data;
			if ('oc-api:active-filters' in data) {
				// the data has filters
				html += '
';
				html += '
Filters on the data
';
				html += '
';
				for (var i = 0, length = data['oc-api:active-filters'].length; i < length; i++) {
					var filter = data['oc-api:active-filters'][i];
					html += this.make_filter_html(filter);
				}
				html += '
';
				html += '
';
				act_dom.innerHTML = html;
			}
		}
	}
	this.make_filter_html = function(filter){
		var html = '
';
		html += '';
		html += filter.label;
		html += '
';
		return html;
	}
	this.change = function(change_url){
		// this function is executed when a user clicks on a link
		// to add a filter or remove a filter
		this.change_frag_id(change_url);
		this.api_url = change_url;
		this.get_data();
	}
	this.change_frag_id = function(new_frag){
		window.location.hash = new_frag;
	}
	this.get_dataError = function(){
		var act_dom = this.get_facets_dom();
		if (act_dom != false) {
			var html = [
			'
',
			'',
			'Failed to load valid data from Open Context.',
			'
'
			].join(' ');
			act_dom.innerHTML = html;
		}
	}
	this.get_facets_dom = function(){
		var act_dom = false;
		if (this.facets_dom_id != false) {
			if (document.getElementById(this.facets_dom_id)) {
				act_dom = document.getElementById(this.facets_dom_id);
			}
		}
		return act_dom;
	}
	this.get_filters_dom = function(){
		var act_dom = false;
		if (this.filters_dom_id != false) {
			if (document.getElementById(this.filters_dom_id)) {
				act_dom = document.getElementById(this.filters_dom_id);
			}
		}
		return act_dom;
	}
}
<|endoftext|>


<commit_before>var path = require('path'),
	fs = require('fs'),
	leaves = require('./leaves'),
	woods = require('./woods'),
	Tree = require('./Tree'),
	Showdown = require('showdown'),
	converter = new Showdown.converter();

var addResources = function(branch) {
	var routeUrl = path.join(branch.getUrl(), 'resources');
	console.log('Adding static route:', routeUrl);
	// that.tree.express.use(routeUrl, express.static(file));
	// Add resources and images:
	var images = branch.images = [];
	var resources = branch.resources = [];
	var resourcesDir = path.join(branch.getUri(), 'resources');
	if (!fs.existsSync(resourcesDir))
		return;
	fs.readdir(resourcesDir, function(err, files) {
		files.forEach(function(file) {
			if (/jpg|jpeg|png|gif/.test(file)) {
				images.push(file);
			} else {
				resources.push(file);
			}
		});
	});
};

var addChildren = function(branch) {
	// Read the directory and add child branches (if any):
	var children = branch.children = [];
	var uri = branch.getUri();
	var files = fs.readdirSync(uri);
	var index = 0;
	for (var i in files) {
		var file = path.resolve(uri, files[i]);
		var name = path.basename(file);
		var isDirectory = fs.statSync(file).isDirectory();
		if (isDirectory && !Branch.nameIsReserved(name)) {
			var isChild = /^[0-9]+\-/.test(name);
			var childBranch = new Branch(branch.tree, branch, path.relative(uri, file));
			childBranch.index = index++;
			// Only add to children list if it is a child
			// - i.e. its name starts in the style of: 01- or 02-
			if (isChild)
				children.push(childBranch);
		}
	}
};

var parseContent = function(branch) {
	// Parse the content file and place values in branch.data:
	branch.data = {};
	var contentPath = branch.getUri() + '/content.md';
	leaves.parse(contentPath, branch);
};

var installRoute = function(branch) {
	console.log('Installing route: ' + branch.urlPath);

	// Install the path in express:
	woods.express.get(branch.urlPath, function(req, res) {
		var template = branch.getTemplateLocation('html');
		res.render(template, {
			title: branch.data.title,
			text: branch.data.text || '',
			css: branch.tree.getUri() + 'static/styles/styles.css',
			branch: branch,
			parse: function(content, param) {
				return converter.makeHtml(content);
			},
			bodyTemplate: 'body'
		});
	});
};

var Branch = function(tree, parent, directory) {
	var that = this;
	this.tree = tree;
	if (parent)
		this.parent = parent;
	this.directory = directory;
	// Remove the numbers in the path, since they are only used for order:
	this.urlPath = this.getUrl()
		.replace(/\/[0-9]+\-/g, '/')
		.replace(/\s/g, '-');
	tree.branchByUrl[this.urlPath] = this;
	this.name = this.path == '/'
			? 'root'
			: path.basename(this.urlPath).replace(/\/$/, '');

	installRoute(this);
	addChildren(this);
	addResources(this);
	parseContent(this);
};

Branch.prototype.getTemplate = function(name) {
	return this.data.type && this.tree.types[this.data.type][name]
		? this.tree.types[this.data.type][name]
		: this.tree.types.default[name] || function(param) {
			return 'Template not found: ' + name;
		};
};

Branch.prototype.getTemplateLocation = function(name) {
	var templateLocations = this.tree.templateLocations,
		type = this.data.type;
		console.log(templateLocations);
	return this.data.type && templateLocations[type][name]
		? templateLocations[type][name]
		: templateLocations.default[name];
};

Branch.prototype.renderTemplate = function(name) {
	return this.getTemplate(name)({
		branch: this,
		parse: function(content, param) {
			return converter.makeHtml(content);
		}
	});
};

Branch.prototype.getUri = function(url) {
	var uri = this.directory,
		parent = this.parent;
	while (parent) {
		uri = path.join(parent.directory, uri);
		parent = parent.parent;
	}
	var tree = url ? this.tree.getUrl() : this.tree.getUri('content');
	var resolved = path.resolve(tree, uri);
	return resolved;
};

Branch.prototype.getUrl = function() {
	if (!this._url)
		this._url = this.getUri(true).replace(/\/[0-9]+-/g,'/')
				.replace(/\s/g, '-');
	return this._url;
};

var reservedNames = {resources: true, error: true, home: true};
Branch.nameIsReserved = function(name) {
	return !!name && !!reservedNames[name];
};

module.exports = Branch;<commit_msg>Branch: move around a few things.<commit_after>var path = require('path'),
	fs = require('fs'),
	leaves = require('./leaves'),
	woods = require('./woods'),
	Tree = require('./Tree'),
	Showdown = require('showdown'),
	converter = new Showdown.converter();

var Branch = function(tree, parent, directory) {
	var that = this;
	this.tree = tree;
	if (parent)
		this.parent = parent;
	this.directory = directory;
	// Remove the numbers in the path, since they are only used for order:
	this.urlPath = this.getUrl()
		.replace(/\/[0-9]+\-/g, '/')
		.replace(/\s/g, '-');
	tree.branchByUrl[this.urlPath] = this;
	this.name = this.path == '/'
			? 'root'
			: path.basename(this.urlPath).replace(/\/$/, '');

	installRoute(this);
	addChildren(this);
	addResources(this);
	parseContent(this);
};

Branch.prototype.getTemplate = function(name) {
	return this.data.type && this.tree.types[this.data.type][name]
		? this.tree.types[this.data.type][name]
		: this.tree.types.default[name] || function(param) {
			return 'Template not found: ' + name;
		};
};

Branch.prototype.getTemplateLocation = function(name) {
	var templateLocations = this.tree.templateLocations,
		type = this.data.type;
		console.log(templateLocations);
	return this.data.type && templateLocations[type][name]
		? templateLocations[type][name]
		: templateLocations.default[name];
};

Branch.prototype.renderTemplate = function(name) {
	return this.getTemplate(name)({
		branch: this,
		parse: function(content, param) {
			return converter.makeHtml(content);
		}
	});
};

Branch.prototype.getUri = function(url) {
	var uri = this.directory,
		parent = this.parent;
	while (parent) {
		uri = path.join(parent.directory, uri);
		parent = parent.parent;
	}
	var tree = url ? this.tree.getUrl() : this.tree.getUri('content');
	var resolved = path.resolve(tree, uri);
	return resolved;
};

Branch.prototype.getUrl = function() {
	if (!this._url)
		this._url = this.getUri(true).replace(/\/[0-9]+-/g,'/')
				.replace(/\s/g, '-');
	return this._url;
};

var reservedNames = {resources: true, error: true, home: true};
Branch.nameIsReserved = function(name) {
	return !!name && !!reservedNames[name];
};

var addResources = function(branch) {
	var routeUrl = path.join(branch.getUrl(), 'resources');
	console.log('Adding static route:', routeUrl);
	// that.tree.express.use(routeUrl, express.static(file));
	// Add resources and images:
	var images = branch.images = [];
	var resources = branch.resources = [];
	var resourcesDir = path.join(branch.getUri(), 'resources');
	if (!fs.existsSync(resourcesDir))
		return;
	fs.readdir(resourcesDir, function(err, files) {
		files.forEach(function(file) {
			if (/jpg|jpeg|png|gif/.test(file)) {
				images.push(file);
			} else {
				resources.push(file);
			}
		});
	});
};

var addChildren = function(branch) {
	// Read the directory and add child branches (if any):
	var children = branch.children = [];
	var uri = branch.getUri();
	var files = fs.readdirSync(uri);
	var index = 0;
	for (var i in files) {
		var file = path.resolve(uri, files[i]);
		var name = path.basename(file);
		var isDirectory = fs.statSync(file).isDirectory();
		if (isDirectory && !Branch.nameIsReserved(name)) {
			var isChild = /^[0-9]+\-/.test(name);
			var childBranch = new Branch(branch.tree, branch, path.relative(uri, file));
			childBranch.index = index++;
			// Only add to children list if it is a child
			// - i.e. its name starts in the style of: 01- or 02-
			if (isChild)
				children.push(childBranch);
		}
	}
};

var parseContent = function(branch) {
	// Parse the content file and place values in branch.data:
	branch.data = {};
	var contentPath = branch.getUri() + '/content.md';
	leaves.parse(contentPath, branch);
};

var installRoute = function(branch) {
	console.log('Installing route: ' + branch.urlPath);

	// Install the path in express:
	woods.express.get(branch.urlPath, function(req, res) {
		var template = branch.getTemplateLocation('html');
		res.render(template, {
			title: branch.data.title,
			text: branch.data.text || '',
			css: branch.tree.getUri() + 'static/styles/styles.css',
			branch: branch,
			parse: function(content, param) {
				return converter.makeHtml(content);
			},
			bodyTemplate: 'body'
		});
	});
};

module.exports = Branch;<|endoftext|>


<commit_before>'use babel';

import RequireJsSortView from './require-js-sort-view';
import { CompositeDisposable } from 'atom';

// const GadgetAukro = require("app/ui/page-hp/components/main-content/gadget-layout/gadget-aukro/gadget-aukro.jsx");
// const GadgetEmail = require("app/ui/page-hp/components/main-content/gadget-layout/gadget-email/gadget-email.jsx");

const commonSplitters = [
    'require("',
    'from "',
];
const LINE_SPLITTER = '\n';

export default {

  requireJsSortView: null,
  modalPanel: null,
  subscriptions: null,

  activate(state) {
    this.requireJsSortView = new RequireJsSortView(state.requireJsSortViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.requireJsSortView.getElement(),
      visible: false
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'require-js-sort:sort': () => this.sort()
    }));
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.requireJsSortView.destroy();
  },

  serialize() {
    return {
      requireJsSortViewState: this.requireJsSortView.serialize()
    };
  },

  sort() {
    let editor;
    if (editor = atom.workspace.getActiveTextEditor()) {
        let text = editor.getSelectedText();
        let lines = text.split(LINE_SPLITTER);

        lines = lines
            .map((line) => {
                let usedSplitterIndex = commonSplitters.findIndex((splitter) => {
                    return line.indexOf(splitter) > -1;
                })

                let config = line.split(commonSplitters[usedSplitterIndex]);

                if (config.length < 2) {
                    return;
                }
                config.push(usedSplitterIndex);
                console.log("config", config);
                return config;
            })
            .sort((a, b) => {
                console.log(a, b);
                let first = a[1].toLowerCase();
                let second = b[1].toLowerCase();

                if (first < second) {
                    return -1;
                } else if (first > second) {
                    return 1;
                }

                return 0;
            })
            .map((line) => {
                if (!line) {
                    return;
                }
                console.log(line);
                let usedSplitterIndex = line.splice(-1);
                console.log(line, usedSplitterIndex);
                return line.join(commonSplitters[usedSplitterIndex]);
            });

        text = lines.join(LINE_SPLITTER);
        editor.insertText(text);
    }
  }

};
<commit_msg>removed logging<commit_after>'use babel';

import RequireJsSortView from './require-js-sort-view';
import { CompositeDisposable } from 'atom';

// const GadgetAukro = require("app/ui/page-hp/components/main-content/gadget-layout/gadget-aukro/gadget-aukro.jsx");
// const GadgetEmail = require("app/ui/page-hp/components/main-content/gadget-layout/gadget-email/gadget-email.jsx");

const commonSplitters = [
    'require("',
    'from "',
];
const LINE_SPLITTER = '\n';

export default {

  requireJsSortView: null,
  modalPanel: null,
  subscriptions: null,

  activate(state) {
    this.requireJsSortView = new RequireJsSortView(state.requireJsSortViewState);
    this.modalPanel = atom.workspace.addModalPanel({
      item: this.requireJsSortView.getElement(),
      visible: false
    });

    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'require-js-sort:sort': () => this.sort()
    }));
  },

  deactivate() {
    this.modalPanel.destroy();
    this.subscriptions.dispose();
    this.requireJsSortView.destroy();
  },

  serialize() {
    return {
      requireJsSortViewState: this.requireJsSortView.serialize()
    };
  },

  sort() {
    let editor;
    if (editor = atom.workspace.getActiveTextEditor()) {
        let text = editor.getSelectedText();
        let lines = text.split(LINE_SPLITTER);

        lines = lines
            .map((line) => {
                let usedSplitterIndex = commonSplitters.findIndex((splitter) => {
                    return line.indexOf(splitter) > -1;
                })

                let config = line.split(commonSplitters[usedSplitterIndex]);
                if (config.length < 2) {
                    return;
                }
                config.push(usedSplitterIndex);
                return config;
            })
            .sort((a, b) => {
                let first = a[1].toLowerCase();
                let second = b[1].toLowerCase();

                if (first < second) {
                    return -1;
                } else if (first > second) {
                    return 1;
                }

                return 0;
            })
            .map((line) => {
                if (!line) {
                    return;
                }
                let usedSplitterIndex = line.splice(-1);
                return line.join(commonSplitters[usedSplitterIndex]);
            });

        text = lines.join(LINE_SPLITTER);
        editor.insertText(text);
    }
  }

};
<|endoftext|>