<commit_before>
const { presets } = require('react-motion');
const _merge = require('lodash/merge');
const React = require('react');

const defaultSpring = {
    stiffness: 170,
    damping: 26,
    precision: 0.01
}

module.exports = {

    defaultSpring,

    assignDefaultsToAnimConfig: (animConfig) => {

        if (animConfig.leave) {

            const leaveAnimVals = _merge({}, animConfig.leave);

            if (!animConfig.start) {
                animConfig.start = leaveAnimVals;
            }
        }
        else if (animConfig.start) {
            animConfig.leave = animConfig.start;
        }

        if (!animConfig.beforeEnter) {
            animConfig.beforeEnter = _merge(
                {},
                animConfig.start
            );
        }

        return animConfig;
    },

    getElementsFromChildren: (children) => {

        if (!Array.isArray(children)) {
            children = [].concat(children);
        }

        return children.reduce((collector, child) => {

            if (React.isValidElement(child)) {
                collector.push(child);
            }

            return collector;
        }, []);
    },

    /*
        Also, for doggo-dish -- for each user that has access to an
        organization, make an encrypted copy of the key to unencrypt
        a single secure item. Each user gets a copy of the key to
        unencrypt each secure.
        Make a symmetrically encrypted copy of the user's password,
        save it locally and create different ways to unlock it.
        Make the doggo-dish server local, and offer the option to sync
        with a db.
        When you want to share, it will send a message out to the
        doggo-dish server saying it's got an invite waiting for someone.
        When the invited person signs in, their app checks the server, gets the
        invite and shares the secure item(s)
        To share a secure item, invite the person. This will require your
        encrypted key to be unencrypted, then encrypted for that person,
        and sent up for them to download
    */

    /*
        Returns:
        {
            assignedAnimConfig,
            delays
        }
    */

    assignAnimConfig: function({
        beginAnimConfig,
        newAnimConfig,
        reactMotion
    }) {

        if (!beginAnimConfig) {
            beginAnimConfig = newAnimConfig;
        }

        let delays = {};

        const assignedAnimConfig = Object.keys(beginAnimConfig)
        .reduce((collector, animStyleName) => {

            const beginAnimStyle = beginAnimConfig[animStyleName];
            const newAnimStyle = newAnimConfig[animStyleName] || beginAnimStyle;

            if (animStyleName === 'start' ||
               animStyleName === 'beforeEnter') {

               // These can't handle springs set on them

               collector[animStyleName] = newAnimConfig[animStyleName] || beginAnimConfig[animStyleName];
            }
            else {

                console.log(newAnimStyle);

                collector[animStyleName] = Object.keys(newAnimStyle)
                .reduce((newCSSProps, cssPropName) => {

                    let cssProp = newAnimStyle[cssPropName];

                    if (typeof cssProp === 'object') {

                        let additional = {};

                        // Special config settings

                        if (typeof cssProp.preset === 'string') {

                            const reactPreset = presets[cssProp.preset];

                            if (reactPreset) {
                                additional = presets[cssProp.preset];
                            }

                            // TODO pass in user options

                            // const userPreset = internals.userPresets[cssProp.preset];

                            // if (reactPreset) {
                            //     additional = internals.userPresets[cssProp.preset];
                            // }

                            delete cssProp.preset;
                        }

                        // spring is an alias for val

                        if (typeof cssProp.spring !== 'undefined') {
                            if (typeof cssProp.val !== 'undefined') {
                                throw new Error('Can\'t have spring and val both set');
                            }
                            cssProp.val = cssProp.spring;
                            delete cssProp.spring;
                        }

                        if (typeof cssProp.$delay !== 'undefined') {

                            // TODO Use something similar for the repeat prop

                            const { $delay, ...cssPropWithoutDelay } = cssProp;

                            // Set cssProp to the latest of reactMotion here
                            // cssProp = reactMotion.state.lastIdealStyle[cssPropName];

                            const delayedAnimConfig = {};
                            delayedAnimConfig[animStyleName] = {};
                            delayedAnimConfig[animStyleName][cssPropName] = cssPropWithoutDelay;

                            const animKeyDiff = Object.keys(beginAnimConfig[animStyleName])
                            .filter(function(item) {

                                return Object.keys(delayedAnimConfig[animStyleName])
                                .indexOf(item) < 0;
                            })
                            .reduce((collector, diffKey) => {

                                collector.enter[diffKey] = 'getLastIdealStyle';
                                return collector;
                            }, { enter: {} });

                            const delayObj = {};
                            delayObj[$delay] = _merge({},
                                animKeyDiff,
                                delayedAnimConfig
                            );

                            delays = _merge({},
                                delays,
                                delayObj
                            );
                        }

                        const beginStyleMerge = typeof beginAnimConfig[animStyleName][cssPropName] !== 'undefined' ?
                            beginAnimConfig[animStyleName][cssPropName] :
                            {};

                        if (cssProp.$delay) {

                            delete cssProp.$delay;
                            newCSSProps[cssPropName] = _merge(
                                {},
                                defaultSpring,
                                cssProp,
                                beginStyleMerge,
                                additional
                            );
                        }
                        else {
                            newCSSProps[cssPropName] = _merge(
                                {},
                                defaultSpring,
                                beginStyleMerge,
                                additional,
                                cssProp
                            );
                        }
                    }
                    else {

                        const beginStyleMerge = typeof beginAnimConfig[animStyleName][cssPropName] !== 'undefined' ?
                            beginAnimConfig[animStyleName][cssPropName] :
                            {};

                        newCSSProps[cssPropName] = _merge({},
                            defaultSpring,
                            beginStyleMerge,
                            { val: cssProp }
                        );
                    }

                    return newCSSProps;
                }, {});
            }

            return collector;
        }, {});

        if (Object.keys(delays).length === 0) {
            delays = undefined;
        }

        return {
            assignedAnimConfig,
            delays
        }
    },

    flattenCssPropsToValIfNeeded: function(cssProps) {

        return Object.keys(cssProps)
        .reduce((collector, cssPropName) => {

            const currentCssProp = cssProps[cssPropName];

            if (typeof currentCssProp === 'object' &&
                !Array.isArray(currentCssProp)) {

                const currentCssPropKeys = Object.keys(currentCssProp);

                if (currentCssPropKeys.length === 1 &&
                    currentCssPropKeys[0] === 'val') {

                    collector[cssPropName] = currentCssProp.val;
                }
                else {
                    collector[cssPropName] = currentCssProp;
                }
            }
            else {
                collector[cssPropName] = currentCssProp;
            }

            return collector;
        }, {});
    },

    debounce: function(func, wait, immediate) {

        let timeout;
        return (...args) => {

            const self = this;
            const later = () => {

                timeout = null;
                if (!immediate) {
                    func.apply(self, ...args);
                }
            };
            const callNow = immediate && !timeout;

            clearTimeout(timeout);

            timeout = setTimeout(later, wait);

            if (callNow) {
                func.apply(self, ...args);
            }
        }
    }
};
<commit_msg>Add default for enter, remove notes, refactor delay and beginCssProp<commit_after>
const { presets } = require('react-motion');
const _merge = require('lodash/merge');
const React = require('react');

const defaultSpring = {
    stiffness: 170,
    damping: 26,
    precision: 0.01
}

module.exports = {

    defaultSpring,

    assignDefaultsToAnimConfig: (animConfig) => {

        if (animConfig.leave) {

            const leaveAnimVals = _merge({}, animConfig.leave);

            if (!animConfig.start) {
                animConfig.start = leaveAnimVals;
            }
        }
        else if (animConfig.start) {
            animConfig.leave = animConfig.start;
            if (!animConfig.enter) {
                animConfig.enter = animConfig.start;
            }
        }

        if (!animConfig.beforeEnter) {
            animConfig.beforeEnter = _merge(
                {},
                animConfig.start
            );
        }

        return animConfig;
    },

    getElementsFromChildren: (children) => {

        if (!Array.isArray(children)) {
            children = [].concat(children);
        }

        return children.reduce((collector, child) => {

            if (React.isValidElement(child)) {
                collector.push(child);
            }

            return collector;
        }, []);
    },

    assignAnimConfig: function({
        beginAnimConfig,
        newAnimConfig,
        reactMotion
    }) {

        if (!beginAnimConfig) {
            beginAnimConfig = newAnimConfig;
        }

        let delays = {};

        const assignedAnimConfig = Object.keys(beginAnimConfig)
        .reduce((collector, animStyleName) => {

            const beginAnimStyle = beginAnimConfig[animStyleName];
            const newAnimStyle = newAnimConfig[animStyleName] || beginAnimStyle;

            if (animStyleName === 'start' ||
               animStyleName === 'beforeEnter') {

               // These can't handle springs set on them

               collector[animStyleName] = newAnimConfig[animStyleName] || beginAnimConfig[animStyleName];
            }
            else {

                collector[animStyleName] = Object.keys(newAnimStyle)
                .reduce((newCSSProps, cssPropName) => {

                    let cssProp = newAnimStyle[cssPropName];

                    const beginCssProp = typeof beginAnimConfig[animStyleName][cssPropName] !== 'undefined' ?
                    beginAnimConfig[animStyleName][cssPropName] : {};

                    if (typeof cssProp === 'object') {

                        let additional = {};

                        // Special config settings

                        if (typeof cssProp.preset === 'string') {

                            const reactPreset = presets[cssProp.preset];

                            if (reactPreset) {
                                additional = presets[cssProp.preset];
                            }

                            // TODO pass in user options

                            // const userPreset = internals.userPresets[cssProp.preset];

                            // if (userPreset) {
                            //     additional = internals.userPresets[userPreset];
                            // }

                            delete cssProp.preset;
                        }

                        // spring is an alias for val

                        if (typeof cssProp.spring !== 'undefined') {
                            if (typeof cssProp.val !== 'undefined') {
                                throw new Error('Can\'t have spring and val both set');
                            }
                            cssProp.val = cssProp.spring;
                            delete cssProp.spring;
                        }

                        if (typeof cssProp.$delay !== 'undefined') {

                            // TODO Use something similar for the repeat prop

                            const { $delay, ...cssPropWithoutDelay } = cssProp;

                            // Set cssProp to the latest of reactMotion here
                            // cssProp = reactMotion.state.lastIdealStyle[cssPropName];

                            const delayedAnimConfig = {};
                            delayedAnimConfig[animStyleName] = {};
                            delayedAnimConfig[animStyleName][cssPropName] = cssPropWithoutDelay;

                            const animKeyDiff = Object.keys(beginAnimConfig[animStyleName])
                            .filter(function(item) {

                                return Object.keys(delayedAnimConfig[animStyleName])
                                .indexOf(item) === -1;
                            })
                            .reduce((collector, diffKey) => {

                                collector.enter[diffKey] = 'getLastIdealStyle';
                                return collector;
                            }, { enter: {} });

                            const delayObj = {};
                            delayObj[$delay] = _merge({},
                                animKeyDiff,
                                delayedAnimConfig
                            );

                            delays = _merge({},
                                delays,
                                delayObj
                            );
                        }

                        if (cssProp.$delay) {

                            // Need to set this delay's key to the current one!!

                            delete cssProp.$delay;
                            newCSSProps[cssPropName] = _merge({},
                                defaultSpring,
                                beginCssProp,
                                additional,
                                cssProp
                            );
                        }
                        else {
                            newCSSProps[cssPropName] = _merge({},
                                defaultSpring,
                                beginCssProp,
                                additional,
                                cssProp
                            );
                        }
                    }
                    else {

                        newCSSProps[cssPropName] = _merge({},
                            defaultSpring,
                            beginCssProp,
                            { val: cssProp }
                        );
                    }

                    return newCSSProps;
                }, {});
            }

            return collector;
        }, {});

        if (Object.keys(delays).length === 0) {
            delays = undefined;
        }

        return {
            assignedAnimConfig,
            delays
        }
    },

    flattenCssPropsToValIfNeeded: function(cssProps) {

        return Object.keys(cssProps)
        .reduce((collector, cssPropName) => {

            const currentCssProp = cssProps[cssPropName];

            if (typeof currentCssProp === 'object' &&
                !Array.isArray(currentCssProp)) {

                const currentCssPropKeys = Object.keys(currentCssProp);

                if (currentCssPropKeys.length === 1 &&
                    currentCssPropKeys[0] === 'val') {

                    collector[cssPropName] = currentCssProp.val;
                }
                else {
                    collector[cssPropName] = currentCssProp;
                }
            }
            else {
                collector[cssPropName] = currentCssProp;
            }

            return collector;
        }, {});
    },

    debounce: function(func, wait, immediate) {

        let timeout;
        return (...args) => {

            const self = this;
            const later = () => {

                timeout = null;
                if (!immediate) {
                    func.apply(self, ...args);
                }
            };
            const callNow = immediate && !timeout;

            clearTimeout(timeout);

            timeout = setTimeout(later, wait);

            if (callNow) {
                func.apply(self, ...args);
            }
        }
    }
};
<|endoftext|>


<commit_before>var keyOf = attr('key');
var nodeOf = attr('node');

/**
 * A special value to use in the path list to represent the path 'to' a root object (which doesn't really
 * have any path). This prevents the need for special-casing detection of the root object and allows it
 * to be treated like any other object.
 *
 * This is kept as an object to take advantage that in an OO language, objects are guaranteed to be
 * distinct, therefore no other object can possibly clash with this one.
 */
var ROOT_PATH = {r:1};

/**
 * Listen to the given clarinet instance and progressively builds and stores the json based on the callbacks it provides.
 *
 * Notify on the given event bus when interesting things happen.
 *
 * Returns a function which gives access to the content built up so far
 *
 * @param clarinetParser our source of low-level events
 * @param {Function} fire a handle on an event bus to fire higher level events on when a new node
 *    or path is found
 */
function incrementalContentBuilder( clarinetParser, fire, on ) {

   var
         // array of nodes from curNode up to the root of the document.
         // the root is at the far end of the list, the current node is at the close end (the head)
         ascent

   ,     rootNode;

   function checkForMissedArrayKey(ascent, newLeafNode) {

      // for arrays we aren't pre-warned of the coming paths (there is no call to onkey like there
      // is for objects)
      // so we need to notify of the paths when we find the items:

      var parentNode = nodeOf(head(ascent));

      if (isOfType(Array, parentNode)) {

         pathFound(len(parentNode), newLeafNode);
      }
   }

   /**
    * Manage the state and notifications for when a new node is found.
    *
    * @param {*} newLeafNode the thing that has been found in the json
    * @function
    */
   function nodeFound( newLeafNode ) {

      if( !ascent ) {

         // we discovered the root node, it has a special path
         rootNode = newLeafNode;
         pathFound(ROOT_PATH, newLeafNode);

         return;
      }

      checkForMissedArrayKey(ascent, newLeafNode);

      // the node is a non-root node
      var branches = tail(ascent),
          parentBranch = head(branches),
          oldLeaf = head(ascent),
          newLeaf = mapping(keyOf(oldLeaf), newLeafNode);

      appendBuiltContent( parentBranch, newLeaf );

      ascent = cons(newLeaf, branches);
   }

   /**
    * Add a new value to the top-level object which has been already output
    */
   function appendBuiltContent( branch, leaf ){

      nodeOf(branch)[keyOf(leaf)] = nodeOf(leaf);
   }

   /**
    * Get a new key->node mapping
    *
    * @param {String|Number} key
    * @param {Object|Array|String|Number|null} node a value found in the json
    */
   function mapping(key, node) {
      return {key:key, node:node};
   }

   /**
    * For when we find a new key in the json.
    *
    * @param {String|Number|Object} key the key. If we are in an array will be a number, otherwise a string. May
    *    take the special value ROOT_PATH if the root node has just been found
    * @param {String|Number|Object|Array|Null|undefined} [maybeNode] usually this won't be known so can be undefined.
    *    can't use null because null is a valid value in some json
    **/
   function pathFound(key, maybeNode) {

      var newLeaf = mapping(key, maybeNode);

      if( ascent ) { // if not root

         // if we have the key but (unless adding to an array) no known value yet, at least put
         // that key in the output but against no defined value:
         appendBuiltContent( head(ascent), newLeaf );
      }

      ascent = cons(newLeaf, ascent);

      fire(TYPE_PATH, ascent);

   }

   /**
    * manages the state and notifications for when the current node has ended
    */
   function curNodeFinished( ) {

      fire(TYPE_NODE, ascent);

      // pop the complete node and its path off the lists:
      ascent = tail(ascent);
   }

   /*
    * Assign listeners to clarinet.
    */

   clarinetParser.onopenobject = function (firstKey) {

      nodeFound({});

      // It'd be odd but firstKey could be the empty string. This is valid json even though it isn't very nice.
      // so can't do !firstKey here, have to compare against undefined
      if( defined(firstKey) ) {

         // We know the first key of the newly parsed object. Notify that path has been found but don't put firstKey
         // perminantly onto pathList yet because we haven't identified what is at that key yet. Give null as the
         // value because we haven't seen that far into the json yet
         pathFound(firstKey);
      }
   };

   clarinetParser.onopenarray = function () {
      nodeFound([]);
   };

   // called by Clarinet when keys are found in objects
   clarinetParser.onkey = pathFound;

   clarinetParser.onvalue = function (value) {

      // Called for strings, numbers, boolean, null etc. These nodes are declared found and finished at once since they
      // can't have descendants.

      nodeFound(value);

      curNodeFinished();
   };

   clarinetParser.oncloseobject =
   clarinetParser.onclosearray =
      curNodeFinished;

   /**
    * If we abort this Oboe's request stop listening
    * to the clarinet parser. This prevents more tokens
    * being found after we abort in the case where we
    * aborted while reading though a current buffer.
    */
   on( ABORTING, function() {
      clarinet.EVENTS.forEach(function(event){
         // maybe not onerror
         clarinetParser['on'+event] = null;
      });
   });

   /* finally, return a function to get the root of the json (or undefined if not yet found) */
   return function() {
      return rootNode;
   }
}<commit_msg>incomplete note<commit_after>var keyOf = attr('key');
var nodeOf = attr('node');

/**
 * A special value to use in the path list to represent the path 'to' a root object (which doesn't really
 * have any path). This prevents the need for special-casing detection of the root object and allows it
 * to be treated like any other object. We might think of this as being similar to the unnamed root
 * domain: CITE THIS
 *
 * This is kept as an object to take advantage that in an OO language, objects are guaranteed to be
 * distinct, therefore no other object can possibly clash with this one. Strings, numbers etc provide
 * no such guarantee.
 */
var ROOT_PATH = {};

/**
 * Listen to the given clarinet instance and progressively builds and stores the json based on the callbacks it provides.
 *
 * Notify on the given event bus when interesting things happen.
 *
 * Returns a function which gives access to the content built up so far
 *
 * @param clarinetParser our source of low-level events
 * @param {Function} fire a handle on an event bus to fire higher level events on when a new node
 *    or path is found
 */
function incrementalContentBuilder( clarinetParser, fire, on ) {

   var
         // array of nodes from curNode up to the root of the document.
         // the root is at the far end of the list, the current node is at the close end (the head)
         ascent

   ,     rootNode;

   function checkForMissedArrayKey(ascent, newLeafNode) {

      // for arrays we aren't pre-warned of the coming paths (there is no call to onkey like there
      // is for objects)
      // so we need to notify of the paths when we find the items:

      var parentNode = nodeOf(head(ascent));

      if (isOfType(Array, parentNode)) {

         pathFound(len(parentNode), newLeafNode);
      }
   }

   /**
    * Manage the state and notifications for when a new node is found.
    *
    * @param {*} newLeafNode the thing that has been found in the json
    * @function
    */
   function nodeFound( newLeafNode ) {

      if( !ascent ) {

         // we discovered the root node, it has a special path
         rootNode = newLeafNode;
         pathFound(ROOT_PATH, newLeafNode);

         return;
      }

      checkForMissedArrayKey(ascent, newLeafNode);

      // the node is a non-root node
      var branches = tail(ascent),
          parentBranch = head(branches),
          oldLeaf = head(ascent),
          newLeaf = mapping(keyOf(oldLeaf), newLeafNode);

      appendBuiltContent( parentBranch, newLeaf );

      ascent = cons(newLeaf, branches);
   }

   /**
    * Add a new value to the top-level object which has been already output
    */
   function appendBuiltContent( branch, leaf ){

      nodeOf(branch)[keyOf(leaf)] = nodeOf(leaf);
   }

   /**
    * Get a new key->node mapping
    *
    * @param {String|Number} key
    * @param {Object|Array|String|Number|null} node a value found in the json
    */
   function mapping(key, node) {
      return {key:key, node:node};
   }

   /**
    * For when we find a new key in the json.
    *
    * @param {String|Number|Object} key the key. If we are in an array will be a number, otherwise a string. May
    *    take the special value ROOT_PATH if the root node has just been found
    * @param {String|Number|Object|Array|Null|undefined} [maybeNode] usually this won't be known so can be undefined.
    *    can't use null because null is a valid value in some json
    **/
   function pathFound(key, maybeNode) {

      var newLeaf = mapping(key, maybeNode);

      if( ascent ) { // if not root

         // if we have the key but (unless adding to an array) no known value yet, at least put
         // that key in the output but against no defined value:
         appendBuiltContent( head(ascent), newLeaf );
      }

      ascent = cons(newLeaf, ascent);

      fire(TYPE_PATH, ascent);

   }

   /**
    * manages the state and notifications for when the current node has ended
    */
   function curNodeFinished( ) {

      fire(TYPE_NODE, ascent);

      // pop the complete node and its path off the lists:
      ascent = tail(ascent);
   }

   /*
    * Assign listeners to clarinet.
    */

   clarinetParser.onopenobject = function (firstKey) {

      nodeFound({});

      // It'd be odd but firstKey could be the empty string. This is valid json even though it isn't very nice.
      // so can't do !firstKey here, have to compare against undefined
      if( defined(firstKey) ) {

         // We know the first key of the newly parsed object. Notify that path has been found but don't put firstKey
         // perminantly onto pathList yet because we haven't identified what is at that key yet. Give null as the
         // value because we haven't seen that far into the json yet
         pathFound(firstKey);
      }
   };

   clarinetParser.onopenarray = function () {
      nodeFound([]);
   };

   // called by Clarinet when keys are found in objects
   clarinetParser.onkey = pathFound;

   clarinetParser.onvalue = function (value) {

      // Called for strings, numbers, boolean, null etc. These nodes are declared found and finished at once since they
      // can't have descendants.

      nodeFound(value);

      curNodeFinished();
   };

   clarinetParser.oncloseobject =
   clarinetParser.onclosearray =
      curNodeFinished;

   /**
    * If we abort this Oboe's request stop listening
    * to the clarinet parser. This prevents more tokens
    * being found after we abort in the case where we
    * aborted while reading though a current buffer.
    */
   on( ABORTING, function() {
      clarinet.EVENTS.forEach(function(event){
         // maybe not onerror
         clarinetParser['on'+event] = null;
      });
   });

   /* finally, return a function to get the root of the json (or undefined if not yet found) */
   return function() {
      return rootNode;
   }
}<|endoftext|>


<commit_before>var config = {};

var running = false;

var version = 0.1;

require('./php.js');

function checkForValidURL(value)
{
	value = value.replace('localhost', '0.0.0.0');
    var urlregex = new RegExp("^((http|https):\/\/)?(www.)?([a-zA-Z0-9]|-)+([.][a-zA-Z0-9(-|\/|=|?#)?]+)+$");
    if (urlregex.test(value)) {
        return true;
    }
    return false;
}

var iniparser = require('iniparser');
iniparser.parse('./config.ini', function(err,data)
{
	if (err)
	{
		console.log('error reading config.ini');
		console.log(err);
	}
	else
	{
		var hasError = false;
		var port = data.port;

		if (port === undefined)
		{
			console.log('You must define a port in the config.ini file.');
			hasError = true;
		}
		else if (isNaN(port))
		{
			console.log('Port must be a number');
			hasError = true;
		}
		else
		{
			config.port = port;
		}

		if (!hasError)
		{
			startServer();
		}
	}

});

//save files
var tasksFile = './data/tasks.json';
var nextTasksFile = './data/nextTasks.json';
var pendingTasksFile = './data/pendingTasks.json';

//data
var tasks = {};
var nextTasks = {};
var pendingTasks = {};

//main part of app
var fs = require('fs');

loadSaveData = function()
{
	var returnValue = true;

	//load tasks
	if (fs.existsSync(tasksFile)) //load
	{
		var tasks = JSON.parse(fs.readFileSync(tasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('tasks'))
		{
			returnValue = false;
		}
	}

	//load nextTasks
	if (fs.existsSync(nextTasksFile)) //load
	{
		var nextTasks = JSON.parse(fs.readFileSync(nextTasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('nextTasks'))
		{
			returnValue = false;
		}
	}

	//load pendingTasks
	if (fs.existsSync(pendingTasksFile)) //load
	{
		var pendingTasks = JSON.parse(fs.readFileSync(pendingTasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('pendingTasks'))
		{
			returnValue = false;
		}
	}

	return returnValue; //temp
}

saveData = function (what)
{

}

saveDataSync = function (what)
{
	if (what == 'tasks')
	{
		fs.writeFileSync(tasksFile, JSON.stringify(tasks), 'utf8');

		if (fs.existsSync(tasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (what == 'nextTasks')
	{
		fs.writeFileSync(nextTasksFile, JSON.stringify(nextTasks), 'utf8');

		if (fs.existsSync(nextTasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (what == 'pendingTasks')
	{
		fs.writeFileSync(pendingTasksFile, JSON.stringify(pendingTasks), 'utf8');

		if (fs.existsSync(pendingTasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

startServer = function()
{
	if (loadSaveData())
	{
		running = true;
		//start task processer

		//start taking API calls

		var express = require('express');
		var app = express();

		app.use(express.bodyParser());

		app.get('/jobs', function(req, res){
		  res.send('hello world');
		});

		app.post('/addJob', function(req, res){
			var outJson = {};
			var valid = true;
			var errors = {};

			var title = trim(req.body.title);
			var scriptURL = trim(req.body.scriptURL);
			var when = trim(req.body.when);

			//validate title
			if (title.length > 0)
			{
				if (title.length > 255)
				{
					errors.title = 'long';
					valid = false;
				}
			}
			else
			{
				errors.title = 'short';
				valid = false;
			}

			//validate scriptURL
			if (!checkForValidURL(scriptURL))
			{
				errors.url = 'invalid';
				valid = false;
			}

			//validate when

			//output json
			outJson.errors = errors;
			res.send(outJson);
		});

		app.all('*', function (req, res) //404 error - Keep this as the last route
		{
			//uh 404!
			res.send('404');
		});

		app.listen(config.port);

		console.log('server running on port ' + config.port + '. \nCTRL + C to shutdown');
	}
	else
	{
		console.log('Error loading saved data.');
	}
}<commit_msg>port number validation<commit_after>var config = {};

var running = false;

var version = 0.1;

require('./php.js');

function checkForValidURL(value)
{
	value = value.replace('localhost', '0.0.0.0');
    var urlregex = new RegExp("^((http|https):\/\/)?(www.)?([a-zA-Z0-9]|-)+([.][a-zA-Z0-9(-|\/|=|?#)?]+)+$");
    if (urlregex.test(value)) {
        return true;
    }
    return false;
}

var iniparser = require('iniparser');
iniparser.parse('./config.ini', function(err,data)
{
	if (err)
	{
		console.log('error reading config.ini');
		console.log(err);
	}
	else
	{
		var hasError = false;
		var port = data.port;

		if (port === undefined)
		{
			console.log('You must define a port in the config.ini file.');
			hasError = true;
		}
		else if (isNaN(port))
		{
			console.log('Port must be a number');
			hasError = true;
		}
		else
		{
			config.port = port;
		}

		if (!hasError)
		{
			startServer();
		}
	}

});

//save files
var tasksFile = './data/tasks.json';
var nextTasksFile = './data/nextTasks.json';
var pendingTasksFile = './data/pendingTasks.json';

//data
var tasks = {};
var nextTasks = {};
var pendingTasks = {};

//main part of app
var fs = require('fs');

loadSaveData = function()
{
	var returnValue = true;

	//load tasks
	if (fs.existsSync(tasksFile)) //load
	{
		var tasks = JSON.parse(fs.readFileSync(tasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('tasks'))
		{
			returnValue = false;
		}
	}

	//load nextTasks
	if (fs.existsSync(nextTasksFile)) //load
	{
		var nextTasks = JSON.parse(fs.readFileSync(nextTasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('nextTasks'))
		{
			returnValue = false;
		}
	}

	//load pendingTasks
	if (fs.existsSync(pendingTasksFile)) //load
	{
		var pendingTasks = JSON.parse(fs.readFileSync(pendingTasksFile, 'utf8'));
	}
	else //save blank file
	{
		if (!saveDataSync('pendingTasks'))
		{
			returnValue = false;
		}
	}

	return returnValue; //temp
}

saveData = function (what)
{

}

saveDataSync = function (what)
{
	if (what == 'tasks')
	{
		fs.writeFileSync(tasksFile, JSON.stringify(tasks), 'utf8');

		if (fs.existsSync(tasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (what == 'nextTasks')
	{
		fs.writeFileSync(nextTasksFile, JSON.stringify(nextTasks), 'utf8');

		if (fs.existsSync(nextTasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (what == 'pendingTasks')
	{
		fs.writeFileSync(pendingTasksFile, JSON.stringify(pendingTasks), 'utf8');

		if (fs.existsSync(pendingTasksFile))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

startServer = function()
{
	if (loadSaveData())
	{
		running = true;
		//start task processer

		//start taking API calls

		var express = require('express');
		var app = express();

		app.use(express.bodyParser());

		app.get('/jobs', function(req, res){
		  res.send('hello world');
		});

		app.post('/addJob', function(req, res){
			var outJson = {};
			var valid = true;
			var errors = {};

			var title = trim(req.body.title);
			var scriptURL = trim(req.body.scriptURL);
			var when = trim(req.body.when);

			//validate title
			if (title.length > 0)
			{
				if (title.length > 255)
				{
					errors.title = 'long';
					valid = false;
				}
			}
			else
			{
				errors.title = 'short';
				valid = false;
			}

			//validate scriptURL
			if (!checkForValidURL(scriptURL))
			{
				errors.url = 'invalid';
				valid = false;
			}

			//validate when
			if (when == '')
			{
				when = 0;
			}

			if (isNaN(when))
			{
				errors.when = 'notNumber';
				valid = false;
			}
			else if (when < 1) //must be 1 or higher
			{
				errors.when = 'notPos';
				valid = false;
			}
			else if (when > 65535)
			{
				errors.when = 'highPort';
				valid = false;
			}

			//output json
			outJson.errors = errors;
			res.send(outJson);
		});

		app.all('*', function (req, res) //404 error - Keep this as the last route
		{
			//uh 404!
			res.send('404');
		});

		app.listen(config.port);

		console.log('server running on port ' + config.port + '. \nCTRL + C to shutdown');
	}
	else
	{
		console.log('Error loading saved data.');
	}
}<|endoftext|>


<commit_before>var generator = require('yeoman-generator')
  , uri = require('url')
  , path = require('path')
  , fs = require('fs')
  , util = require('util');

module.exports = generator.Base.extend({

  constructor: function () {
    generator.Base.apply(this, arguments);
  },

  initializing: function () {
    this.props = {};
    this.props.repositoryType = 'git';

    //this.props.dependencies = { foo: 'bar' };
    this.props.keywords = ['one', 'two']

    var path = this.destinationPath('package.json')
      , pkg;
    if (fs.existsSync(path)) {
      try {
        pkg = JSON.parse(fs.readFileSync(path));

        this.props.name = pkg.name;
        this.props.version = pkg.version;
        this.props.description = pkg.description;
        //this.props.keywords = pkg.keywords && pkg.keywords.join(', ');
        this.props.authorName = pkg.author && pkg.author.name;
        this.props.authorEmail = pkg.author && pkg.author.email;
        this.props.authorUrl = pkg.author && pkg.author.url;
        this.props.repositoryUrl = pkg.repository && pkg.repository.url;

        this.props.dependencies = pkg.dependencies ? pkg.dependencies : {
          foo: "barx",
          bax: "boox"
        };

      } catch (_) {}
    }
  },

  prompting: function() {
    var done = this.async();

    this.prompt([
      { type    : 'input',
        name    : 'name',
        message : 'Name',
        default : this.props.name || this.appname // default to name of current directory
      }, {
        type    : 'input',
        name    : 'version',
        message : 'Version',
        default : this.props.version || '0.0.0'
      }, {
        type    : 'input',
        name    : 'description',
        message : 'Description',
        default : this.props.description || ''
      }, {
        type    : 'input',
        name    : 'authorName',
        message : 'Author Name',
        default : this.props.authorName || ''
      }, {
        type    : 'input',
        name    : 'authorEmail',
        message : 'Author Email',
        default : this.props.authorEmail || ''
      }, {
        type    : 'input',
        name    : 'authorUrl',
        message : 'Author URL',
        default : this.props.authorUrl || ''
      }, {
        type    : 'input',
        name    : 'repositoryUrl',
        message : 'Repository URL',
        default : this.props.repositoryUrl || ''
      }, {
        type    : 'input',
        name    : 'licenseType',
        message : 'License',
        default : this.props.licenceType || ''
      }
    ], function (answers) {
      this.props.name = answers.name;
      this.props.version = answers.version;
      this.props.description = answers.description;
      this.props.authorName = answers.authorName;
      this.props.authorEmail = answers.authorEmail;
      this.props.authorUrl = answers.authorUrl;
      this.props.repositoryUrl = answers.repositoryUrl;
      this.props.licenseType = answers.licenseType;
      // FIXME
      this.props.bugsUrl = 'foo'
      this.props.licenseUrl = 'x';
      this.props.main = 'x';
      done();
    }.bind(this));
  },

  writing: function() {
    console.log(this.props)

    this.fs.copyTpl(this.templatePath('package2.json'), this.destinationPath('package.json'), this.props);

    this.fs.copy(this.templatePath('_gitignore'), this.destinationPath('.gitignore'));
    this.fs.copy(this.templatePath('_jshintrc'), this.destinationPath('.jshintrc'));
    this.fs.copy(this.templatePath('_npmignore'), this.destinationPath('.npmignore'));
    this.fs.copy(this.templatePath('_travis.yml'), this.destinationPath('.travis.yml'));
    this.fs.copy(this.templatePath('Makefile'), this.destinationPath('Makefile'));

    switch (this.props.licenseType) {
    case 'MIT':
      //this.template('licenses/MIT', 'LICENSE');
      break;
    default:
      break;
    }
  }

});

/*
function NodeGenerator(args, options) {
  generator.Base.apply(this, arguments);

  this.pkgDefaults = {
    'main': './lib',
    'dependencies': {
    },
    'devDependencies': {
      'mocha': '1.x.x',
      'chai': '1.x.x'
    },
    'engines': {
      'node': '*'
    },
    'scripts': {
      'test': 'node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js'
    }
  }

  if (existsSync('package.json')) {
    try {
      this.pkg = JSON.parse(fs.readFileSync('package.json'));
    } catch (_) {}
  }
}

util.inherits(NodeGenerator, generator.Base);

NodeGenerator.prototype.doPrompt = function() {
  var self = this;
  var done = this.async();

  var prompts = [{
    name: 'name',
    message: 'Name',
    default: this.pkg && this.pkg.name ? this.pkg.name : path.basename(process.cwd())
  }, {
    name: 'version',
    message: 'Version',
    default: this.pkg && this.pkg.version ? this.pkg.version : '0.0.0'
  }, {
    name: 'description',
    message: 'Description',
    default: this.pkg && this.pkg.description ? this.pkg.description : '',
    filter: function(input) { return input || 'TODO: No description specified'; }
  }, {
    name: 'keywords',
    message: 'Keywords',
    default: this.pkg && this.pkg.keywords ? this.pkg.keywords.join(', ') : '',
    filter: function(input) {
      if (!input) { return []; }
      var separators = [',', ' '];
      for (var i = 0, len = separators.length; i < len; i++) {
        var words = input.split(separators[i]);
        if (words.length > 1) {
          return words.map(function(word) { return word.trim(); });
        }
      }
      return [ input.trim() ];
    }
  }, {
    name: 'authorName',
    message: 'Author Name',
    default: this.pkg && this.pkg.author && this.pkg.author.name ? this.pkg.author.name : ''
  }, {
    name: 'authorEmail',
    message: 'Author Email',
    default: this.pkg && this.pkg.author && this.pkg.author.email ? this.pkg.author.email : ''
  }, {
    name: 'authorUrl',
    message: 'Author URL',
    default: this.pkg && this.pkg.author && this.pkg.author.url ? this.pkg.author.url : ''
  }, {
    name: 'repositoryUrl',
    message: 'Repository URL',
    default: this.pkg && this.pkg.repository && this.pkg.repository.url ? this.pkg.repository.url : '',
    filter: function(input) {
      var url = uri.parse(input);
      if (url.protocol) { return uri.format(url); }
      var segments = url.pathname.split('/');
      switch (segments.length) {
      case 2:
        return 'git://github.com/' + segments.join('/') + '.git';
      case 3:
        return 'git://' + segments.join('/') + '.git';
      }
      return input;
    }
  }, {
    name: 'licenseType',
    message: 'License',
    default: function() {
      if (self.pkg && self.pkg.licenses && self.pkg.licenses[0]) { return self.pkg.licenses[0].type || 'MIT'; }
      return 'MIT';
    }
  }];

  this.prompt(prompts, function(props) {
    this.props = props;

    var now = new Date();
    this.props.year = now.getFullYear();

    this.props.repositoryType = 'git';

    var repositoryUrl = uri.parse(props.repositoryUrl)
      , segments = repositoryUrl.pathname.slice(1).split('/')
    switch (repositoryUrl.hostname) {
      case 'github.com': {
        this.props.bugsUrl = 'http://github.com/' + segments[0] + '/' + segments[1].replace(/\.git$/, '') + '/issues';
        break;
      }
      default: {
        this.props.bugsUrl = this.pkg && this.pkg.bugs && this.pkg.bugs.url ? this.pkg.bugs.url : '';
        break;
      }
    }

    // TODO: Implement support for more license types
    if (props.licenseType == 'MIT') {
      props.licenseUrl = 'http://www.opensource.org/licenses/MIT';
    }

    this.props.main = this.pkg && this.pkg.main ? this.pkg.main : this.pkgDefaults.main;
    this.props.dependencies = this.pkg && this.pkg.dependencies ? this.pkg.dependencies : this.pkgDefaults.dependencies;
    this.props.devDependencies = this.pkg && this.pkg.devDependencies ? this.pkg.devDependencies : this.pkgDefaults.devDependencies;
    this.props.engines = this.pkg && this.pkg.engines ? this.pkg.engines : this.pkgDefaults.engines;
    this.props.scripts = this.pkg && this.pkg.scripts ? this.pkg.scripts : this.pkgDefaults.scripts;

    done();
  }.bind(this));
};

NodeGenerator.prototype.doGenerate = function() {
  if (!existsSync('README.md')) {
    this.template('README.md', 'README.md');
  }

  this.template('package.json', 'package.json');
  this.mkdir('lib');
  this.mkdir('test');
  this.mkdir('test/bootstrap');
  this.copy('test/bootstrap/node.js', 'test/bootstrap/node.js');
  if (!existsSync('test/package.test.js')) {
    this.template('test/package.test.js', 'test/package.test.js');
  }

  this.copy('_gitignore', '.gitignore');
  this.copy('_jshintrc', '.jshintrc');
  this.copy('_npmignore', '.npmignore');
  this.copy('_travis.yml', '.travis.yml');
  this.copy('Makefile', 'Makefile');
  this.directory('support', 'support');

  switch (this.props.licenseType) {
  case 'MIT':
    this.template('licenses/MIT', 'LICENSE');
    break;
  default:
    break;
  }
}

module.exports = NodeGenerator;
*/<commit_msg>Copy correct template.<commit_after>var generator = require('yeoman-generator')
  , uri = require('url')
  , path = require('path')
  , fs = require('fs')
  , util = require('util');

module.exports = generator.Base.extend({

  constructor: function () {
    generator.Base.apply(this, arguments);
  },

  initializing: function () {
    this.props = {};
    this.props.repositoryType = 'git';

    //this.props.dependencies = { foo: 'bar' };
    this.props.keywords = ['one', 'two']

    var path = this.destinationPath('package.json')
      , pkg;
    if (fs.existsSync(path)) {
      try {
        pkg = JSON.parse(fs.readFileSync(path));

        this.props.name = pkg.name;
        this.props.version = pkg.version;
        this.props.description = pkg.description;
        //this.props.keywords = pkg.keywords && pkg.keywords.join(', ');
        this.props.authorName = pkg.author && pkg.author.name;
        this.props.authorEmail = pkg.author && pkg.author.email;
        this.props.authorUrl = pkg.author && pkg.author.url;
        this.props.repositoryUrl = pkg.repository && pkg.repository.url;

        this.props.dependencies = pkg.dependencies ? pkg.dependencies : {
          foo: "barx",
          bax: "boox"
        };

      } catch (_) {}
    }
  },

  prompting: function() {
    var done = this.async();

    this.prompt([
      { type    : 'input',
        name    : 'name',
        message : 'Name',
        default : this.props.name || this.appname // default to name of current directory
      }, {
        type    : 'input',
        name    : 'version',
        message : 'Version',
        default : this.props.version || '0.0.0'
      }, {
        type    : 'input',
        name    : 'description',
        message : 'Description',
        default : this.props.description || ''
      }, {
        type    : 'input',
        name    : 'authorName',
        message : 'Author Name',
        default : this.props.authorName || ''
      }, {
        type    : 'input',
        name    : 'authorEmail',
        message : 'Author Email',
        default : this.props.authorEmail || ''
      }, {
        type    : 'input',
        name    : 'authorUrl',
        message : 'Author URL',
        default : this.props.authorUrl || ''
      }, {
        type    : 'input',
        name    : 'repositoryUrl',
        message : 'Repository URL',
        default : this.props.repositoryUrl || ''
      }, {
        type    : 'input',
        name    : 'licenseType',
        message : 'License',
        default : this.props.licenceType || ''
      }
    ], function (answers) {
      this.props.name = answers.name;
      this.props.version = answers.version;
      this.props.description = answers.description;
      this.props.authorName = answers.authorName;
      this.props.authorEmail = answers.authorEmail;
      this.props.authorUrl = answers.authorUrl;
      this.props.repositoryUrl = answers.repositoryUrl;
      this.props.licenseType = answers.licenseType;
      // FIXME
      this.props.bugsUrl = 'foo'
      this.props.licenseUrl = 'x';
      this.props.main = 'x';
      done();
    }.bind(this));
  },

  writing: function() {
    console.log(this.props)

    this.fs.copyTpl(this.templatePath('package.json'), this.destinationPath('package.json'), this.props);

    this.fs.copy(this.templatePath('_gitignore'), this.destinationPath('.gitignore'));
    this.fs.copy(this.templatePath('_jshintrc'), this.destinationPath('.jshintrc'));
    this.fs.copy(this.templatePath('_npmignore'), this.destinationPath('.npmignore'));
    this.fs.copy(this.templatePath('_travis.yml'), this.destinationPath('.travis.yml'));
    this.fs.copy(this.templatePath('Makefile'), this.destinationPath('Makefile'));

    switch (this.props.licenseType) {
    case 'MIT':
      //this.template('licenses/MIT', 'LICENSE');
      break;
    default:
      break;
    }
  }

});

/*
function NodeGenerator(args, options) {
  generator.Base.apply(this, arguments);

  this.pkgDefaults = {
    'main': './lib',
    'dependencies': {
    },
    'devDependencies': {
      'mocha': '1.x.x',
      'chai': '1.x.x'
    },
    'engines': {
      'node': '*'
    },
    'scripts': {
      'test': 'node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js'
    }
  }

  if (existsSync('package.json')) {
    try {
      this.pkg = JSON.parse(fs.readFileSync('package.json'));
    } catch (_) {}
  }
}

util.inherits(NodeGenerator, generator.Base);

NodeGenerator.prototype.doPrompt = function() {
  var self = this;
  var done = this.async();

  var prompts = [{
    name: 'name',
    message: 'Name',
    default: this.pkg && this.pkg.name ? this.pkg.name : path.basename(process.cwd())
  }, {
    name: 'version',
    message: 'Version',
    default: this.pkg && this.pkg.version ? this.pkg.version : '0.0.0'
  }, {
    name: 'description',
    message: 'Description',
    default: this.pkg && this.pkg.description ? this.pkg.description : '',
    filter: function(input) { return input || 'TODO: No description specified'; }
  }, {
    name: 'keywords',
    message: 'Keywords',
    default: this.pkg && this.pkg.keywords ? this.pkg.keywords.join(', ') : '',
    filter: function(input) {
      if (!input) { return []; }
      var separators = [',', ' '];
      for (var i = 0, len = separators.length; i < len; i++) {
        var words = input.split(separators[i]);
        if (words.length > 1) {
          return words.map(function(word) { return word.trim(); });
        }
      }
      return [ input.trim() ];
    }
  }, {
    name: 'authorName',
    message: 'Author Name',
    default: this.pkg && this.pkg.author && this.pkg.author.name ? this.pkg.author.name : ''
  }, {
    name: 'authorEmail',
    message: 'Author Email',
    default: this.pkg && this.pkg.author && this.pkg.author.email ? this.pkg.author.email : ''
  }, {
    name: 'authorUrl',
    message: 'Author URL',
    default: this.pkg && this.pkg.author && this.pkg.author.url ? this.pkg.author.url : ''
  }, {
    name: 'repositoryUrl',
    message: 'Repository URL',
    default: this.pkg && this.pkg.repository && this.pkg.repository.url ? this.pkg.repository.url : '',
    filter: function(input) {
      var url = uri.parse(input);
      if (url.protocol) { return uri.format(url); }
      var segments = url.pathname.split('/');
      switch (segments.length) {
      case 2:
        return 'git://github.com/' + segments.join('/') + '.git';
      case 3:
        return 'git://' + segments.join('/') + '.git';
      }
      return input;
    }
  }, {
    name: 'licenseType',
    message: 'License',
    default: function() {
      if (self.pkg && self.pkg.licenses && self.pkg.licenses[0]) { return self.pkg.licenses[0].type || 'MIT'; }
      return 'MIT';
    }
  }];

  this.prompt(prompts, function(props) {
    this.props = props;

    var now = new Date();
    this.props.year = now.getFullYear();

    this.props.repositoryType = 'git';

    var repositoryUrl = uri.parse(props.repositoryUrl)
      , segments = repositoryUrl.pathname.slice(1).split('/')
    switch (repositoryUrl.hostname) {
      case 'github.com': {
        this.props.bugsUrl = 'http://github.com/' + segments[0] + '/' + segments[1].replace(/\.git$/, '') + '/issues';
        break;
      }
      default: {
        this.props.bugsUrl = this.pkg && this.pkg.bugs && this.pkg.bugs.url ? this.pkg.bugs.url : '';
        break;
      }
    }

    // TODO: Implement support for more license types
    if (props.licenseType == 'MIT') {
      props.licenseUrl = 'http://www.opensource.org/licenses/MIT';
    }

    this.props.main = this.pkg && this.pkg.main ? this.pkg.main : this.pkgDefaults.main;
    this.props.dependencies = this.pkg && this.pkg.dependencies ? this.pkg.dependencies : this.pkgDefaults.dependencies;
    this.props.devDependencies = this.pkg && this.pkg.devDependencies ? this.pkg.devDependencies : this.pkgDefaults.devDependencies;
    this.props.engines = this.pkg && this.pkg.engines ? this.pkg.engines : this.pkgDefaults.engines;
    this.props.scripts = this.pkg && this.pkg.scripts ? this.pkg.scripts : this.pkgDefaults.scripts;

    done();
  }.bind(this));
};

NodeGenerator.prototype.doGenerate = function() {
  if (!existsSync('README.md')) {
    this.template('README.md', 'README.md');
  }

  this.template('package.json', 'package.json');
  this.mkdir('lib');
  this.mkdir('test');
  this.mkdir('test/bootstrap');
  this.copy('test/bootstrap/node.js', 'test/bootstrap/node.js');
  if (!existsSync('test/package.test.js')) {
    this.template('test/package.test.js', 'test/package.test.js');
  }

  this.copy('_gitignore', '.gitignore');
  this.copy('_jshintrc', '.jshintrc');
  this.copy('_npmignore', '.npmignore');
  this.copy('_travis.yml', '.travis.yml');
  this.copy('Makefile', 'Makefile');
  this.directory('support', 'support');

  switch (this.props.licenseType) {
  case 'MIT':
    this.template('licenses/MIT', 'LICENSE');
    break;
  default:
    break;
  }
}

module.exports = NodeGenerator;
*/<|endoftext|>


<commit_before>ngapp.config(['$stateProvider', function($stateProvider) {
    $stateProvider.state('base', {
        url: '',
        redirectTo: 'base.start',
        templateUrl: 'partials/base.html',
        controller: 'baseController'
    });
}]);

ngapp.controller('baseController', function($scope, $rootScope, $document, $q, $timeout, settingsService, themeService, buttonFactory, modalService, htmlHelpers) {
    // helper variables
    let currentWindow = remote.getCurrentWindow(),
        themeStylesheet = document.getElementById('theme'),
        syntaxThemeStylesheet = document.getElementById('syntaxTheme');

    // helper functions
    let toggleMaximized = (w) => w.isMaximized() ? w.unmaximize() : w.maximize();
    let modalActive = function(modalName) {
        let opts = $scope.modalOptions;
        return $rootScope.modalActive && opts && opts.modal === modalName;
    };

    // scope functions
    $scope.buttonClick = (button, e) => button.onClick($scope, e);
    $scope.extensionsClick = () => $scope.$emit('openModal', 'manageExtensions');
    $scope.settingsClick = () => $scope.$broadcast('settingsClick');
    $scope.helpClick = () => $scope.$emit('openModal', 'help');
    $scope.minimizeClick = () => currentWindow.minimize();
    $scope.restoreClick = () => toggleMaximized(currentWindow);
    $scope.closeClick = () => currentWindow.close();

    // prompt modal functions
    $rootScope.prompt = function(options) {
        $scope.promptPromise = $q.defer();
        $scope.$emit('openModal', 'prompt', options);
        return $scope.promptPromise.promise;
    };

    // event handlers
    $scope.$on('startDrag', (e, dragData) => $rootScope.dragData = dragData);
    $scope.$on('stopDrag', () => $rootScope.dragData = undefined);
    $scope.$on('setTitle', (e, title) => $scope.title = title);
    $scope.$on('setTheme', (e, theme) => $scope.theme = theme);
    $scope.$on('setSyntaxTheme', (e, theme) => $scope.syntaxTheme = theme);

    $scope.$on('openContextMenu', function(e, offset, items) {
        if (!items.length) return;
        $timeout(function() {
            $scope.showContextMenu = true;
            $scope.contextMenuOffset = offset;
            let buildTemplateUrl = function(item) {
                item.templateUrl = `directives/contextMenu${item.divider ? 'Divider' : 'Item'}.html`;
                if (item.children) item.children.forEach(buildTemplateUrl);
            };
            items.forEach(buildTemplateUrl);
            $scope.contextMenuItems = items;
        });
    });

    $scope.$on('closeContextMenu', function(e) {
        $scope.showContextMenu = false;
        e.stopPropagation();
    });

    $scope.$on('openModal', function(e, label, options = {}) {
        $scope.$evalAsync(function() {
            $rootScope.modalActive = true;
            $scope.modalOptions = modalService.buildOptions(label, options);
            $scope.showModal = true;
        });
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('closeModal', function(e) {
        $scope.$applyAsync(function() {
            $rootScope.modalActive = false;
            $scope.modalOptions = undefined;
            $scope.showModal = false;
        });
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('restart', function() {
        remote.app.relaunch();
        remote.app.forceClose = true;
        currentWindow.close();
    });

    $scope.$on('terminate', function() {
        remote.app.forceClose = true;
        currentWindow.close();
    });

    $scope.$watch('title', () => document.title = $scope.title);

    $scope.$watch('theme', function() {
        themeStylesheet.href = fh.jetpack.path(`themes/${$scope.theme}`);
        $scope.$broadcast('themeChanged', $scope.theme);
    });

    $scope.$watch('syntaxTheme', function() {
        if ($scope.syntaxTheme === '') {
            syntaxThemeStylesheet.href = '';
        } else {
            let syntaxThemePath = `syntaxThemes/${$scope.syntaxTheme}`;
            syntaxThemeStylesheet.href = fh.jetpack.path(syntaxThemePath);
        }
        $scope.$broadcast('syntaxThemeChanged', $scope.syntaxTheme);
    });

    // documentation navigation
    ipcRenderer.on('docs-navigate', function(e, url) {
        if (!modalActive('help')) $scope.$emit('openModal', 'help');
        $scope.$broadcast('helpNavigateTo', url.substr(7));
    });

    // hide context menu when user clicks in document
    $document.bind('mousedown', function(e) {
        if ($scope.showContextMenu) {
            let parentMenu = htmlHelpers.findParent(e.srcElement, function(element) {
                return element.tagName === 'CONTEXT-MENU';
            });
            if (parentMenu) return;
            $scope.$applyAsync(() => $scope.showContextMenu = false);
        }
    });

    // hide context menu when window loses focus
    window.onblur = () => $scope.$applyAsync(() => $scope.showContextMenu = false);

    // global keyboard shortcuts
    $document.bind('keydown', function(e) {
        if (e.keyCode === 73 && e.shiftKey && e.ctrlKey) { // ctrl + shift + i
            currentWindow.toggleDevTools();
        } else if (e.keyCode === 83 && e.ctrlKey) { // ctrl + s
            $scope.$broadcast('save');
        }
    });

    // initialization
    settingsService.loadGlobalSettings();
    $scope.title = 'zEdit - New Session';
    $scope.buttons = buttonFactory.buttons;
    $scope.theme = themeService.getCurrentTheme();
    $scope.syntaxTheme = themeService.getCurrentSyntaxTheme();
    $scope.$emit('appStart');
});
<commit_msg>now initializing protocol service in base.js<commit_after>ngapp.config(['$stateProvider', function($stateProvider) {
    $stateProvider.state('base', {
        url: '',
        redirectTo: 'base.start',
        templateUrl: 'partials/base.html',
        controller: 'baseController'
    });
}]);

ngapp.controller('baseController', function($scope, $rootScope, $document, $q, $timeout, settingsService, themeService, protocolService, buttonFactory, modalService, htmlHelpers) {
    // helper variables
    let currentWindow = remote.getCurrentWindow(),
        themeStylesheet = document.getElementById('theme'),
        syntaxThemeStylesheet = document.getElementById('syntaxTheme');

    // helper functions
    let toggleMaximized = (w) => w.isMaximized() ? w.unmaximize() : w.maximize();
    let modalActive = function(modalName) {
        let opts = $scope.modalOptions;
        return $rootScope.modalActive && opts && opts.modal === modalName;
    };

    // scope functions
    $scope.buttonClick = (button, e) => button.onClick($scope, e);
    $scope.extensionsClick = () => $scope.$emit('openModal', 'manageExtensions');
    $scope.settingsClick = () => $scope.$broadcast('settingsClick');
    $scope.helpClick = () => $scope.$emit('openModal', 'help');
    $scope.minimizeClick = () => currentWindow.minimize();
    $scope.restoreClick = () => toggleMaximized(currentWindow);
    $scope.closeClick = () => currentWindow.close();

    // prompt modal functions
    $rootScope.prompt = function(options) {
        $scope.promptPromise = $q.defer();
        $scope.$emit('openModal', 'prompt', options);
        return $scope.promptPromise.promise;
    };

    // event handlers
    $scope.$on('startDrag', (e, dragData) => $rootScope.dragData = dragData);
    $scope.$on('stopDrag', () => $rootScope.dragData = undefined);
    $scope.$on('setTitle', (e, title) => $scope.title = title);
    $scope.$on('setTheme', (e, theme) => $scope.theme = theme);
    $scope.$on('setSyntaxTheme', (e, theme) => $scope.syntaxTheme = theme);

    $scope.$on('openContextMenu', function(e, offset, items) {
        if (!items.length) return;
        $timeout(function() {
            $scope.showContextMenu = true;
            $scope.contextMenuOffset = offset;
            let buildTemplateUrl = function(item) {
                item.templateUrl = `directives/contextMenu${item.divider ? 'Divider' : 'Item'}.html`;
                if (item.children) item.children.forEach(buildTemplateUrl);
            };
            items.forEach(buildTemplateUrl);
            $scope.contextMenuItems = items;
        });
    });

    $scope.$on('closeContextMenu', function(e) {
        $scope.showContextMenu = false;
        e.stopPropagation();
    });

    $scope.$on('openModal', function(e, label, options = {}) {
        $scope.$evalAsync(function() {
            $rootScope.modalActive = true;
            $scope.modalOptions = modalService.buildOptions(label, options);
            $scope.showModal = true;
        });
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('closeModal', function(e) {
        $scope.$applyAsync(function() {
            $rootScope.modalActive = false;
            $scope.modalOptions = undefined;
            $scope.showModal = false;
        });
        e.stopPropagation && e.stopPropagation();
    });

    $scope.$on('restart', function() {
        remote.app.relaunch();
        remote.app.forceClose = true;
        currentWindow.close();
    });

    $scope.$on('terminate', function() {
        remote.app.forceClose = true;
        currentWindow.close();
    });

    $scope.$watch('title', () => document.title = $scope.title);

    $scope.$watch('theme', function() {
        themeStylesheet.href = fh.jetpack.path(`themes/${$scope.theme}`);
        $scope.$broadcast('themeChanged', $scope.theme);
    });

    $scope.$watch('syntaxTheme', function() {
        if ($scope.syntaxTheme === '') {
            syntaxThemeStylesheet.href = '';
        } else {
            let syntaxThemePath = `syntaxThemes/${$scope.syntaxTheme}`;
            syntaxThemeStylesheet.href = fh.jetpack.path(syntaxThemePath);
        }
        $scope.$broadcast('syntaxThemeChanged', $scope.syntaxTheme);
    });

    // documentation navigation
    ipcRenderer.on('docs-navigate', function(e, url) {
        if (!modalActive('help')) $scope.$emit('openModal', 'help');
        $scope.$broadcast('helpNavigateTo', url.substr(7));
    });

    // hide context menu when user clicks in document
    $document.bind('mousedown', function(e) {
        if ($scope.showContextMenu) {
            let parentMenu = htmlHelpers.findParent(e.srcElement, function(element) {
                return element.tagName === 'CONTEXT-MENU';
            });
            if (parentMenu) return;
            $scope.$applyAsync(() => $scope.showContextMenu = false);
        }
    });

    // hide context menu when window loses focus
    window.onblur = () => $scope.$applyAsync(() => $scope.showContextMenu = false);

    // global keyboard shortcuts
    $document.bind('keydown', function(e) {
        if (e.keyCode === 73 && e.shiftKey && e.ctrlKey) { // ctrl + shift + i
            currentWindow.toggleDevTools();
        } else if (e.keyCode === 83 && e.ctrlKey) { // ctrl + s
            $scope.$broadcast('save');
        }
    });

    // initialization
    protocolService.init($scope);
    settingsService.loadGlobalSettings();
    $scope.title = 'zEdit - New Session';
    $scope.buttons = buttonFactory.buttons;
    $scope.theme = themeService.getCurrentTheme();
    $scope.syntaxTheme = themeService.getCurrentSyntaxTheme();
    $scope.$emit('appStart');
});
<|endoftext|>


<commit_before>// dependencies -------------------------------------------------------------------

/**
 * If the current enviroment is server side
 * nodejs/iojs import fs.
 */
if (typeof window === 'undefined') {
    var fs = require('fs');
}

// public API ---------------------------------------------------------------------

var fileUtils = {
	readFile: readFile,
    readDir: readDir,
	generateTree: generateTree
};

// implementations ----------------------------------------------------------------

/**
 * Read
 *
 * A helper method for reading file contents.
 * Takes a file object and a callback and calls
 * the callback with the binary contents of the
 * file as the only argument.
 *
 * In the browser the file should be a file object.
 * In node the file should be a path to a file.
 *
 */
function readFile (file, callback) {
    if (fs) {
        fs.readFile(file.path, 'utf8', function (err, data) {
            if (err) {
                callback(err);
            } else {
                callback(data);
            }
        });
    } else {
    	var reader = new FileReader();
    	reader.onloadend = function (e) {
    		if (e.target.readyState == FileReader.DONE) {
    			callback(e.target.result);
    		}
    	};
    	reader.readAsBinaryString(file);
    }
}

/**
 * Read Directory
 *
 * Takes a path to a directory and returns an
 * array containing all of the files to a callback.
 * Used to input and organize files in node, in a
 * similar structure to how chrome reads a
 * directory.
 */
function readDir (path, callback) {
    if (fs) {
        files = getFiles(path);
        filesObj = {};
        for (var i = 0; i < files.length; i++) {
            filesObj[i] = {name: files[i].substr(files[i].lastIndexOf('/') + 1), path: files[i]};
        }
        callback(filesObj);
    }
}

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

/**
 * Generate Tree
 *
 * Takes a files object of a selected directory
 * and restructures them from a flat array to a
 * tree following the structure of the original
 * directory.
 */
function generateTree (files) {
	var pathList = {};
	var dirTree = {};

    // generate list of paths
	for (var i = 0; i < files.length; i++) {
		var file = files[i];
        pathList[file.webkitRelativePath] = file;
    }

    // build path from list
    for (var key in pathList) {
    	var path = key;
    	var pathParts = path.split('/');
    	var subObj = dirTree;
    	for (var j = 0; j < pathParts.length; j++) {
    		var part = pathParts[j];
    		if (!subObj[part]) {
    			subObj[part] = j < pathParts.length - 1 ? {} : pathList[key];
    		}
    		subObj = subObj[part];
    	}
    }

	// convert dirTree to array structure
    function objToArr (obj) {
    	var arr = [];
    	for (var key in obj) {
    		if (obj[key].webkitRelativePath && obj[key].webkitRelativePath.length > 0) {
    			arr.push(obj[key]);
    		} else {
    			arr.push({name: key, type: 'folder', children: objToArr(obj[key])});
    		}
    	}
    	return arr;
	}

	dirTree = objToArr(dirTree);

    // return tree
    return dirTree;
}

module.exports = fileUtils;<commit_msg>added relative path to files object on server side<commit_after>// dependencies -------------------------------------------------------------------

/**
 * If the current enviroment is server side
 * nodejs/iojs import fs.
 */
if (typeof window === 'undefined') {
    var fs = require('fs');
}

// public API ---------------------------------------------------------------------

var fileUtils = {
	readFile: readFile,
    readDir: readDir,
	generateTree: generateTree
};

// implementations ----------------------------------------------------------------

/**
 * Read
 *
 * A helper method for reading file contents.
 * Takes a file object and a callback and calls
 * the callback with the binary contents of the
 * file as the only argument.
 *
 * In the browser the file should be a file object.
 * In node the file should be a path to a file.
 *
 */
function readFile (file, callback) {
    if (fs) {
        fs.readFile(file.path, 'utf8', function (err, data) {
            if (err) {
                callback(err);
            } else {
                callback(data);
            }
        });
    } else {
    	var reader = new FileReader();
    	reader.onloadend = function (e) {
    		if (e.target.readyState == FileReader.DONE) {
    			callback(e.target.result);
    		}
    	};
    	reader.readAsBinaryString(file);
    }
}

/**
 * Read Directory
 *
 * Takes a path to a directory and returns an
 * array containing all of the files to a callback.
 * Used to input and organize files in node, in a
 * similar structure to how chrome reads a
 * directory.
 */
function readDir (path, callback) {
    if (fs) {
        files = getFiles(path);
        filesObj = {};
        var str = path.substr(path.lastIndexOf('/') + 1) + '$';
        var subpath = path.replace(new RegExp(str), '');
        for (var i = 0; i < files.length; i++) {
            filesObj[i] = {
                name: files[i].substr(files[i].lastIndexOf('/') + 1),
                path: files[i],
                relativePath: files[i].replace(subpath, '')
            };
        }
        callback(filesObj);
    }
}

function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
}

/**
 * Generate Tree
 *
 * Takes a files object of a selected directory
 * and restructures them from a flat array to a
 * tree following the structure of the original
 * directory.
 */
function generateTree (files) {
	var pathList = {};
	var dirTree = {};

    // generate list of paths
	for (var i = 0; i < files.length; i++) {
		var file = files[i];
        pathList[file.webkitRelativePath] = file;
    }

    // build path from list
    for (var key in pathList) {
    	var path = key;
    	var pathParts = path.split('/');
    	var subObj = dirTree;
    	for (var j = 0; j < pathParts.length; j++) {
    		var part = pathParts[j];
    		if (!subObj[part]) {
    			subObj[part] = j < pathParts.length - 1 ? {} : pathList[key];
    		}
    		subObj = subObj[part];
    	}
    }

	// convert dirTree to array structure
    function objToArr (obj) {
    	var arr = [];
    	for (var key in obj) {
    		if (obj[key].webkitRelativePath && obj[key].webkitRelativePath.length > 0) {
    			arr.push(obj[key]);
    		} else {
    			arr.push({name: key, type: 'folder', children: objToArr(obj[key])});
    		}
    	}
    	return arr;
	}

	dirTree = objToArr(dirTree);

    // return tree
    return dirTree;
}

module.exports = fileUtils;<|endoftext|>


<commit_before>const dotenv = require('dotenv');
const http = require('http');
const path = require('path');
const db = require('./config/db');
const logger = require('../utils/logger');

dotenv.config();

const host = process.env.HOST;
const port = process.env.PORT;

const server = http.createServer((req, res) => {
  res.write('Test');
  req.pipe(res);
});

server.listen(port, host, () => { logger.info(`Server listening at http://${host}:${port}.\n`); });
<commit_msg>Edited request/response object naming convention in HTTP server.<commit_after>const dotenv = require('dotenv');
const http = require('http');
const path = require('path');
const db = require('./config/db');
const logger = require('../utils/logger');

dotenv.config();

const host = process.env.HOST;
const port = process.env.PORT;

const server = http.createServer((request, response) => {
  response.write('Test');
  request.pipe(response);
});

server.listen(port, host, () => { logger.info(`Server listening at http://${host}:${port}.\n`); });
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   MySystem.EditableLabelView
// Copyright: ©2011 Concord Consortium
// Author:    Noah Paessel <knowuh@gmail.com>
// ==========================================================================
/*globals MySystem RaphaelViews */

/** @class

  RaphaelView for an editable label.

  @extends SC.View
  @extends RaphaelViews.RenderSupport
  @extends SC.Editable
*/
MySystem.EditableLabelView = RaphaelViews.RaphaelView.extend(SC.Editable, {
/** @scope MySystem.EditableLabelView.prototype */

  childViews: ['editBoxView'],
  displayProperties: 'displayText textColor centerX centerY fontSize'.w(),

  // PROPERTIES

  isEditing:     YES,
  isAllSelected: NO,
  fontSize:      12,
  text:          '',
  textColor:     '#000',
  centerX:       0,
  centerY:       0,

  displayText: function () {
    var txt = this.get('text');
    if (this.get('isEditing')) { txt = txt + "_"; }
    return txt;
  }.property('text', 'isEditing').cacheable(),

  textBBox: function () {
    var raphaelText = this.get('raphaelObject');
    return raphaelText ? raphaelText.getBBox() : null;
  }.property('displayText', 'centerX', 'centerY', 'fontSize', 'raphaelObject'),  // don't make this .cacheable(), it doesn't work right

  acceptsFirstResponder: function () {
    return this.get('isEnabled');
  }.property('isEnabled').cacheable(),

  willLoseFirstResponder: function () {
    console.log("loosing first responder");
    this.set('isEditing', NO);
    this.set('isAllSelected', NO);
  },

  renderCallback: function (raphaelCanvas, attrs) {
    return raphaelCanvas.text().attr(attrs);
  },

  render: function (context, firstTime) {
    var attrs = {
          x:             this.get('centerX'),
          y:             this.get('centerY'),
          fill:          this.get('textColor'),
          text:          this.get('displayText'),
          'font-size':   this.get('fontSize'),
          'text-anchor': 'middle'
        },

        raphaelText;

    if (firstTime) {
      context.callback(this, this.renderCallback, attrs);
      this.renderChildViews(context,firstTime);
    }
    else {
      raphaelText = this.get('raphaelObject');
      raphaelText.attr(attrs);
    }
  },

  toggle: function (paramName) {
    this.set(paramName, (! this.get(paramName)));
  },

  editFirstTime: function () {
    var item = this.get('item');

    if (this.get('isEditFirstTimePending')) {
      this.beginEditing();
      this.beginEditing(); // call twice to force selectAll
      // this.set('hasEditedFirstTime', YES);
    }
  }.observes('isEditFirstTimePending'),

  beginEditing: function () {
    if (!this.get('isEditable')) { return NO ; }
    this.becomeFirstResponder();
    if (this.get('isEditing')) {
      this.toggle('isAllSelected');
    }
    else {
      this.set('isEditing', YES);
    }
    return YES ;
  },

  discardEditing: function () {
    return this.commitEditing();
  },

  commitEditing: function () {
    this.resignFirstResponder();
    this.set('isEditing', NO) ;
    return YES ;
  },

  updateText: function (newtext) {
    this.beginPropertyChanges();
    this.set('isAllSelected', NO);
    this.set('text',newtext);
    this.endPropertyChanges();
  },

  keyDown: function (evt) {
    var chr = null;
    if (this.interpretKeyEvents(evt)) {
      return YES;
    }
    if (evt.type === 'keypress') {
      chr = evt.getCharString();
      if (chr) {
        this.appendText(chr);
        return YES;
      }
    }
    return NO;
  },

  appendText: function (chr) {
    if (this.get('isAllSelected')) {
      this.updateText(chr);
    }
    else {
      this.updateText(this.get('text') + chr);
    }
    return YES;
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  insertNewline: function () {
    this.appendText("\n");
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  insertTab: function () {
    this.commitEditing();
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  cancel: function () {
    this.discardEditing();
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  selectAll: function() {
    this.set('isAllSelected', YES);
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  deleteBackward: function () {
    var t       = this.get('text'),
        newText = t.substr(0,t.length-1);

    if (this.get('isAllSelected')) {
      newText = "";
    }
    this.updateText(newText);
    return YES;
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  // only problem is that deleteForward seems bound to "."
  // deleteForward: function () {
  //   return this.deleteBackward();
  // },

  editBoxView: RaphaelViews.RaphaelView.design({
    displayProperties:    'textBBox isAllSelected'.w(),

    textLabelView:        SC.outlet('parentView'),
    isVisibleBinding:     '.textLabelView.isEditing',
    isAllSelectedBinding: '.textLabelView.isAllSelected',
    textBBoxBinding:      '.textLabelView.textBBox',
    textBBoxBindingDefault: SC.Binding.oneWay(),

    minHeight:            18,
    minWidth:             20,
    margin:               2,

    fill:                 '#FF5',
    strokeWidth:          1,
    stroke:               '#CCC',
    editingOpacity:       0.3,
    normalOpacity:        0.05,
    margin:               3,

    x: function () {
      var textBBox = this.get('textBBox');
      return textBBox ? textBBox.x - this.get('margin') : 0;
    }.property('textBBox').cacheable(),

    y: function () {
      var textBBox = this.get('textBBox');
      return textBBox ? textBBox.y - this.get('margin') : 0;
    }.property('textBBox').cacheable(),

    width: function () {
      var textBBox  = this.get('textBBox'),
          minWidth = this.get('minWidth'),
          width    = textBBox ? textBBox.width + 2 * this.get('margin') : 0;

      return (width >= minWidth) ? width : minWidth;
    }.property('textBBox').cacheable(),

    height: function () {
      var textBBox  = this.get('textBBox'),
          minHeight = this.get('minHeight'),
          height    = textBBox ? textBBox.height + 2 * this.get('margin') : 0;

      return (height >= minHeight) ? height : minHeight;
    }.property('textBBox').cacheable(),

    renderCallback: function (raphaelCanvas, attrs) {
      return raphaelCanvas.rect().attr(attrs);
    },

    render: function (context, firstTime) {
      var raphaelRect,
          opacity = this.get('isAllSelected') ? this.get('editingOpacity') : this.get('normalOpacity'),
          attrs = {
             'fill':         this.get('fill'),
             'fill-opacity': opacity,
             'stroke-width': this.get('strokeWidth'),
             'stroke':       this.get('stroke'),
             'x':            this.get('x'),
             'y':            this.get('y'),
             'width':        this.get('width'),
             'height':       this.get('height')
          };

      if (firstTime) {
        context.callback(this, this.renderCallback, attrs);
      }
      else {
        raphaelRect = this.get('raphaelObject');
        raphaelRect.attr(attrs);
      }
    } // render

  })
});
<commit_msg>margin was defined twice.<commit_after>// ==========================================================================
// Project:   MySystem.EditableLabelView
// Copyright: ©2011 Concord Consortium
// Author:    Noah Paessel <knowuh@gmail.com>
// ==========================================================================
/*globals MySystem RaphaelViews */

/** @class

  RaphaelView for an editable label.

  @extends SC.View
  @extends RaphaelViews.RenderSupport
  @extends SC.Editable
*/
MySystem.EditableLabelView = RaphaelViews.RaphaelView.extend(SC.Editable, {
/** @scope MySystem.EditableLabelView.prototype */

  childViews: ['editBoxView'],
  displayProperties: 'displayText textColor centerX centerY fontSize'.w(),

  // PROPERTIES

  isEditing:     YES,
  isAllSelected: NO,
  fontSize:      12,
  text:          '',
  textColor:     '#000',
  centerX:       0,
  centerY:       0,

  displayText: function () {
    var txt = this.get('text');
    if (this.get('isEditing')) { txt = txt + "_"; }
    return txt;
  }.property('text', 'isEditing').cacheable(),

  textBBox: function () {
    var raphaelText = this.get('raphaelObject');
    return raphaelText ? raphaelText.getBBox() : null;
  }.property('displayText', 'centerX', 'centerY', 'fontSize', 'raphaelObject'),  // don't make this .cacheable(), it doesn't work right

  acceptsFirstResponder: function () {
    return this.get('isEnabled');
  }.property('isEnabled').cacheable(),

  willLoseFirstResponder: function () {
    console.log("loosing first responder");
    this.set('isEditing', NO);
    this.set('isAllSelected', NO);
  },

  renderCallback: function (raphaelCanvas, attrs) {
    return raphaelCanvas.text().attr(attrs);
  },

  render: function (context, firstTime) {
    var attrs = {
          x:             this.get('centerX'),
          y:             this.get('centerY'),
          fill:          this.get('textColor'),
          text:          this.get('displayText'),
          'font-size':   this.get('fontSize'),
          'text-anchor': 'middle'
        },

        raphaelText;

    if (firstTime) {
      context.callback(this, this.renderCallback, attrs);
      this.renderChildViews(context,firstTime);
    }
    else {
      raphaelText = this.get('raphaelObject');
      raphaelText.attr(attrs);
    }
  },

  toggle: function (paramName) {
    this.set(paramName, (! this.get(paramName)));
  },

  editFirstTime: function () {
    var item = this.get('item');

    if (this.get('isEditFirstTimePending')) {
      this.beginEditing();
      this.beginEditing(); // call twice to force selectAll
      // this.set('hasEditedFirstTime', YES);
    }
  }.observes('isEditFirstTimePending'),

  beginEditing: function () {
    if (!this.get('isEditable')) { return NO ; }
    this.becomeFirstResponder();
    if (this.get('isEditing')) {
      this.toggle('isAllSelected');
    }
    else {
      this.set('isEditing', YES);
    }
    return YES ;
  },

  discardEditing: function () {
    return this.commitEditing();
  },

  commitEditing: function () {
    this.resignFirstResponder();
    this.set('isEditing', NO) ;
    return YES ;
  },

  updateText: function (newtext) {
    this.beginPropertyChanges();
    this.set('isAllSelected', NO);
    this.set('text',newtext);
    this.endPropertyChanges();
  },

  keyDown: function (evt) {
    var chr = null;
    if (this.interpretKeyEvents(evt)) {
      return YES;
    }
    if (evt.type === 'keypress') {
      chr = evt.getCharString();
      if (chr) {
        this.appendText(chr);
        return YES;
      }
    }
    return NO;
  },

  appendText: function (chr) {
    if (this.get('isAllSelected')) {
      this.updateText(chr);
    }
    else {
      this.updateText(this.get('text') + chr);
    }
    return YES;
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  insertNewline: function () {
    this.appendText("\n");
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  insertTab: function () {
    this.commitEditing();
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  cancel: function () {
    this.discardEditing();
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  selectAll: function() {
    this.set('isAllSelected', YES);
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  deleteBackward: function () {
    var t       = this.get('text'),
        newText = t.substr(0,t.length-1);

    if (this.get('isAllSelected')) {
      newText = "";
    }
    this.updateText(newText);
    return YES;
  },

  // @see frameworks/sproutcore/frameworks/desktop/system/key_bindings.js
  // only problem is that deleteForward seems bound to "."
  // deleteForward: function () {
  //   return this.deleteBackward();
  // },

  editBoxView: RaphaelViews.RaphaelView.design({
    displayProperties:    'textBBox isAllSelected'.w(),

    textLabelView:        SC.outlet('parentView'),
    isVisibleBinding:     '.textLabelView.isEditing',
    isAllSelectedBinding: '.textLabelView.isAllSelected',
    textBBoxBinding:      '.textLabelView.textBBox',
    textBBoxBindingDefault: SC.Binding.oneWay(),

    minHeight:            18,
    minWidth:             20,
    margin:               2,

    fill:                 '#FF5',
    strokeWidth:          1,
    stroke:               '#CCC',
    editingOpacity:       0.3,
    normalOpacity:        0.05,

    x: function () {
      var textBBox = this.get('textBBox');
      return textBBox ? textBBox.x - this.get('margin') : 0;
    }.property('textBBox').cacheable(),

    y: function () {
      var textBBox = this.get('textBBox');
      return textBBox ? textBBox.y - this.get('margin') : 0;
    }.property('textBBox').cacheable(),

    width: function () {
      var textBBox  = this.get('textBBox'),
          minWidth = this.get('minWidth'),
          width    = textBBox ? textBBox.width + 2 * this.get('margin') : 0;

      return (width >= minWidth) ? width : minWidth;
    }.property('textBBox').cacheable(),

    height: function () {
      var textBBox  = this.get('textBBox'),
          minHeight = this.get('minHeight'),
          height    = textBBox ? textBBox.height + 2 * this.get('margin') : 0;

      return (height >= minHeight) ? height : minHeight;
    }.property('textBBox').cacheable(),

    renderCallback: function (raphaelCanvas, attrs) {
      return raphaelCanvas.rect().attr(attrs);
    },

    render: function (context, firstTime) {
      var raphaelRect,
          opacity = this.get('isAllSelected') ? this.get('editingOpacity') : this.get('normalOpacity'),
          attrs = {
             'fill':         this.get('fill'),
             'fill-opacity': opacity,
             'stroke-width': this.get('strokeWidth'),
             'stroke':       this.get('stroke'),
             'x':            this.get('x'),
             'y':            this.get('y'),
             'width':        this.get('width'),
             'height':       this.get('height')
          };

      if (firstTime) {
        context.callback(this, this.renderCallback, attrs);
      }
      else {
        raphaelRect = this.get('raphaelObject');
        raphaelRect.attr(attrs);
      }
    } // render

  })
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Scroll from 'react-scroll';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';

import '../../styles/instructions.scss';

const ScrollLink = Scroll.Link;
export default class Header extends Component {
  render() {
    return (

          <Row>
            <Col xs={12} sm={3}>
              <object type="image/svg+xml" className="img-responsive main-logo" data="../../img/CityBookLogo.svg">

              </object>

CityBook

Create a contact list from a Google Spreadsheet.

              Citybook Demo <Glyphicon glyph='new-window' />
              <ScrollLink
                to="instructions-start"
                smooth={true}
                duration={500}
                id="get-started-button"
                className="btn btn-header btn-lg btn-block">Make a CityBook <Glyphicon glyph='flash' /></ScrollLink>
            </Col>
            <Col xsHidden smHidden sm={8} smOffset={1} className="iframe-container">
              <Col sm={6} smOffset={3}>

              </Col>
            </Col>
          </Row>

    );
  }
}
<commit_msg>Updated demo url link<commit_after>import React, { Component } from 'react';
import Scroll from 'react-scroll';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';

import '../../styles/instructions.scss';

const ScrollLink = Scroll.Link;
export default class Header extends Component {
  render() {
    return (

          <Row>
            <Col xs={12} sm={3}>
              <object type="image/svg+xml" className="img-responsive main-logo" data="../../img/CityBookLogo.svg">

              </object>

CityBook

Create a contact list from a Google Spreadsheet.

              Citybook Demo <Glyphicon glyph='new-window' />
              <ScrollLink
                to="instructions-start"
                smooth={true}
                duration={500}
                id="get-started-button"
                className="btn btn-header btn-lg btn-block">Make a CityBook <Glyphicon glyph='flash' /></ScrollLink>
            </Col>
            <Col xsHidden smHidden sm={8} smOffset={1} className="iframe-container">
              <Col sm={6} smOffset={3}>

              </Col>
            </Col>
          </Row>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var wrench = require('wrench');
var yeoman = require('yeoman-generator');

var MagentoGenerator = module.exports = function MagentoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(MagentoGenerator, yeoman.generators.Base);

MagentoGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'magentoVersion',
    message: 'What version do you want to use? (e.g. 1.7.0.2)',
    default: '1.7.0.2'
  }, {
    type:'confirm',
    name: 'includeGitignore',
    message: 'Do you want to include the default .gitignore file?',
    default: true,
  }, {
    type: 'confirm',
    name: 'includeUnitTest',
    message: 'Do you want to include EcomDevs PHPUnit module?',
    default: false
  }];

  this.prompt(prompts, function (props) {
    this.magentoVersion = props.magentoVersion;
    this.includeUnitTest = props.includeUnitTest;

    cb();
  }.bind(this));
};

MagentoGenerator.prototype.app = function app() {
  var cb = this.async(),
    self = this;

  this.copy('_gitignore', '.gitignore');
  this.tarball('http://www.magentocommerce.com/downloads/assets/' + self.magentoVersion + '/magento-' + self.magentoVersion + '.tar.gz', './', cb);
};

MagentoGenerator.prototype.permission = function permissions() {
  var cb = this.async(),
    self = this;

  wrench.chmodSyncRecursive('app/etc', 775);
  wrench.chmodSyncRecursive('media', 775);
  wrench.chmodSyncRecursive('var', 775);
}

MagentoGenerator.prototype.phpunit = function phpunit() {
  var cb = this.async(),
    self = this;

  if (self.includeUnitTest) {
    try {
      var version = exec('git ls-remote --tags git://github.com/EcomDev/EcomDev_PHPUnit.git | tail -n 1', function(err, stdout, stderr) {
        if (err) {
          cb()
        } else {
          var pattern = /\d\.\d[\.\d]*/ig,
            match = pattern.exec(stdout);

          if (match !== null && typeof match[0] !== 'undefined') {
            self.ecomdevPHPUnitVersion = match[0];
          }
        }

        cb()
      });
    } catch(e) {
      cb()
    }

    if (typeof self.ecomdevPHPUnitVersion !== "undefined") {
      this.tarball('https://github.com/EcomDev/EcomDev_PHPUnit  /tarball/' + self.ecomdevPHPUnitVersion, './', cb);
    }
  }
}
<commit_msg>Include bower.json & package.json<commit_after>'use strict';
var util = require('util');
var path = require('path');
var wrench = require('wrench');
var yeoman = require('yeoman-generator');

var MagentoGenerator = module.exports = function MagentoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(MagentoGenerator, yeoman.generators.Base);

MagentoGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'magentoVersion',
    message: 'What version do you want to use? (e.g. 1.7.0.2)',
    default: '1.7.0.2'
  }, {
    type:'confirm',
    name: 'includeGitignore',
    message: 'Do you want to include the default .gitignore file?',
    default: true,
  }, {
    type: 'confirm',
    name: 'includeUnitTest',
    message: 'Do you want to include EcomDevs PHPUnit module?',
    default: false
  }];

  this.prompt(prompts, function (props) {
    this.magentoVersion = props.magentoVersion;
    this.includeUnitTest = props.includeUnitTest;

    cb();
  }.bind(this));
};

MagentoGenerator.prototype.app = function app() {
  var cb = this.async(),
    self = this;

  this.copy('_gitignore', '.gitignore');
  this.copy('_bower.json', 'bower.json');
  this.copy('_package.json', 'package.json');

  this.tarball('http://www.magentocommerce.com/downloads/assets/' + self.magentoVersion + '/magento-' + self.magentoVersion + '.tar.gz', './', cb);
};

MagentoGenerator.prototype.permission = function permissions() {
  var cb = this.async(),
    self = this;

  wrench.chmodSyncRecursive('app/etc', 775);
  wrench.chmodSyncRecursive('media', 775);
  wrench.chmodSyncRecursive('var', 775);
}

MagentoGenerator.prototype.phpunit = function phpunit() {
  var cb = this.async(),
    self = this;

  if (self.includeUnitTest) {
    try {
      var version = exec('git ls-remote --tags git://github.com/EcomDev/EcomDev_PHPUnit.git | tail -n 1', function(err, stdout, stderr) {
        if (err) {
          cb()
        } else {
          var pattern = /\d\.\d[\.\d]*/ig,
            match = pattern.exec(stdout);

          if (match !== null && typeof match[0] !== 'undefined') {
            self.ecomdevPHPUnitVersion = match[0];
          }
        }

        cb()
      });
    } catch(e) {
      cb()
    }

    if (typeof self.ecomdevPHPUnitVersion !== "undefined") {
      this.tarball('https://github.com/EcomDev/EcomDev_PHPUnit  /tarball/' + self.ecomdevPHPUnitVersion, './', cb);
    }
  }
}
<|endoftext|>