<commit_before>module.exports = HeapCallStore;

function HeapCallStore() {
	var calls = [];

	this.record = function record(thisBinding, callArguments, onExecuted) {
		calls.push({
			thisBinding: thisBinding,
			callArguments : callArguments,
			onExecuted : onExecuted
		});
	};

	this.getCalls = function getCalls() {
		return calls.slice(0); // clone
	};
}<commit_msg>IDEA gets confused and thinks I'm coercing an array to a 'clone' type<commit_after>module.exports = HeapCallStore;

function HeapCallStore() {
	var calls = [];

	this.record = function record(thisBinding, callArguments, onExecuted) {
		calls.push({
			thisBinding: thisBinding,
			callArguments : callArguments,
			onExecuted : onExecuted
		});
	};

	this.getCalls = function getCalls() {
		// Use slice to clone
		return calls.slice(0);
	};
}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { setTransform, isTransformSupported } from './utils';

export function getScroll(w, top) {
  let ret = w[`page${top ? 'Y' : 'X'}Offset`];
  const method = `scroll${top ? 'Top' : 'Left'}`;
  if (typeof ret !== 'number') {
    const d = w.document;
    // ie6,7,8 standard mode
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      // quirks mode
      ret = d.body[method];
    }
  }
  return ret;
}

function offset(elem) {
  let box;
  let x;
  let y;
  const doc = elem.ownerDocument;
  const body = doc.body;
  const docElem = doc && doc.documentElement;
  box = elem.getBoundingClientRect();
  x = box.left;
  y = box.top;
  x -= docElem.clientLeft || body.clientLeft || 0;
  y -= docElem.clientTop || body.clientTop || 0;
  const w = doc.defaultView || doc.parentWindow;
  x += getScroll(w);
  y += getScroll(w, true);
  return {
    left: x, top: y,
  };
}

function componentDidUpdate(component, init) {
  const { styles } = component.props;
  const rootNode = component.props.getRef('root');
  const wrapNode = component.props.getRef('nav') || rootNode;
  const containerOffset = offset(wrapNode);
  const inkBarNode = component.props.getRef('inkBar');
  const activeTab = component.props.getRef('activeTab');
  const inkBarNodeStyle = inkBarNode.style;
  const tabBarPosition = component.props.tabBarPosition;
  if (init) {
    // prevent mount animation
    inkBarNodeStyle.display = 'none';
  }
  if (activeTab) {
    const tabNode = activeTab;
    const tabOffset = offset(tabNode);
    const transformSupported = isTransformSupported(inkBarNodeStyle);
    if (tabBarPosition === 'top' || tabBarPosition === 'bottom') {
      let left = tabOffset.left - containerOffset.left;
      let width = tabNode.offsetWidth;

      // If tabNode'width width equal to wrapNode'width when tabBarPosition is top or bottom
      // It means no css working, then ink bar should not have width until css is loaded
      // Fix https://github.com/ant-design/ant-design/issues/7564
      if (width === rootNode.offsetWidth) {
        width = 0;
      } else if (styles.inkBar && styles.inkBar.width !== undefined) {
        width = parseFloat(styles.inkBar.width, 10);
        if (width) {
          left = left + (tabNode.offsetWidth - width) / 2;
        }
      }
      // use 3d gpu to optimize render
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`);
        inkBarNodeStyle.width = `${width}px`;
        inkBarNodeStyle.height = '';
      } else {
        inkBarNodeStyle.left = `${left}px`;
        inkBarNodeStyle.top = '';
        inkBarNodeStyle.bottom = '';
        inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - width}px`;
      }
    } else {
      let top = tabOffset.top - containerOffset.top;
      let height = tabNode.offsetHeight;
      if (styles.inkBar && styles.inkBar.height !== undefined) {
        height = parseFloat(styles.inkBar.height, 10);
        if (height) {
          top = top + (tabNode.offsetHeight - height) / 2;
        }
      }
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`);
        inkBarNodeStyle.height = `${height}px`;
        inkBarNodeStyle.width = '';
      } else {
        inkBarNodeStyle.left = '';
        inkBarNodeStyle.right = '';
        inkBarNodeStyle.top = `${top}px`;
        inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - height}px`;
      }
    }
  }
  inkBarNodeStyle.display = activeTab ? 'block' : 'none';
}

export default class InkTabBarNode extends React.Component {
  componentDidMount() {
    // ref https://github.com/ant-design/ant-design/issues/8678
    // ref https://github.com/ant-design/ant-design/issues/11612
    // InkTabBarNode need parent/root ref for calculating position
    // since parent componentDidMount triggered after child componentDidMount
    // we're doing a quick fix here to use setTimeout to calculate position
    // after parent/root component mounted
    this.timeout = setTimeout(() => {
      componentDidUpdate(this, true);
    }, 0);
  }

  componentDidUpdate() {
    componentDidUpdate(this);
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

  render() {
    const { prefixCls, styles, inkBarAnimated } = this.props;
    const className = `${prefixCls}-ink-bar`;
    const classes = classnames({
      [className]: true,
      [
        inkBarAnimated ?
          `${className}-animated` :
          `${className}-no-animated`
        ]: true,
    });
    return (
      <div
        style={styles.inkBar}
        className={classes}
        key="inkBar"
        ref={this.props.saveRef('inkBar')}
      />
    );
  }
}

InkTabBarNode.propTypes = {
  prefixCls: PropTypes.string,
  styles: PropTypes.object,
  inkBarAnimated: PropTypes.bool,
  saveRef: PropTypes.func,
};

InkTabBarNode.defaultProps = {
  prefixCls: '',
  inkBarAnimated: true,
  styles: {},
  saveRef: () => {},
};
<commit_msg>chore: update issue link<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { setTransform, isTransformSupported } from './utils';

export function getScroll(w, top) {
  let ret = w[`page${top ? 'Y' : 'X'}Offset`];
  const method = `scroll${top ? 'Top' : 'Left'}`;
  if (typeof ret !== 'number') {
    const d = w.document;
    // ie6,7,8 standard mode
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      // quirks mode
      ret = d.body[method];
    }
  }
  return ret;
}

function offset(elem) {
  let box;
  let x;
  let y;
  const doc = elem.ownerDocument;
  const body = doc.body;
  const docElem = doc && doc.documentElement;
  box = elem.getBoundingClientRect();
  x = box.left;
  y = box.top;
  x -= docElem.clientLeft || body.clientLeft || 0;
  y -= docElem.clientTop || body.clientTop || 0;
  const w = doc.defaultView || doc.parentWindow;
  x += getScroll(w);
  y += getScroll(w, true);
  return {
    left: x, top: y,
  };
}

function componentDidUpdate(component, init) {
  const { styles } = component.props;
  const rootNode = component.props.getRef('root');
  const wrapNode = component.props.getRef('nav') || rootNode;
  const containerOffset = offset(wrapNode);
  const inkBarNode = component.props.getRef('inkBar');
  const activeTab = component.props.getRef('activeTab');
  const inkBarNodeStyle = inkBarNode.style;
  const tabBarPosition = component.props.tabBarPosition;
  if (init) {
    // prevent mount animation
    inkBarNodeStyle.display = 'none';
  }
  if (activeTab) {
    const tabNode = activeTab;
    const tabOffset = offset(tabNode);
    const transformSupported = isTransformSupported(inkBarNodeStyle);
    if (tabBarPosition === 'top' || tabBarPosition === 'bottom') {
      let left = tabOffset.left - containerOffset.left;
      let width = tabNode.offsetWidth;

      // If tabNode'width width equal to wrapNode'width when tabBarPosition is top or bottom
      // It means no css working, then ink bar should not have width until css is loaded
      // Fix https://github.com/ant-design/ant-design/issues/7564
      if (width === rootNode.offsetWidth) {
        width = 0;
      } else if (styles.inkBar && styles.inkBar.width !== undefined) {
        width = parseFloat(styles.inkBar.width, 10);
        if (width) {
          left = left + (tabNode.offsetWidth - width) / 2;
        }
      }
      // use 3d gpu to optimize render
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`);
        inkBarNodeStyle.width = `${width}px`;
        inkBarNodeStyle.height = '';
      } else {
        inkBarNodeStyle.left = `${left}px`;
        inkBarNodeStyle.top = '';
        inkBarNodeStyle.bottom = '';
        inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - width}px`;
      }
    } else {
      let top = tabOffset.top - containerOffset.top;
      let height = tabNode.offsetHeight;
      if (styles.inkBar && styles.inkBar.height !== undefined) {
        height = parseFloat(styles.inkBar.height, 10);
        if (height) {
          top = top + (tabNode.offsetHeight - height) / 2;
        }
      }
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`);
        inkBarNodeStyle.height = `${height}px`;
        inkBarNodeStyle.width = '';
      } else {
        inkBarNodeStyle.left = '';
        inkBarNodeStyle.right = '';
        inkBarNodeStyle.top = `${top}px`;
        inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - height}px`;
      }
    }
  }
  inkBarNodeStyle.display = activeTab ? 'block' : 'none';
}

export default class InkTabBarNode extends React.Component {
  componentDidMount() {
    // ref https://github.com/ant-design/ant-design/issues/8678
    // ref https://github.com/react-component/tabs/issues/135
    // InkTabBarNode need parent/root ref for calculating position
    // since parent componentDidMount triggered after child componentDidMount
    // we're doing a quick fix here to use setTimeout to calculate position
    // after parent/root component mounted
    this.timeout = setTimeout(() => {
      componentDidUpdate(this, true);
    }, 0);
  }

  componentDidUpdate() {
    componentDidUpdate(this);
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }

  render() {
    const { prefixCls, styles, inkBarAnimated } = this.props;
    const className = `${prefixCls}-ink-bar`;
    const classes = classnames({
      [className]: true,
      [
        inkBarAnimated ?
          `${className}-animated` :
          `${className}-no-animated`
        ]: true,
    });
    return (
      <div
        style={styles.inkBar}
        className={classes}
        key="inkBar"
        ref={this.props.saveRef('inkBar')}
      />
    );
  }
}

InkTabBarNode.propTypes = {
  prefixCls: PropTypes.string,
  styles: PropTypes.object,
  inkBarAnimated: PropTypes.bool,
  saveRef: PropTypes.func,
};

InkTabBarNode.defaultProps = {
  prefixCls: '',
  inkBarAnimated: true,
  styles: {},
  saveRef: () => {},
};
<|endoftext|>


<commit_before>module.exports = (gulp, plugins, utilities) => {
    return () => {
        let publisher = plugins.awspublish.create({
            params: {
                Bucket: utilities.deploySettings.deployTarget[utilities.args.target]
            }
        });
        return gulp.src([`${utilities.paths.BUILD_FOLDER}/**/*`])
            .pipe(plugins.awspublishRouter({

                routes: {
                    "^.+\\.(?:js|css|svg|ttf|json)$": {
                        gzip: true,
                        useExpires: true,
                        cacheTime: 630720000,
                        public: false
                    },
                    "^.+\\.html": {
                        gzip: true
                    },
                    "^.+\\.mp4": {
                        useExpires: true,
                        cacheTime: 630720000,
                        public: false
                    },
                    "^.+$" : {}
                }
            }))
            .pipe(publisher.publish())
            .pipe(publisher.sync())
            .pipe(publisher.cache())
            .pipe(plugins.awspublish.reporter());
    }
};
<commit_msg>removed useExpires for now as it is not necessary<commit_after>module.exports = (gulp, plugins, utilities) => {
    return () => {
        let publisher = plugins.awspublish.create({
            params: {
                Bucket: utilities.deploySettings.deployTarget[utilities.args.target]
            }
        });
        return gulp.src([`${utilities.paths.BUILD_FOLDER}/**/*`])
            .pipe(plugins.awspublishRouter({

                routes: {
                    "^.+\\.(?:js|css|svg|ttf|json)$": {
                        gzip: true,
                        // useExpires: true,
                        cacheTime: 630720000,
                        public: false
                    },
                    "^.+\\.html": {
                        gzip: true
                    },
                    "^.+\\.mp4": {
                        // useExpires: true,
                        cacheTime: 630720000,
                        public: false
                    },
                    "^.+$" : {}
                }
            }))
            .pipe(publisher.publish())
            .pipe(publisher.sync())
            .pipe(publisher.cache())
            .pipe(plugins.awspublish.reporter());
    }
};
<|endoftext|>


<commit_before>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function setBundleConfig(bundleName, _bundleMap) {
    var targetName = bundleName.split("/").join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,["' +
        bundleName
        + '"]);'
    );
  }

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1) {
    // Merge task-specific and/or target-specific options with these defaults.

    var options = this.options({
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dest",
      resourcesJson: "resource.json"
    });

    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourcesJson;
    var indexBundles = options.indexBundles;
    var traversed_bundles = {}, traversed_files = {};
    var resourcesJs = { bundles: bundles };

    function getFiles(packageName, files, bundledFile) {
      if (!traversed_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.bundled.push(bundledFile);

          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files,bundledFile);
          }
          for (var i in bundle.js) {
            var file = dir + "/" + bundle.js[i];
            if (!traversed_files[file]) {
              files.push(file);
              traversed_files[file] = true;
            }
          }
        }
      }
      return files;
    }

    if (arg1 === "bundlify") {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          //console.log(abspath, rootdir, subdir, filename);
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if (packageName !== undefined) {
            for (var bundleName in _bundles) {
              if (bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) {
                bundles[bundleName] = { js: [], on: [], css: [] };
                for (var file_i in _bundles[bundleName].js) {
                  bundles[bundleName].js.push(subdir + "/" + _bundles[bundleName].js[file_i]);
                }
                for (var file_i in _bundles[bundleName].css) {
                  bundles[bundleName].css.push(subdir + "/" + _bundles[bundleName].css[file_i]);
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("file", abspath);
                console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      var myIndexBnudles = uniqueArray(indexBundles.concat(Object.keys(bundles)));

      myIndexBnudles.forEach(function (bundleName) {
        var _bundleMap = {};
        var bundledFile = dest + "/" + bundleName.split("/").join(".") + ".js";
        var files = uniqueArray(getFiles(bundleName, [], bundledFile));
        _bundleMap[bundledFile] = files;
        setBundleConfig(bundleName, _bundleMap);
      });

      grunt.task.run("uglify");

      grunt.file.write(dest + "/" + resourcesFile, JSON.stringify(resourcesJs));
    }
  });

};
<commit_msg>added one more task<commit_after>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function endsWith(str,suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  };

  function setBundleConfig(bundleName, _bundleMap) {
    var targetName = bundleName.split("/").join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,["' +
        bundleName
        + '"]);'
    );
  }

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1) {
    // Merge task-specific and/or target-specific options with these defaults.

    var TASK_BUNDLIFY = arg1==="bundlify";
    var TASK_SCAN = arg1==="scan";

    var options = this.options({
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dest",
      resourcesJson: "resource.json"
    });

    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourcesJson;
    var indexBundles = options.indexBundles;
    var traversed_bundles = {}, traversed_files = {};
    var resourcesJs = { bundles: bundles };

    function getFiles(packageName, files, bundledFile) {
      if (!traversed_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.bundled.push(bundledFile);

          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files,bundledFile);
          }
          for (var i in bundle.js) {
            var file = dir + "/" + bundle.js[i];
            if (!traversed_files[file]) {
              files.push(file);
              traversed_files[file] = true;
            }
          }
        }
      }
      return files;
    }

    if (TASK_BUNDLIFY || TASK_SCAN) {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          //console.log(abspath, rootdir, subdir, filename);
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if (packageName !== undefined) {
            for (var bundleName in _bundles) {
              if (bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) {
                bundles[bundleName] = { js: [], on: [], css: [] };
                for (var file_i in _bundles[bundleName].js) {
                  bundles[bundleName].js.push(subdir + "/" + _bundles[bundleName].js[file_i]);
                }
                for (var file_i in _bundles[bundleName].css) {
                  bundles[bundleName].css.push(subdir + "/" + _bundles[bundleName].css[file_i]);
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("file", abspath);
                console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      var myIndexBnudles = indexBundles;
      if(TASK_BUNDLIFY){
        myIndexBnudles = uniqueArray(indexBundles.concat(Object.keys(bundles).filter(function(bundleName){
          return !endsWith(bundleName,"/min");
        })));
      }

      myIndexBnudles.forEach(function (bundleName) {
        var _bundleMap = {};
        var bundledFile = dest + "/bootloader_bundled/" + bundleName.split("/").join(".") + ".js";
        var files = uniqueArray(getFiles(bundleName, [], bundledFile));
        _bundleMap[bundledFile] = files;
        setBundleConfig(bundleName, _bundleMap);
      });

      grunt.task.run("uglify");

      grunt.file.write(dest + "/" + resourcesFile, JSON.stringify(resourcesJs));
    }
  });

};
<|endoftext|>


<commit_before>'use strict'

const mixpanel = require('mixpanel')
const config = require('../config')

let _mixpanel = mixpanel.init(config.mixpanel_token)

class Mixpanel {

  static setPerson(sender, profile) {
    _mixpanel.identify(sender.id)
    _mixpanel.people.set({
      $first_name: profile.first_name,
      $last_name: profile.last_name,
      $created: (new Date()).toISOString(),
      locale: profile.locale,
      timezone: profile.timezone,
      gender: profile.gender
    })
  }

  static track(event, sender, message) {
    _mixpanel.track(event, {
      distinctId: sender.id,
      message: message
    })
  }
}

module.exports = Mixpanel<commit_msg>mix panel distinctId<commit_after>'use strict'

const mixpanel = require('mixpanel')
const config = require('../config')

let _mixpanel = mixpanel.init(config.mixpanel_token)

class Mixpanel {

  static setPerson(sender, profile) {
    _mixpanel.people.set(sender.id, {
      $first_name: profile.first_name,
      $last_name: profile.last_name,
      $created: (new Date()).toISOString(),
      distinctId: sender.id,
      locale: profile.locale,
      timezone: profile.timezone,
      gender: profile.gender
    })
  }

  static track(event, sender, message) {
    _mixpanel.track(event, {
      distinctId: sender.id,
      message: message
    })
  }
}

module.exports = Mixpanel<|endoftext|>


<commit_before>/*
 * ScratchX extension for WebAudio Oscillator
 *
 * yokobond <koji.yokokawa@yengawa.com>
 */

(function (ext) {
    var audioctx;
    if (typeof (webkitAudioContext) !== "undefined") {
        audioctx = new webkitAudioContext();
    }
    else if (typeof (AudioContext) !== "undefined") {
        audioctx = new AudioContext();
    }

    function Oscillator(waveType, freqValue, gainValue) {
        this.oscillator = audioctx.createOscillator();
        this.gain = audioctx.createGain();
        this.oscillator.connect(this.gain);
        this.gain.connect(audioctx.destination);
        this.oscillator.type = waveType || 'sine';
        this.oscillator.frequency.value = freqValue || 440;
        this.gain.value = gainValue || 0.5;
    }

    Oscillator.prototype.setType = function (type) {
        this.oscillator.type = type;
        return this;
    }

    Oscillator.prototype.setFrequency = function (freqValue) {
        this.oscillator.frequency.value = freqValue;
        return this;
    }

    Oscillator.prototype.setGain = function (gainValue) {
        this.oscillator.gain.gain.value = gainValue;
        return this;
    }

    Oscillator.prototype.start = function () {
        this.oscillator.start();
        return this;
    }

    Oscillator.prototype.stop = function () {
        this.oscillator.stop();
        return this;
    }

    var osc;

    /**
     * return oscillator can be start.
     */
    function getOscilator() {
        if (!osc) {
            osc = new Oscillator();
        }
        return osc;
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () {
        ext.oscillatorStop();
    };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        return {status: 2, msg: 'Ready'};
    };

    ext.oscillatorType = function (type) {
        getOscilator().setType(type);
    };

    ext.oscillatorFrequency = function (freqValue) {
        getOscilator().setFrequency(freqValue);
    };

    ext.oscillatorGain = function (gainValue) {
        getOscilator().setGain(gainValue);
    };

    ext.oscillatorStart = function () {
        getOscilator().start();
    };

    ext.oscillatorStop = function () {
        if (!osc) {
            return;
        }
        osc.stop();
        osc = null;
    };

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            // Block type, block name, function name
            [' ', 'start oscillator', 'oscillatorStart'],
            [' ', 'stop oscillator', 'oscillatorStop'],
            [' ', 'set oscillator type %m.waveType', 'oscillatorType', 'sine'],
            [' ', 'set oscillator frequency %n', 'oscillatorFrequency', 440],
            [' ', 'set oscillator gain %n', 'oscillatorGain', 0.5]
        ],
        menus: {
            waveType: ["sine", "square", "sawtooth", "triangle"]
        }
    };

    // Register the extension
    ScratchExtensions.register('WebAudio Oscillator', descriptor, ext);
})({});

<commit_msg>Fixed Oscillator setGain() to work.<commit_after>/*
 * ScratchX extension for WebAudio Oscillator
 *
 * yokobond <koji.yokokawa@yengawa.com>
 */

(function (ext) {
    var audioctx;
    if (typeof (webkitAudioContext) !== "undefined") {
        audioctx = new webkitAudioContext();
    }
    else if (typeof (AudioContext) !== "undefined") {
        audioctx = new AudioContext();
    }

    function Oscillator(waveType, freqValue, gainValue) {
        this.oscillator = audioctx.createOscillator();
        this.gain = audioctx.createGain();
        this.oscillator.connect(this.gain);
        this.gain.connect(audioctx.destination);
        this.oscillator.type = waveType || 'sine';
        this.oscillator.frequency.value = freqValue || 440;
        this.gain.value = gainValue || 0.5;
    }

    Oscillator.prototype.setType = function (type) {
        this.oscillator.type = type;
        return this;
    }

    Oscillator.prototype.setFrequency = function (freqValue) {
        this.oscillator.frequency.value = freqValue;
        return this;
    }

    Oscillator.prototype.setGain = function (gainValue) {
        this.gain.gain.value = gainValue;
        return this;
    }

    Oscillator.prototype.start = function () {
        this.oscillator.start();
        return this;
    }

    Oscillator.prototype.stop = function () {
        this.oscillator.stop();
        return this;
    }

    var osc;

    /**
     * return oscillator can be start.
     */
    function getOscilator() {
        if (!osc) {
            osc = new Oscillator();
        }
        return osc;
    }

    // Cleanup function when the extension is unloaded
    ext._shutdown = function () {
        ext.oscillatorStop();
    };

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function () {
        return {status: 2, msg: 'Ready'};
    };

    ext.oscillatorType = function (type) {
        getOscilator().setType(type);
    };

    ext.oscillatorFrequency = function (freqValue) {
        getOscilator().setFrequency(freqValue);
    };

    ext.oscillatorGain = function (gainValue) {
        getOscilator().setGain(gainValue);
    };

    ext.oscillatorStart = function () {
        getOscilator().start();
    };

    ext.oscillatorStop = function () {
        if (!osc) {
            return;
        }
        osc.stop();
        osc = null;
    };

    // Block and block menu descriptions
    var descriptor = {
        blocks: [
            // Block type, block name, function name
            [' ', 'start oscillator', 'oscillatorStart'],
            [' ', 'stop oscillator', 'oscillatorStop'],
            [' ', 'set oscillator type %m.waveType', 'oscillatorType', 'sine'],
            [' ', 'set oscillator frequency %n', 'oscillatorFrequency', 440],
            [' ', 'set oscillator gain %n', 'oscillatorGain', 0.5]
        ],
        menus: {
            waveType: ["sine", "square", "sawtooth", "triangle"]
        }
    };

    // Register the extension
    ScratchExtensions.register('WebAudio Oscillator', descriptor, ext);
})({});

<|endoftext|>


<commit_before>var indexController = function(params) {
  var defaultParams = {
    'query': ''
  };
  $.extend(defaultParams, params);
  params = defaultParams;

  var SearchForm = React.createClass({
    handleSubmit: function(event) {
      var query = $('#search-form-input').val();
      PressNavigation.switchToUri('/search', {'query': query});
      event.preventDefault();
    },

    render: function() {
      return (
        <form action='#' onSubmit={this.handleSubmit}>
          {this.props.children}
          <input
            type='submit'
            className="press-right press-button"
            value='Search'
          />
        </form>
      );
    }
  });

  var SearchFormInput = React.createClass({
    getInitialState: function() {
      return {value: params.query};
    },

    handleChange: function(event) {
      this.setState({value: event.target.value});
    },

    render: function() {
      return (
        <input
          id='search-form-input'
          type='search'
          className='press-wide'
          value={this.state.value}
          onChange={this.handleChange}
        />
      );
    }
  });

  return {
    'toolbar':

        <PressNavigationButton
          label='Add search engine'
          uri='/add_engine'
          className='press-right'
        />
        <PressNavigationButton
          label='New bookmark'
          uri='/new'
          className='press-right'
        />

          Search your bookmarks

,
    'content':

        <SearchForm>
          <SearchFormInput/>
        </SearchForm>
        <PressNavigationButton
          label='Show all bookmarks'
          uri='/show_all'
          className='press-left'
        />

  };
}
<commit_msg>Disable auto capitalize<commit_after>var indexController = function(params) {
  var defaultParams = {
    'query': ''
  };
  $.extend(defaultParams, params);
  params = defaultParams;

  var SearchForm = React.createClass({
    handleSubmit: function(event) {
      var query = $('#search-form-input').val();
      PressNavigation.switchToUri('/search', {'query': query});
      event.preventDefault();
    },

    render: function() {
      return (
        <form action='#' onSubmit={this.handleSubmit}>
          {this.props.children}
          <input
            type='submit'
            className="press-right press-button"
            value='Search'
          />
        </form>
      );
    }
  });

  var SearchFormInput = React.createClass({
    getInitialState: function() {
      return {value: params.query};
    },

    handleChange: function(event) {
      this.setState({value: event.target.value});
    },

    render: function() {
      return (
        <input
          id='search-form-input'
          type='search'
          className='press-wide'
          autoCapitalize='none'
          value={this.state.value}
          onChange={this.handleChange}
        />
      );
    }
  });

  return {
    'toolbar':

        <PressNavigationButton
          label='Add search engine'
          uri='/add_engine'
          className='press-right'
        />
        <PressNavigationButton
          label='New bookmark'
          uri='/new'
          className='press-right'
        />

          Search your bookmarks

,
    'content':

        <SearchForm>
          <SearchFormInput/>
        </SearchForm>
        <PressNavigationButton
          label='Show all bookmarks'
          uri='/show_all'
          className='press-left'
        />

  };
}
<|endoftext|>


<commit_before>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function cleanURL(url) {
    var protocol = null;
    url = url.replace(/[\/]+/g, '/');;
    var ars = url.split('/');
    var context = ars.shift();
    var parents = [];
    for ( var i in ars) {
      switch (ars[i]) {
        case '.':
          // Don't need to do anything here
          break;
        case '..':
          parents.pop();
          break;
        default:
          parents.push(ars[i]);
          break;
      }
    }
    if(protocol){
      return protocol +"://"+ ( context + '/' + parents.join('/')).replace(/(\/)+/g, '/');
    }
    return (context + '/' + parents.join('/')).replace(/(\/)+/g, '/');
  }

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function mixin(obj, proto) {
    for ( var prop in proto) {
      if (proto.hasOwnProperty(prop)) {
        obj[prop] = proto[prop];
      }
    }
    return obj;
  }

  function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }

  function toIgnore(bundleName){
    return endsWith(bundleName, "/min") || endsWith(bundleName, "/test");
  }

  function setBundleConfig(bundleName, _bundleMap, includedBundles,bundledFile) {
    var targetName = bundleName.split(/[\/.]/).join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,' +
        // JSON.stringify(includedBundles)
        JSON.stringify([bundleName])
        + ');/*'+_bundleMap[bundledFile].join(",")+'*/'
    );
  }

  var TASK_BUNDLIFY, TASK_SCAN, TASK_SKIP_INIT, TASK_SERVER;
  var datahandler,STUBS_URL = "./app", CONTROLLER_MATCH,INDEX_MATCH;

  function showIndex(url){
    if((/\/(src|dist|data)\//).test(url)){
      return false;
    }
    if(INDEX_MATCH && (INDEX_MATCH).test(url)){
      return true;
    }
    if((CONTROLLER_MATCH).test(url)){
      return false;
    }
    if(INDEX_MATCH){
      return false;
    }
    return true;
  }

  var bootServerOptions = {
      port: 8090,
      hostname: "*",
      base: './',
      keepalive: true,
      noBypass : /^\/(view|json|data|swagger)\//,
      indexMatch : false,
    /**
     * Description
     * @method middleware
     * @param {} connect
     * @param {} options
     * @return ArrayExpression
     */
      middleware: function (connect, options) {
      return [
        connect.compress({
          level: 9
        }),
        //require('connect-livereload')(),
        function(req, res, next){
          if (req.headers.origin === undefined) {
            res.setHeader('Access-Control-Allow-Origin', "*");
          } else {
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
          }
          res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
          console.log(req.method + " on " + req.originalUrl);
          if (req.method === "OPTIONS") {
            res.setHeader('Access-Control-Allow-Headers', 'content-type');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            res.setHeader('Content-Length', '0');
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            var body = grunt.file.read(req.originalUrl.split("?")[0]);
            //res.write(body);
            res.end("200");
            //next();
          } else {
            next();
          }
        },
        connect.static(options.base),
        function (req, res, next) {
          if (showIndex(req.originalUrl)) {
            var body = grunt.file.read("index.html");
            res.write(body);
            res.end();
          } else {
            res.setHeader('Access-Control-Allow-Headers', 'content-type');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            res.setHeader('Content-Length', '0');
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            datahandler(req, res, STUBS_URL, function(){
              console.log("first end");
              res.end();
              //next();
            });
          }
        },
        function (req, res, next) {
          if (req.headers.origin === undefined) {
            res.setHeader('Access-Control-Allow-Origin', "*");
          } else {
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
          }
          if (showIndex(req.originalUrl)) {
            var body = grunt.file.read("index.html");
            res.write(body);
            console.log("2nd end");
            res.end();
          } else {
            next();
          }
        },
        connect.directory(options.base)
      ];
    }
  };

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  function bundler(options) {
    var allFiles = {};
    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourceJson;
    var indexBundles = options.indexBundles;
    var titleIndexBnudles = {};
    var traversed_bundles = {}, traversed_files = {},excluded_bundles = {};
    var version = new Date().getTime();
    var resourcesJs = {};
    for (var key in options) {
      resourcesJs[key] = options[key];
    }
    resourcesJs.bundles = bundles;

    function getFiles(packageName, files, bundledFile, includedBundles) {
      if (!traversed_bundles[packageName] && !excluded_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.bundled_html = bundle.bundled_html || [];
          bundle.in = bundle.in || [];
          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files, bundledFile, includedBundles);
          }
          for (var i in bundle.js) {
            var file = cleanURL(dir + "/" + bundle.js[i]);
            if (!traversed_files[file]) {
              files.js.push(file);
              traversed_files[file] = true;
            }
          }
          if (files.js.length > 0) {
            bundle.bundled.push(bundledFile+".js");
          }

          for (var i in bundle.html) {
            var file = cleanURL(dir + "/" + bundle.html[i]);
            if (!traversed_files[file]) {
              files.html.push(file);
              traversed_files[file] = true;
            }
          }
          if (files.html.length > 0) {
            bundle.bundled_html.push(bundledFile+".html");
          }

          includedBundles.push(packageName);
        }
      }
      return files;
    }

    if (TASK_BUNDLIFY || TASK_SCAN) {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          var packageInfo = {};
          if(grunt.file.exists(subdir+"/.bower.json")){
            var bowerJson =grunt.file.readJSON(subdir+"/.bower.json");
            packageInfo.bowerName = bowerJson.name;
            packageInfo.bowerVersion = bowerJson.version;
          }
          if(grunt.file.exists(subdir+"/composer.json")){
            var composerJson =grunt.file.readJSON(subdir+"/composer.json");
            packageInfo.composerName = composerJson.name;
            packageInfo.composerVersion = composerJson.version;
          }
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if(_bundles.exclude){
            for(var i in _bundles.exclude){
              excluded_bundles[_bundles.exclude[i]] = true;
            }
          }
          if (packageName !== undefined) {
            titleIndexBnudles[packageName] = [];
            for (var bundleName in _bundles) {
              if ((bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) && !excluded_bundles[bundleName]) {
                if (bundles[bundleName]) {
                  console.log("====Duplicate Package", bundleName);
                } else if(!toIgnore(bundleName)){
                  titleIndexBnudles[packageName].push(bundleName);
                }
                bundles[bundleName] = { js: [], on: [], css: [], html : [], packageInfo : packageInfo};
                for (var file_i in _bundles[bundleName].js) {
                  var js_file = subdir + "/" + _bundles[bundleName].js[file_i];
                  bundles[bundleName].js.push(js_file);
                  if (!allFiles[js_file]) {
                    allFiles[js_file] = js_file;
                  } else {
                    console.log("====Duplicate File" + js_file);
                  }
                }
                for (var file_i in _bundles[bundleName].css) {
                  var css_file = subdir + "/" + _bundles[bundleName].css[file_i];
                  bundles[bundleName].css.push(css_file);
                  if (!allFiles[css_file]) {
                    allFiles[css_file] = css_file;
                  } else {
                    console.log("====Duplicate File" + css_file);
                  }
                }
                for (var file_i in _bundles[bundleName].html) {
                  var html_file = subdir + "/" + _bundles[bundleName].html[file_i];
                  bundles[bundleName].html.push(html_file);
                  if (!allFiles[html_file]) {
                    allFiles[html_file] = html_file;
                  } else {
                    console.log("====Duplicate File" + html_file);
                  }
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("==Module.json", abspath);
                //console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      var titleIndexBnudlesNames =  Object.keys(titleIndexBnudles);
//      titleIndexBnudlesNames.map(function(bundName){
//        if(!bundles[bundName] && !toIgnore(bundName)){
//          bundles[bundName] =  { js: [], on: titleIndexBnudles[bundName], css: [], html : [], packageInfo : {}}
//          console.log("New Package ",bundName,bundles[bundName]);
//        }
//      });

      for(var packageKey in excluded_bundles){
        delete bundles[packageKey];
      }

      var firstIndexBundled = null;

      if (!TASK_SKIP_INIT) {
        var myIndexBnudles = indexBundles;
        if (TASK_BUNDLIFY) {

          var moreBundles = Object.keys(bundles);

          if(options.sort){
            moreBundles = moreBundles.sort();
          }

          if(options.projectPrefix !== undefined){
            myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles).filter(function(bundleName){
              return bundleName.indexOf(options.projectPrefix) === 0;
            })));
          }

          myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles))).filter(function (bundleName) {
            return !toIgnore(bundleName);
          });

        }
        console.log("Bundles in Order",myIndexBnudles);

        var prevBundle = null;
        myIndexBnudles.forEach(function (bundleName) {
          var _bundleMap = {};
          var includedBundles = [];
          var bundledFile = dest + "/bootloader_bundled/" + bundleName.split("/").join(".");
          var bundledFile_js = bundledFile+".js";
          var files = getFiles(bundleName, {js : [], html : []}, bundledFile, includedBundles);
          var js_files = uniqueArray(files.js.reverse()).reverse();
          if (js_files.length > 0) {
            if(!firstIndexBundled &&  options.resourcesInline){
              firstIndexBundled = bundleName;
              js_files.unshift(resourcesFile+".js");
            }
            _bundleMap[bundledFile_js] = js_files;
            //console.log("files",bundleName,files.length,files);
            setBundleConfig(bundleName, _bundleMap, includedBundles,bundledFile_js);

            if (prevBundle) {
              var bundle = resourcesJs.bundles[bundleName];
              if (bundle) {
                bundle.on = [prevBundle].concat(bundle.on)
              }
            }
            prevBundle = bundleName;

          } else console.log("No File in bundle to bundlify thus skipping ", bundleName);

          var html_files = uniqueArray(files.html.reverse()).reverse();
          if(html_files.length){
            var html_file_content = "";
            for(var i in html_files){
              html_file_content+='<script type="text/html" src="'+html_files[i]+'">'+grunt.file.read(html_files[i]).split("\t").join("")
                .split("\n").join(" ")
                .split(">").map(function(v) {
                  return v.trim();
                }).join(">")+'</script>';
            }
            grunt.file.write(bundledFile+".html",html_file_content);
          }

        });

        if(firstIndexBundled){
          grunt.file.write(resourcesFile+".js", "var _BOOTLOADER_CONFIG_=" + JSON.stringify({
            RESOURCES_JSON : resourcesJs,
            RESOURCES_FILE: resourcesFile
          }));
          resourcesJs.bundles[firstIndexBundled].js.unshift(resourcesFile+".js");
        }

        grunt.task.run("uglify");
      }

      grunt.file.write(resourcesFile, JSON.stringify(resourcesJs));
    }
  }

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1, arg2) {
    // Merge task-specific and/or target-specific options with these defaults.

    TASK_BUNDLIFY = arg1 === "bundlify";
    TASK_SCAN = arg1 === "scan";
    TASK_SKIP_INIT = TASK_SCAN && arg2 == "skip";
    TASK_SERVER = arg1 === "server";

    var options = this.options({
      version: new Date().getTime(0),
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dist",
      resourceJson: "dist/resource.json"
    });

    if (TASK_BUNDLIFY || TASK_SCAN) {
      bundler(options)
    } else if (TASK_SERVER) {
     // global.__base = options.src;
      datahandler = require(__dirname + "/../utils/stubshandler");
      var _bootServerOptions = Object.create(bootServerOptions);
      mixin(_bootServerOptions,options.bootServer);
      CONTROLLER_MATCH = _bootServerOptions.noBypass;
      INDEX_MATCH = _bootServerOptions.indexMatch;
      grunt.config("connect.bootServer.options", _bootServerOptions);
      grunt.task.run("connect:bootServer");
    } else if(arg1 === "swagger"){
      ([
        "controller/SwaggerController.js",
        "view/swaggerui.html"
      ]).forEach(function(file){
        grunt.file.copy(__dirname+"/../examples/"+file, "app/"+file);
      })
    }

  });

};
<commit_msg>modulize and order flags added<commit_after>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function cleanURL(url) {
    var protocol = null;
    url = url.replace(/[\/]+/g, '/');;
    var ars = url.split('/');
    var context = ars.shift();
    var parents = [];
    for ( var i in ars) {
      switch (ars[i]) {
        case '.':
          // Don't need to do anything here
          break;
        case '..':
          parents.pop();
          break;
        default:
          parents.push(ars[i]);
          break;
      }
    }
    if(protocol){
      return protocol +"://"+ ( context + '/' + parents.join('/')).replace(/(\/)+/g, '/');
    }
    return (context + '/' + parents.join('/')).replace(/(\/)+/g, '/');
  }

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function mixin(obj, proto) {
    for ( var prop in proto) {
      if (proto.hasOwnProperty(prop)) {
        obj[prop] = proto[prop];
      }
    }
    return obj;
  }

  function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  }

  function toIgnore(bundleName){
    return endsWith(bundleName, "/min") || endsWith(bundleName, "/test");
  }

  function setBundleConfig(bundleName, _bundleMap, includedBundles,bundledFile) {
    var targetName = bundleName.split(/[\/.]/).join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,' +
        // JSON.stringify(includedBundles)
        JSON.stringify([bundleName])
        + ');/*'+_bundleMap[bundledFile].join(",")+'*/'
    );
  }

  var TASK_BUNDLIFY, TASK_SCAN, TASK_SKIP_INIT, TASK_SERVER;
  var datahandler,STUBS_URL = "./app", CONTROLLER_MATCH,INDEX_MATCH;

  function showIndex(url){
    if((/\/(src|dist|data)\//).test(url)){
      return false;
    }
    if(INDEX_MATCH && (INDEX_MATCH).test(url)){
      return true;
    }
    if((CONTROLLER_MATCH).test(url)){
      return false;
    }
    if(INDEX_MATCH){
      return false;
    }
    return true;
  }

  var bootServerOptions = {
      port: 8090,
      hostname: "*",
      base: './',
      keepalive: true,
      noBypass : /^\/(view|json|data|swagger)\//,
      indexMatch : false,
    /**
     * Description
     * @method middleware
     * @param {} connect
     * @param {} options
     * @return ArrayExpression
     */
      middleware: function (connect, options) {
      return [
        connect.compress({
          level: 9
        }),
        //require('connect-livereload')(),
        function(req, res, next){
          if (req.headers.origin === undefined) {
            res.setHeader('Access-Control-Allow-Origin', "*");
          } else {
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
          }
          res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
          console.log(req.method + " on " + req.originalUrl);
          if (req.method === "OPTIONS") {
            res.setHeader('Access-Control-Allow-Headers', 'content-type');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            res.setHeader('Content-Length', '0');
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            var body = grunt.file.read(req.originalUrl.split("?")[0]);
            //res.write(body);
            res.end("200");
            //next();
          } else {
            next();
          }
        },
        connect.static(options.base),
        function (req, res, next) {
          if (showIndex(req.originalUrl)) {
            var body = grunt.file.read("index.html");
            res.write(body);
            res.end();
          } else {
            res.setHeader('Access-Control-Allow-Headers', 'content-type');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            res.setHeader('Content-Length', '0');
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            datahandler(req, res, STUBS_URL, function(){
              console.log("first end");
              res.end();
              //next();
            });
          }
        },
        function (req, res, next) {
          if (req.headers.origin === undefined) {
            res.setHeader('Access-Control-Allow-Origin', "*");
          } else {
            res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
          }
          if (showIndex(req.originalUrl)) {
            var body = grunt.file.read("index.html");
            res.write(body);
            console.log("2nd end");
            res.end();
          } else {
            next();
          }
        },
        connect.directory(options.base)
      ];
    }
  };

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  function bundler(options) {
    var allFiles = {};
    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourceJson;
    var indexBundles = options.indexBundles;
    var titleIndexBnudles = {};
    var traversed_bundles = {}, traversed_files = {},excluded_bundles = {};
    var version = new Date().getTime();
    var resourcesJs = {};
    for (var key in options) {
      resourcesJs[key] = options[key];
    }
    resourcesJs.bundles = bundles;

    function getFiles(packageName, files, bundledFile, includedBundles) {
      if (!traversed_bundles[packageName] && !excluded_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.bundled_html = bundle.bundled_html || [];
          bundle.in = bundle.in || [];
          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files, bundledFile, includedBundles);
          }
          for (var i in bundle.js) {
            var file = cleanURL(dir + "/" + bundle.js[i]);
            if (!traversed_files[file]) {
              files.js.push(file);
              traversed_files[file] = packageName;
            }
          }
          if (files.js.length > 0) {
            bundle.bundled.push(bundledFile+".js");
          }

          for (var i in bundle.html) {
            var file = cleanURL(dir + "/" + bundle.html[i]);
            if (!traversed_files[file]) {
              files.html.push(file);
              traversed_files[file] = packageName;
            }
          }
          if (files.html.length > 0) {
            bundle.bundled_html.push(bundledFile+".html");
          }

          includedBundles.push(packageName);
        }
      }
      return files;
    }

    if (TASK_BUNDLIFY || TASK_SCAN) {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          var packageInfo = {};
          if(grunt.file.exists(subdir+"/.bower.json")){
            var bowerJson =grunt.file.readJSON(subdir+"/.bower.json");
            packageInfo.bowerName = bowerJson.name;
            packageInfo.bowerVersion = bowerJson.version;
          }
          if(grunt.file.exists(subdir+"/composer.json")){
            var composerJson =grunt.file.readJSON(subdir+"/composer.json");
            packageInfo.composerName = composerJson.name;
            packageInfo.composerVersion = composerJson.version;
          }
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if(_bundles.exclude){
            for(var i in _bundles.exclude){
              excluded_bundles[_bundles.exclude[i]] = true;
            }
          }
          if (packageName !== undefined) {
            titleIndexBnudles[packageName] = [];
            for (var bundleName in _bundles) {
              if ((bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) && !excluded_bundles[bundleName]) {
                if (bundles[bundleName]) {
                  console.log("====Duplicate Package", bundleName);
                } else if(!toIgnore(bundleName)){
                  titleIndexBnudles[packageName].push(bundleName);
                }
                bundles[bundleName] = { js: [], on: [], css: [], html : [], packageInfo : packageInfo};
                for (var file_i in _bundles[bundleName].js) {
                  var js_file = subdir + "/" + _bundles[bundleName].js[file_i];
                  bundles[bundleName].js.push(js_file);
                  if (!allFiles[js_file]) {
                    allFiles[js_file] = js_file;
                  } else {
                    console.log("====Duplicate File" + js_file);
                  }
                }
                for (var file_i in _bundles[bundleName].css) {
                  var css_file = subdir + "/" + _bundles[bundleName].css[file_i];
                  bundles[bundleName].css.push(css_file);
                  if (!allFiles[css_file]) {
                    allFiles[css_file] = css_file;
                  } else {
                    console.log("====Duplicate File" + css_file);
                  }
                }
                for (var file_i in _bundles[bundleName].html) {
                  var html_file = subdir + "/" + _bundles[bundleName].html[file_i];
                  bundles[bundleName].html.push(html_file);
                  if (!allFiles[html_file]) {
                    allFiles[html_file] = html_file;
                  } else {
                    console.log("====Duplicate File" + html_file);
                  }
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("==Module.json", abspath);
                //console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      var titleIndexBnudlesNames =  Object.keys(titleIndexBnudles);

      if(options.modulize){
        titleIndexBnudlesNames.map(function(bundName){
          if(!bundles[bundName] && !toIgnore(bundName)){
            bundles[bundName] =  { js: [], on: titleIndexBnudles[bundName], css: [], html : [], packageInfo : {}}
            console.log("New Package ",bundName,bundles[bundName]);
          }
        });
      }

      for(var packageKey in excluded_bundles){
        delete bundles[packageKey];
      }

      var firstIndexBundled = null;

      if (!TASK_SKIP_INIT) {
        var myIndexBnudles = indexBundles;
        if (TASK_BUNDLIFY) {

          var moreBundles = Object.keys(bundles);

          if(options.sort){
            moreBundles = moreBundles.sort();
          }

          if(options.projectPrefix !== undefined){
            myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles).filter(function(bundleName){
              return bundleName.indexOf(options.projectPrefix) === 0;
            })));
          }

          myIndexBnudles = uniqueArray(myIndexBnudles.concat(titleIndexBnudlesNames.concat(moreBundles))).filter(function (bundleName) {
            return !toIgnore(bundleName);
          });

        }
        console.log("Bundles in Order",myIndexBnudles);

        var prevBundle = null;
        myIndexBnudles.forEach(function (bundleName) {
          var _bundleMap = {};
          var includedBundles = [];
          var bundledFile = dest + "/bootloader_bundled/" + bundleName.split("/").join(".");
          var bundledFile_js = bundledFile+".js";
          var files = getFiles(bundleName, {js : [], html : []}, bundledFile, includedBundles);
          var js_files = uniqueArray(files.js.reverse()).reverse();
          if (js_files.length > 0) {
            if(!firstIndexBundled &&  options.resourcesInline){
              firstIndexBundled = bundleName;
              js_files.unshift(resourcesFile+".js");
            }
            _bundleMap[bundledFile_js] = js_files;
            //console.log("files",bundleName,files.length,files);
            setBundleConfig(bundleName, _bundleMap, includedBundles,bundledFile_js);

            if (prevBundle && options.order) {
              var bundle = resourcesJs.bundles[bundleName];
              if (bundle) {
                bundle.on = [prevBundle].concat(bundle.on)
              }
            }
            prevBundle = bundleName;

          } else console.log("No File in bundle to bundlify thus skipping ", bundleName);

          var html_files = uniqueArray(files.html.reverse()).reverse();
          if(html_files.length){
            var html_file_content = "";
            for(var i in html_files){
              html_file_content+='<script type="text/html" src="'+html_files[i]+'">'+grunt.file.read(html_files[i]).split("\t").join("")
                .split("\n").join(" ")
                .split(">").map(function(v) {
                  return v.trim();
                }).join(">")+'</script>';
            }
            grunt.file.write(bundledFile+".html",html_file_content);
          }

        });

        if(firstIndexBundled){
          grunt.file.write(resourcesFile+".js", "var _BOOTLOADER_CONFIG_=" + JSON.stringify({
            RESOURCES_JSON : resourcesJs,
            RESOURCES_FILE: resourcesFile
          }));
          resourcesJs.bundles[firstIndexBundled].js.unshift(resourcesFile+".js");
        }

        grunt.task.run("uglify");
      }

      grunt.file.write(resourcesFile, JSON.stringify(resourcesJs));
    }
  }

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1, arg2) {
    // Merge task-specific and/or target-specific options with these defaults.

    TASK_BUNDLIFY = arg1 === "bundlify";
    TASK_SCAN = arg1 === "scan";
    TASK_SKIP_INIT = TASK_SCAN && arg2 == "skip";
    TASK_SERVER = arg1 === "server";

    var options = this.options({
      version: new Date().getTime(0),
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dist",
      resourceJson: "dist/resource.json"
    });

    if (TASK_BUNDLIFY || TASK_SCAN) {
      bundler(options)
    } else if (TASK_SERVER) {
     // global.__base = options.src;
      datahandler = require(__dirname + "/../utils/stubshandler");
      var _bootServerOptions = Object.create(bootServerOptions);
      mixin(_bootServerOptions,options.bootServer);
      CONTROLLER_MATCH = _bootServerOptions.noBypass;
      INDEX_MATCH = _bootServerOptions.indexMatch;
      grunt.config("connect.bootServer.options", _bootServerOptions);
      grunt.task.run("connect:bootServer");
    } else if(arg1 === "swagger"){
      ([
        "controller/SwaggerController.js",
        "view/swaggerui.html"
      ]).forEach(function(file){
        grunt.file.copy(__dirname+"/../examples/"+file, "app/"+file);
      })
    }

  });

};
<|endoftext|>


<commit_before>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function endsWith(str,suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  };

  function setBundleConfig(bundleName, _bundleMap,includedBundles) {
    var targetName = bundleName.split("/").join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,' +
       // JSON.stringify(includedBundles)
        JSON.stringify([bundleName])
        + ');'
    );
  }

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1) {
    // Merge task-specific and/or target-specific options with these defaults.

    var TASK_BUNDLIFY = arg1==="bundlify";
    var TASK_SCAN = arg1==="scan";

    var options = this.options({
      version: new Date().getTime(0),
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dest",
      resourcesJson: "resource.json"
    });

    var allFiles = {};
    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourcesJson;
    var indexBundles = options.indexBundles;
    var traversed_bundles = {}, traversed_files = {};
    var version = new Date().getTime();
    var resourcesJs = {version: options.version, bundles: bundles };

    function getFiles(packageName, files, bundledFile,includedBundles) {
      if (!traversed_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.in = bundle.in || [];
          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files, bundledFile,includedBundles);
          }
          for (var i in bundle.js) {
            var file = dir + "/" + bundle.js[i];
            if (!traversed_files[file]) {
              files.push(file);
              traversed_files[file] = true;
            }
          }
          if(files.length>0){
            bundle.bundled.push(bundledFile);
          }
          includedBundles.push(packageName);
        }
      }
      return files;
    }

    if (TASK_BUNDLIFY || TASK_SCAN) {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          //console.log(abspath, rootdir, subdir, filename);
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if (packageName !== undefined) {
            for (var bundleName in _bundles) {
              if (bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) {
                if(bundles[bundleName]){
                  console.log("====Duplicate Package",bundleName);
                }
                bundles[bundleName] = { js: [], on: [], css: [] };
                for (var file_i in _bundles[bundleName].js) {
                  var js_file = subdir + "/" + _bundles[bundleName].js[file_i];
                  bundles[bundleName].js.push(js_file);
                  if(!allFiles[js_file]){
                    allFiles[js_file] = js_file;
                  } else {
                    console.log("====Duplicate File"+js_file);
                  }
                }
                for (var file_i in _bundles[bundleName].css) {
                  var css_file = subdir + "/" + _bundles[bundleName].css[file_i];
                  bundles[bundleName].css.push(css_file);
                  if(!allFiles[css_file]){
                    allFiles[css_file] = css_file;
                  } else {
                    console.log("====Duplicate File"+css_file);
                  }
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("==Module.json", abspath);
                //console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      var myIndexBnudles = indexBundles;
      if(TASK_BUNDLIFY){
        myIndexBnudles = uniqueArray(indexBundles.concat(Object.keys(bundles).filter(function(bundleName){
          return !endsWith(bundleName,"/min") && !endsWith(bundleName,"/test");
        })));
      }

      var prevBundle = null;
      myIndexBnudles.forEach(function (bundleName) {
        var _bundleMap = {};
        var includedBundles = [];
        var bundledFile = dest + "/bootloader_bundled/" + bundleName.split("/").join(".") + ".js";
        var files = uniqueArray(getFiles(bundleName, [],bundledFile,includedBundles).reverse()).reverse();
        if(files.length>0){
          _bundleMap[bundledFile] = files;
          setBundleConfig(bundleName, _bundleMap,includedBundles);

          if(prevBundle){
            var bundle = resourcesJs.bundles[bundleName];
            if (bundle) {
              bundle.on = [prevBundle].concat(bundle.on)
            }
          }
          prevBundle = bundleName;

        } else console.log("No File in bundle to bundlify so skipping ",bundleName);
      });

      grunt.task.run("uglify");

      grunt.file.write(dest + "/" + resourcesFile, JSON.stringify(resourcesJs));
    }
  });

};
<commit_msg>live reload supported<commit_after>/*
 * grunt-bootloader
 *
 *
 * Copyright (c) 2015 Lalit Tanwar
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  function uniqueArray(list) {
    var u = {}, a = [];
    for (var i = 0, l = list.length; i < l; ++i) {
      if (u.hasOwnProperty(list[i])) {
        continue;
      }
      a.push(list[i]);
      u[list[i]] = 1;
    }
    return a;
  }

  function endsWith(str,suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
  };

  function setBundleConfig(bundleName, _bundleMap,includedBundles) {
    var targetName = bundleName.split("/").join("_");
    grunt.config("uglify." + targetName + ".files", _bundleMap);
    grunt.config("uglify." + targetName + ".options.footer",
        ';\n(function(foo,bundles){foo.__bundled__ = foo.__bundled__ ? foo.__bundled__.concat(bundles) : bundles;})(this,' +
       // JSON.stringify(includedBundles)
        JSON.stringify([bundleName])
        + ');'
    );
  }

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-uglify');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('bootloader', 'Setup your webproject in an instant', function (arg1,arg2) {
    // Merge task-specific and/or target-specific options with these defaults.

    var TASK_BUNDLIFY = arg1==="bundlify";
    var TASK_SCAN = arg1==="scan";
    var TASK_SKIP_INIT = TASK_SCAN && arg2=="skip";

    var options = this.options({
      version: new Date().getTime(0),
      indexBundles: ["webmodules/bootloader", "project/app"],
      src: "./",
      dest: "dest",
      resourcesJson: "resource.json"
    });

    var allFiles = {};
    var bundles = {};
    var dir = options.src;
    var dest = options.dest;
    var resourcesFile = options.resourcesJson;
    var indexBundles = options.indexBundles;
    var traversed_bundles = {}, traversed_files = {};
    var version = new Date().getTime();
    var resourcesJs = {};
    for(var key in options){
      resourcesJs[key] = options[key];
    }
    resourcesJs.bundles = bundles;

    function getFiles(packageName, files, bundledFile,includedBundles) {
      if (!traversed_bundles[packageName]) {
        traversed_bundles[packageName] = true;
        var bundle = resourcesJs.bundles[packageName];
        if (bundle) {
          bundle.bundled = bundle.bundled || [];
          bundle.in = bundle.in || [];
          for (var i in bundle.on) {
            files = getFiles(bundle.on[i], files, bundledFile,includedBundles);
          }
          for (var i in bundle.js) {
            var file = dir + "/" + bundle.js[i];
            if (!traversed_files[file]) {
              files.push(file);
              traversed_files[file] = true;
            }
          }
          if(files.length>0){
            bundle.bundled.push(bundledFile);
          }
          includedBundles.push(packageName);
        }
      }
      return files;
    }

    if (TASK_BUNDLIFY || TASK_SCAN) {
      grunt.file.recurse(dir, function (abspath, rootdir, subdir, filename) {
        if (filename === "module.json" && abspath.indexOf(dest) !== 0) {
          //console.log(abspath, rootdir, subdir, filename);
          var _bundles = grunt.file.readJSON(abspath);
          var packageName = _bundles.name;
          if (packageName !== undefined) {
            for (var bundleName in _bundles) {
              if (bundleName === packageName || bundleName.indexOf(packageName + "/") === 0) {
                if(bundles[bundleName]){
                  console.log("====Duplicate Package",bundleName);
                }
                bundles[bundleName] = { js: [], on: [], css: [] };
                for (var file_i in _bundles[bundleName].js) {
                  var js_file = subdir + "/" + _bundles[bundleName].js[file_i];
                  bundles[bundleName].js.push(js_file);
                  if(!allFiles[js_file]){
                    allFiles[js_file] = js_file;
                  } else {
                    console.log("====Duplicate File"+js_file);
                  }
                }
                for (var file_i in _bundles[bundleName].css) {
                  var css_file = subdir + "/" + _bundles[bundleName].css[file_i];
                  bundles[bundleName].css.push(css_file);
                  if(!allFiles[css_file]){
                    allFiles[css_file] = css_file;
                  } else {
                    console.log("====Duplicate File"+css_file);
                  }
                }
                bundles[bundleName].on = _bundles[bundleName].on || [];
                console.log("==Module.json", abspath);
                //console.log(bundleName, _bundles[bundleName].on);
              }
            }
          }
        }
      });

      if(!TASK_SKIP_INIT){
        var myIndexBnudles = [indexBundles[0]];
        if(TASK_BUNDLIFY){
          myIndexBnudles = uniqueArray(indexBundles.concat(Object.keys(bundles).filter(function(bundleName){
            return !endsWith(bundleName,"/min") && !endsWith(bundleName,"/test");
          })));
        }

        var prevBundle = null;
        myIndexBnudles.forEach(function (bundleName) {
          var _bundleMap = {};
          var includedBundles = [];
          var bundledFile = dest + "/bootloader_bundled/" + bundleName.split("/").join(".") + ".js";
          var files = uniqueArray(getFiles(bundleName, [],bundledFile,includedBundles).reverse()).reverse();
          if(files.length>0){
            _bundleMap[bundledFile] = files;
            setBundleConfig(bundleName, _bundleMap,includedBundles);

            if(prevBundle){
              var bundle = resourcesJs.bundles[bundleName];
              if (bundle) {
                bundle.on = [prevBundle].concat(bundle.on)
              }
            }
            prevBundle = bundleName;

          } else console.log("No File in bundle to bundlify so skipping ",bundleName);
        });

        grunt.task.run("uglify");
      }

      grunt.file.write(dest + "/" + resourcesFile, JSON.stringify(resourcesJs));
    }
  });

};
<|endoftext|>


<commit_before>import assertString from './util/assertString';

export default function unescape(str) {
  assertString(str);
  return (str.replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(///g, '/')
    .replace(/`/g, '`'));
}
<commit_msg>Add missing string to unescape<commit_after>import assertString from './util/assertString';

export default function unescape(str) {
  assertString(str);
  return (str.replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(///g, '/')
    .replace(/\/g, '\\')
    .replace(/`/g, '`'));
}
<|endoftext|>


<commit_before>var CacheManager = function CacheManager(options, storageSpace, garbageCollector, objectSerializer, setSerializer) {
  this.options          = options;
  this.name             = options.name;
  this.debug            = options.debug;

  this.storageSpace     = storageSpace;
  this.collector        = garbageCollector;
  this.objectSerializer = objectSerializer;
  this.setSerializer    = setSerializer;
};

CacheManager.prototype._debug = function _debug(msg){
  if (this.debug) {
    console.log(msg)
  }
};

CacheManager.prototype.setObject = function setObject(key, value) {
  var newValue,
      storageSpace = this.storageSpace,
      objSerializer = this.objectSerializer;

  newValue = objSerializer.serialize(value);

  storageSpace.setItem(key, newValue)
};

CacheManager.prototype.setCategoricalSets = function setCategoricalSets(key, setsToSet, serialize) {
  var newValues, meta,
      _this = this,
      storageSpace = this.storageSpace,
      setSerializer = this.setSerializer,
      collector = this.collector;

  // serialize the new values regardless, in case of retry from err
  // if data needs to be serialized
  if (serialize) {
    meta = setSerializer.serialize(setsToSet);
    newValues = meta.serializedData;
    try {
      _this.setObject(key, newValues);
    }
    catch (err) {
      // cleans out the collector queue FIFO
      //collector.cleanUp(storageSpace);
      // retry setting the object, but with serialized values
      this.setCategoricalSets(key, newValues, true);
    }
    // if data has already been serialized
  } else if (!serialize) {
    try {
      _this.setObject(key, setsToSet)
    }
    catch (err) {
      this.setCategoricalSets(key,setsToSet, false)
    }
  } else {
    throw('Should this Data be serialized? --> boolean flag as third parameter')
  }
};

CacheManager.prototype.getObject = function getObject(key) {
  var objToDeserialize,
      deserializedObj,
      storageSpace = this.storageSpace,
      objSerializer = this.objectSerializer;

  //throw error if key is not a string
  if (!key === typeof String) {
    throw ('Error key is not a string')
  }

  //forces key to be a string if it's not
  objToDeserialize = storageSpace[key];

  //deseralized the object
  deserializedObj = objSerializer.deserialize(objToDeserialize);

  return deserializedObj;
};

CacheManager.prototype.getCategoricalSets = function getCategoricalSets(key) {
  var setsToDeserialize,
      deserializedSet,
      setSerializer = this.setSerializer;

  //JSON.parse[s the (TamperObj)]
  setsToDeserialize = this.getObject(key);

  deserializedSet = setSerializer.deserialize(setsToDeserialize);

  return deserializedSet
};

module.exports = CacheManager;<commit_msg>Changes variable naming to better semantic naming and refactors try/catch block.<commit_after>var CacheManager = function CacheManager(options, storageSpace, garbageCollector, objectSerializer, setSerializer) {
  this.options          = options;
  this.name             = options.name;
  this.debug            = options.debug;

  this.storageSpace     = storageSpace;
  this.collector        = garbageCollector;
  this.objectSerializer = objectSerializer;
  this.setSerializer    = setSerializer;
};

CacheManager.prototype._debug = function _debug(msg){
  if (this.debug) {
    console.log(msg)
  }
};

CacheManager.prototype.setObject = function setObject(key, value) {
  var newValue,
      storageSpace = this.storageSpace,
      objSerializer = this.objectSerializer;

  newValue = objSerializer.serialize(value);

  storageSpace.setItem(key, newValue)
};

CacheManager.prototype.setCategoricalSets = function setCategoricalSets(key, setsToSet) {
  var newValues,
      meta,
      _this = this,
      orderCachedById,
      storageSpace = this.storageSpace,
      setSerializer = this.setSerializer,
      collector = this.collector;

    // serialize the new values regardless, in case of retry from err
    meta = setSerializer.serialize(setsToSet);

    // new Values and the order in which they were cached by object id
    newValues = meta.serializedData;
    orderCachedById = meta.addedCounter;

    try {
      this.setObject(key, newValues)
    }

    catch(err) {
      this._debug('Error has been hit. Max Limit Reached.');
      //collector.cleanUp(storageSpace, orderCachedById);
      this.setCategoricalSets(key, newValues)
    }
};

CacheManager.prototype.getObject = function getObject(key) {
  var objToDeserialize,
      deserializedObj,
      storageSpace = this.storageSpace,
      objSerializer = this.objectSerializer;

  //throw error if key is not a string
  if (!key === typeof String) {
    throw ('Error key is not a string')
  }

  //forces key to be a string if it's not
  objToDeserialize = storageSpace[key];

  //deseralized the object
  deserializedObj = objSerializer.deserialize(objToDeserialize);

  return deserializedObj;
};

CacheManager.prototype.getCategoricalSets = function getCategoricalSets(key) {
  var setsToDeserialize,
      deserializedSet,
      setSerializer = this.setSerializer;

  //JSON.parse[s the (TamperObj)]
  setsToDeserialize = this.getObject(key);

  deserializedSet = setSerializer.deserialize(setsToDeserialize);

  return deserializedSet
};

module.exports = CacheManager;<|endoftext|>


<commit_before>// GPS 1.2 - JavaScript

// YOUR FULL NAMES:
//  1.
//  2.

// 1. "YOU SIGNED... WHO?!"

// 2. "Here they Come!"

// 3. "TIME IS MONEY!"

//YOUR CODE HERE!

var shooterMcGavin = new Client("Shooter McGavin", 48, "Just stay out of my way... or you'll pay. Listen to what I say.");
shooterMcGavin.constructor === Client;
shooterMcGavin.age === 48;
shooterMcGavin.quote === "Just stay out of my way... or you'll pay. Listen to what I say.";

// 4. "SHOW 'EM OFF!"

// ** BONUS **
<commit_msg>Updated the solution!<commit_after>// GPS 1.2 - JavaScript

// YOUR FULL NAMES:
//  1.Shawn Seibert
//  2.Samuel Davis

//  1. "YOU SIGNED... WHO?!"
var hFord = {
  name: "Harrison Ford",
  age: 71,
  quote: "Yes, I am Harrison Ford."
}

var dWashington = {
  name: "Denzel Washington",
  age: 59,
  quote: "You look like a bunch of 5th-grade sissies after a cat fight."
}

// 2. "Here they Come!"

var aSandler = {
  name: "Adam Sandler",
  age: 47,
  quote: "That's is your home? Are you too good for your home?!"
}

var kBell = {
  name: "Kristen Bell",
  age: 33,
  quote: "Do you wanna build a snowman?"
}

var jCarrey = {
  name: "Jim Carrey",
  age: 52,
  quote: "...So you're telling me there's a chance? YEAH!"
}

var clients = new Array(hFord, dWashington, aSandler, kBell, jCarrey)

//    3. "TIME IS MONEY!"

// YOUR CODE HERE!

function Client(name, age, quote)
{
  this.name = name
  this.age = age
  this.quote = quote
}// end function

var shooterMcGavin = new Client("Shooter McGavin", 48, "Just stay out of my way... or you'll pay. Listen to what I say.");
shooterMcGavin.constructor === Client;
shooterMcGavin.age === 48;
shooterMcGavin.quote === "Just stay out of my way... or you'll pay. Listen to what I say.";

//     4. "SHOW 'EM OFF!"
function printClients(clients)
  {
    for (var i=0; i < clients.length; i++) {
      console.log("Introducing " + clients[i].name + ", " + clients[i].age + ", and here is their live interview:" + clients[i].quote + "\n")
    }
  }

//       ** BONUS **
function addProp(clients)
  {
    clients[0].movie = "Star Wars"
    clients[1].movie = "Flight"
    clients[2].movie = "Grown Ups"
    clients[3].movie = "Frozen"
    clients[4].movie = "Series of Unfortunate Events"
  }
<|endoftext|>


<commit_before>/*
 * grunt-concat-css
 * https://github.com/urturn/grunt-concat-css
 *
 * Copyright (c) 2013 Olivier Amblet
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('concat_css', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      base: ""
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      var importStatements = [];
      var sources = [];

      var extractImportStatements = function (data){
        var rex = /@import.*\;/gim;
        var matches = data.css.match(rex);
        if(matches && matches.length > 0){
          grunt.log.write("Found " + matches.join(", "));
          data.imports = matches;
          data.css = data.css.replace(rex, '');
        }
      };

      var rebaseUrls = function (data) {
        function dirname(csspath){
          var splits = csspath.split('/');
          splits.pop();
          return splits.join('/');
        }

        function dataTransformFunc(basedir){
          return function(a, b) {
            return "url('"+path.join(basedir, b)+"')";
          };
        }
        var basedir = dirname(data.path);
        if(basedir){
          data.css = data.css.replace(/url\(['\"]?([^'\"\:]+)['\"]?\)/gm, dataTransformFunc(basedir));
        }
      };

      var imports = "";
      var cssSource = "";

      console.log(f.src, f.dest);
      // Concat specified files.
      var results = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        var data = {
          path: filepath,
          css: grunt.file.read(filepath)
        };
        console.log(data);
        extractImportStatements(data);
        rebaseUrls(data);
        if (data.imports) {
          imports += data.imports.join("\n") + "\n";
        }
        cssSource += data.css;
        return data;
      });

      // Write the destination file.
      grunt.file.write(f.dest, imports + cssSource);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<commit_msg>add rebaseUrls and debugMode options<commit_after>/*
 * grunt-concat-css
 * https://github.com/urturn/grunt-concat-css
 *
 * Copyright (c) 2013 Olivier Amblet
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('concat_css', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      base: "",
      rebaseUrls: true,
      debugMode: false
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      var importStatements = [];
      var sources = [];

      var extractImportStatements = function (data){
        var rex = /@import.*\;/gim;
        var matches = data.css.match(rex);
        if(matches && matches.length > 0){
          grunt.log.write("Found " + matches.join(", "));
          data.imports = matches;
          data.css = data.css.replace(rex, '');
        }
      };

      var rebaseUrls = function (data) {
        function dirname(csspath){
          var splits = csspath.split('/');
          splits.pop();
          return splits.join('/');
        }

        function dataTransformFunc(basedir){
          return function(a, b) {
            return "url('"+path.join(basedir, b)+"')";
          };
        }
        var basedir = dirname(data.path);
        if(basedir){
          data.css = data.css.replace(/url\(['\"]?([^'\"\:]+)['\"]?\)/gm, dataTransformFunc(basedir));
        }
      };

      var imports = "";
      var cssSource = "";

      options.debugMode && console.log(f.src, f.dest);
      // Concat specified files.
      var results = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        var data = {
          path: filepath,
          css: grunt.file.read(filepath)
        };
        options.debugMode && console.log(data);
        extractImportStatements(data);
        options.rebaseUrls && rebaseUrls(data);
        if (data.imports) {
          imports += data.imports.join("\n") + "\n";
        }
        cssSource += data.css;
        return data;
      });

      // Write the destination file.
      grunt.file.write(f.dest, imports + cssSource);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<|endoftext|>


<commit_before>const express = require('express');
const moment = require('moment');
const authHelper = require('../helpers/authentication');
const api = require('../api');

const router = express.Router();

// read here for updateding the tutorials.json: https://docs.schul-cloud.org/display/Intern/Hilfe-Artikel+aktualisieren
const tutorials = require('../helpers/content/tutorials.json');

// secure routes
router.use(authHelper.authChecker);

router.get('/', (req, res, next) => {
	res.render('help/help', {
		title: 'Hilfebereich',
		tutorials,
		adminFormIsActive: req.query.activeForm === 'admin',
		teamFormIsActive: req.query.activeForm === 'team',
	});
});

router.get('/releases', (req, res, next) => {
	api(req).get('/releases', {
		qs: {
			$sort: '-createdAt',
		},
	})
		.then((releases) => {
			// eslint-disable-next-line array-callback-return
			releases.data.map((release) => {
				release.body = converter.makeHtml(release.body);
				release.publishedAt = moment(release.publishedAt).format('ddd, ll');
			});

			res.render('help/releases', {
				breadcrumb: [
					{
						title: 'Hilfebereich',
						url: '/help',
					},
				],
				release: releases.data,
			});
		});
});

router.get('/confluence/:id', (req, res, next) => {
	res.render('help/confluence', {
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
		articleId: req.params.id,
	});
});

router.get('/faq/people', (req, res, next) => {
	res.render('help/people', {
		title: 'Ansprechpartner und Kontaktdaten',
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
	});
});

router.get('/faq/documents', async (req, res, next) => {
	const userRoles = res.locals.currentUser.roles.map(r => r.name);
	const isDemoUser = userRoles.some(r => r.startsWith('demo'));

	if (isDemoUser) {
		req.session.notification = {
			type: 'danger',
			message: 'Sie haben im Demo-Account keinen Zugriff auf diese Dokumente.',
		};
		return res.redirect('/help');
	}

	const documents = await api(req)
		.get('/help/documents/', { qs: { theme: res.locals.theme.name } })
		.catch(() => {
			req.session.notification = {
				type: 'danger',
				message: 'Es existieren womöglich keine Willkommensdokumente. Bitte wende dich an den User-Support.',
			};
			return res.redirect('/help');
		});

	return res.render('help/accordion-sections', {
		title: 'Willkommens-Dokumente zum Download',
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
		sections: documents,
	});
});

module.exports = router;
<commit_msg>restore used imports, removed in 378d45a08779cd1cee23922ec84aee743de698d6<commit_after>const express = require('express');
const moment = require('moment');
const { Converter } = require('showdown');
const authHelper = require('../helpers/authentication');
const api = require('../api');

const router = express.Router();
const converter = new Converter();

// read here for updateding the tutorials.json: https://docs.schul-cloud.org/display/Intern/Hilfe-Artikel+aktualisieren
const tutorials = require('../helpers/content/tutorials.json');

// secure routes
router.use(authHelper.authChecker);

router.get('/', (req, res, next) => {
	res.render('help/help', {
		title: 'Hilfebereich',
		tutorials,
		adminFormIsActive: req.query.activeForm === 'admin',
		teamFormIsActive: req.query.activeForm === 'team',
	});
});

router.get('/releases', (req, res, next) => {
	api(req).get('/releases', {
		qs: {
			$sort: '-createdAt',
		},
	})
		.then((releases) => {
			// eslint-disable-next-line array-callback-return
			releases.data.map((release) => {
				release.body = converter.makeHtml(release.body);
				release.publishedAt = moment(release.publishedAt).format('ddd, ll');
			});

			res.render('help/releases', {
				breadcrumb: [
					{
						title: 'Hilfebereich',
						url: '/help',
					},
				],
				release: releases.data,
			});
		});
});

router.get('/confluence/:id', (req, res, next) => {
	res.render('help/confluence', {
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
		articleId: req.params.id,
	});
});

router.get('/faq/people', (req, res, next) => {
	res.render('help/people', {
		title: 'Ansprechpartner und Kontaktdaten',
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
	});
});

router.get('/faq/documents', async (req, res, next) => {
	const userRoles = res.locals.currentUser.roles.map(r => r.name);
	const isDemoUser = userRoles.some(r => r.startsWith('demo'));

	if (isDemoUser) {
		req.session.notification = {
			type: 'danger',
			message: 'Sie haben im Demo-Account keinen Zugriff auf diese Dokumente.',
		};
		return res.redirect('/help');
	}

	const documents = await api(req)
		.get('/help/documents/', { qs: { theme: res.locals.theme.name } })
		.catch(() => {
			req.session.notification = {
				type: 'danger',
				message: 'Es existieren womöglich keine Willkommensdokumente. Bitte wende dich an den User-Support.',
			};
			return res.redirect('/help');
		});

	return res.render('help/accordion-sections', {
		title: 'Willkommens-Dokumente zum Download',
		breadcrumb: [
			{
				title: 'Hilfebereich',
				url: '/help',
			},
		],
		sections: documents,
	});
});

module.exports = router;
<|endoftext|>


<commit_before>(function(){
  'use strict';

  var gulp = require('gulp');
  var paths = require('./_paths');

  gulp.task('watch', function() {
    var lr = require('gulp-livereload');
    lr.listen();

    gulp.watch(paths.fonts, ['copy-fonts']);
    gulp.watch(paths.styles.concat(paths.icons), ['sass']);
    gulp.watch(paths.images, ['images']);
    gulp.watch(paths.vendor_static, ['copy-vendor-js']);
    gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
    gulp.watch(paths.guidance, ['guidance-build']);
    // watch built files and send reload event
    gulp.watch(paths.dest + '**/*').on('change', lr.changed);
  });
})();
<commit_msg>Watch e2e tests for changes and lint<commit_after>(function(){
  'use strict';

  var gulp = require('gulp');
  var paths = require('./_paths');

  gulp.task('watch', function() {
    var lr = require('gulp-livereload');
    lr.listen();

    gulp.watch(paths.fonts, ['copy-fonts']);
    gulp.watch(paths.styles.concat(paths.icons), ['sass']);
    gulp.watch(paths.images, ['images']);
    gulp.watch(paths.vendor_static, ['copy-vendor-js']);
    gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
    gulp.watch('tests/**/*.js', ['lint']);
    gulp.watch(paths.guidance, ['guidance-build']);
    // watch built files and send reload event
    gulp.watch(paths.dest + '**/*').on('change', lr.changed);
  });
})();
<|endoftext|>