<commit_before>Package.describe({
  summary: 'MVVM for Meteor with Two-Way Binding via Model Schema',
  name: 'comerc:template2',
  version: '1.5.4',
  git: 'https://github.com/comerc/meteor-template2.git'
});

Package.onUse(function(api) {

  // Have to stay on Meteor 1.2.1 to be compatible with all Meteor versions.
  api.versionsFrom('1.2.1');

  api.use([
    'coffeescript',
    'underscore',
    'es5-shim',
    'ecmascript',
    'reactive-var',
    'templating',
    'blaze-html-templates',
    'comerc:template-two-way-binding@1.6.1'
  ], 'client');

  api.addFiles([
    'src/_export.coffee',
    'src/reactive-object.js',
    'src/template2.coffee',
    'src/model-map.coffee'
  ], 'client');

  api.export('Template2', 'client');
  api.export('Template2Config', 'client');
});
<commit_msg>Update package.js<commit_after>Package.describe({
  summary: 'MVVM for Meteor with Two-Way Binding via Model Schema',
  name: 'comerc:template2',
  version: '1.5.4',
  git: 'https://github.com/comerc/meteor-template2.git'
});

Package.onUse(function(api) {

  // Have to stay on Meteor 1.2.1 to be compatible with all Meteor versions.
  api.versionsFrom('1.2.1');

  api.use([
    'coffeescript',
    'underscore',
    'ecmascript',
    'reactive-var',
    'templating',
    'blaze-html-templates',
    'comerc:template-two-way-binding@1.6.1'
  ], 'client');

  api.addFiles([
    'src/_export.coffee',
    'src/reactive-object.js',
    'src/template2.coffee',
    'src/model-map.coffee'
  ], 'client');

  api.export('Template2', 'client');
  api.export('Template2Config', 'client');
});
<|endoftext|>


<commit_before>const winston = require('winston');
const Rotate  = require('winston-logrotate');

module.exports = function(debug, log_dir, name) {
    var logger = new (winston.Logger)({
        transports: [
            new (Rotate)({
                file:      `${log_dir}/${name}.log`,
                colorize:  true,
                timestamp: true,
                json:      true,
                max:       '100m',
                keep:      7,
                compress:  true
            }),
            new (winston.transports.Console)({
                prettyPrint:      true,
                colorize:         true,
                silent:           false,
                timestamp:        debug,
                handleExceptions: true
            })
        ]
    });
    logger.cli();

    return logger;
};<commit_msg>Fixing rotator<commit_after>const winston = require('winston');
const Rotate  = require('winston-logrotate').Rotate;

module.exports = function(debug, log_dir, name) {
    var logger = new (winston.Logger)({
        transports: [
            new (Rotate)({
                file:      `${log_dir}/${name}.log`,
                colorize:  true,
                timestamp: true,
                json:      true,
                max:       '100m',
                keep:      7,
                compress:  true
            }),
            new (winston.transports.Console)({
                prettyPrint:      true,
                colorize:         true,
                silent:           false,
                timestamp:        debug,
                handleExceptions: true
            })
        ]
    });
    logger.cli();

    return logger;
};<|endoftext|>


<commit_before>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Tf from '../_Tf';

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';
import Direction from '../_statics/Direction';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';
import ScrollBar from '../_vendors/ScrollBar';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    shouldComponentUpdate(nextProps) {
        return !nextProps.resizingColumn;
    }

    getColumnsSpan = () => {
        const {columns, data, onRequestColumnsSpan} = this.props;
        return onRequestColumnsSpan ?
            onRequestColumnsSpan(TableFragment.FOOT, columns, data)
            :
            TC.getColumnsSpan(TableFragment.FOOT, columns, data);
    };

    getStyle = (column, colIndex) => {
        const {columns, columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll} = this.props;
        return {
            ...column.footStyle,
            ...TC.getStickyColumnStyle(column?.fixed, colIndex, columns,
                columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll)
        };
    };

    handleClick = e => {
        const {data, disabled, onFootClick} = this.props;
        !disabled && onFootClick && onFootClick(data, e);
    };

    render() {

        const {
                className, data, disabled, ignoreColumnSpan, scrollEl, hasVerticalScroll, hasFixedRightColumn,
                onCellClick
            } = this.props,
            columnsSpan = this.getColumnsSpan(),
            verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

        return (

                    {
                        columnsSpan && columnsSpan.map(({column, span}, colIndex) =>
                            <Tf key={colIndex}
                                className={classNames(column.footClassName, {
                                    'fixed-left': column.fixed === HorizontalAlign.LEFT,
                                    'last-fixed-left': column.fixed === HorizontalAlign.LEFT
                                        && columnsSpan?.[colIndex + 1]?.column?.fixed !== HorizontalAlign.LEFT,
                                    'fixed-right': column.fixed === HorizontalAlign.RIGHT,
                                    'first-fixed-right': column.fixed === HorizontalAlign.RIGHT
                                        && columnsSpan?.[colIndex - 1]?.column?.fixed !== HorizontalAlign.RIGHT
                                })}
                                style={this.getStyle(column, colIndex)}
                                colIndex={colIndex}
                                data={data}
                                title={column.footTitle}
                                renderer={column.footRenderer}
                                align={column.footAlign || column.align}
                                span={ignoreColumnSpan ? null : span}
                                noWrap={TC.handleNoWrap(column.footNoWrap, column.noWrap, {
                                    data,
                                    rowIndex: 0,
                                    colIndex: colIndex,
                                    tableData: data
                                })}
                                disabled={disabled}
                                scrollEl={scrollEl}
                                onCellClick={onCellClick}/>
                        )
                    }

                    {
                        hasVerticalScroll && columnsSpan && verticalScrollBarSize > 0 ?
                            <td className={classNames('scroll-bar-tf', {
                                'fixed-right': hasFixedRightColumn
                            })}
                                style={{
                                    width: verticalScrollBarSize,
                                    ...(hasFixedRightColumn ? {
                                        position: 'sticky',
                                        right: 0
                                    } : null)
                                }}>

                            :
                            null
                    }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    disabled: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,

    /**
     * scroll
     */
    scrollEl: PropTypes.object,
    hasVerticalScroll: PropTypes.bool,

    /**
     * fixed
     */
    hasFixedRightColumn: PropTypes.bool,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,
    resizingColumn: PropTypes.object,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {

    columnKeyField: 'key',
    disabled: false,
    ignoreColumnSpan: false,

    /**
     * scroll
     */
    hasVerticalScroll: false,

    /**
     * fixed
     */
    hasFixedRightColumn: false,

    /**
     * column resizable
     */
    defaultColumnWidth: 100

};

export default Tfoot;
<commit_msg>update Tfoot<commit_after>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import TfootRow from '../_TfootRow';

// Statics
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    shouldComponentUpdate(nextProps) {
        return !nextProps.resizingColumn;
    }

    handleClick = e => {
        const {data, disabled} = this.props;
        !disabled && this.props.onFootClick?.(data, e);
    };

    render() {

        const {
            className, columns, data, footData, disabled,
            ignoreColumnSpan, scrollEl, hasVerticalScroll, hasFixedRightColumn,
            onCellClick
        } = this.props;

        return (

            {
                footData?.map((rowData, rowIndex) =>
                    <TfootRow key={rowIndex}
                              rowIndex={rowIndex}
                              columns={columns}
                              data={rowData}
                              tableData={data}
                              disabled={disabled}
                              ignoreColumnSpan={ignoreColumnSpan}
                              scrollEl={scrollEl}
                              hasVerticalScroll={hasVerticalScroll}
                              hasFixedRightColumn={hasFixedRightColumn}
                              onCellClick={onCellClick}/>
                )
            }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    footData: PropTypes.array,
    disabled: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,

    /**
     * scroll
     */
    scrollEl: PropTypes.object,
    hasVerticalScroll: PropTypes.bool,

    /**
     * fixed
     */
    hasFixedRightColumn: PropTypes.bool,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,
    resizingColumn: PropTypes.object,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {

    columnKeyField: 'key',
    disabled: false,
    ignoreColumnSpan: false,

    /**
     * scroll
     */
    hasVerticalScroll: false,

    /**
     * fixed
     */
    hasFixedRightColumn: false,

    /**
     * column resizable
     */
    defaultColumnWidth: 100

};

export default Tfoot;
<|endoftext|>


<commit_before>'use strict';

var NVG = class {
	constructor(input) {
		this.document = 'nvg';
		this.items = [];
		this.version = '2.0.2'
		if (typeof input == 'string'){
			//do stuff with input object
			try {
				input = JSON.parse(input);
				for (var key in input){
					this[key] = input[key];
				}
			}catch (e) {
				//So parse as JSON failed, try to parse it as xml
				this.parseXML(input);
			}
		}
	}
	add(item){
		this.items.push(item);
	}
	getItems(){ //returns all items
		return this.items;
	}
	parseXML(xml){
		//parse XML string to JSON
		function tagAttributes(nodes, current){
			for (var i = 0; i < nodes.length; i++){
				var node = nodes[i];
				if(node.nodeType == 1){
					var nodeName = node.nodeName.split(':')[1];
					if (nodeName){
						nodeName = nodeName.toLowerCase();
						if(['arcband-ring','circular-ring','elliptic-ring','linear-ring','rect-ring'].lastIndexOf(nodeName) != -1){
							var exclude = {};
							exclude.drawable = nodeName.replace('-','');
							nodeAttibutes(node, exclude);
							current.push(exclude);
						}
						if (nodeName == 'exclude'){
							if (!current.hasOwnProperty(nodeName)){
								current['exclusion'] = [];
							}
							tagAttributes(node.childNodes, current['exclusion'])
						}
						if (nodeName == 'extendeddata'){
							if (!current.hasOwnProperty(nodeName)){
								current[nodeName] = {};
								current[nodeName].simpledata = [];
							}
							nodeAttibutes(node, current[nodeName]);
							parseSubNodes(node.childNodes, current[nodeName]);
						}
						if (nodeName == 'textinfo'){
							current[nodeName] = nodes[i].textContent;
						}
						if (nodeName == 'simplefield'){
							if (!current.hasOwnProperty(nodeName)){
								current[nodeName] = [];
							}
							var field = {};
							nodeAttibutes(node, field);
							current[nodeName].push(field);
						}
					}
				}
			}
		}
		function nodeAttibutes(node, current){
			Array.prototype.slice.call(node.attributes).forEach(function(attr) {
				if (attr.name == 'modifiers' || attr.name == 'style') {
					current[attr.name] = {};
					var attr_list = attr.value.trim().split(';');
					for (var j = 0; j < attr_list.length; j++){
						if(attr_list[j]){
							var s = attr_list[j].split(':');
							if(s[0] && s[1])current[attr.name][s[0].trim()] = isNaN(Number(s[1].trim()))?s[1].trim():Number(s[1].trim());
						}
					}
				return;
				}
				if (attr.name == 'points') {
					current[attr.name] = [];
					var attr_list = attr.value.trim().split(' ');
					for (var j = 0; j < attr_list.length; j++){
						if(attr_list[j]){
							var s = attr_list[j].split(',');
							if(s[0] && s[1])current[attr.name].push([Number(s[0]),Number(s[1])]);
						}
					}
				return;
				}
				current[attr.name] = isNaN(Number(attr.value))?attr.value:Number(attr.value);
			});
		}
		function parseSubNodes(nodes, current){
			for (var i = 0; i < nodes.length; i++){
				var node = nodes[i];
				if(node.nodeType == 1){
					var nodeName = node.nodeName.split(':')[1].toLowerCase();
					if (['extendeddata','extension','metadata','schema','simpledata','simplefield'].lastIndexOf(nodeName) != -1){

						// add schema handeling

						if (nodeName == 'simpledata'){
							var simpledata = {};
							nodeAttibutes(node, simpledata);
							simpledata.value = node.textContent;
							current.simpledata.push(simpledata);
						}else{
							current[nodeName] = {};
							nodeAttibutes(node, current[nodeName]);
							tagAttributes(node.childNodes, current[nodeName]);
						}
					}else{
						var item = {};
						nodeAttibutes(node, item);
						item.drawable = nodeName;

						if(node.childNodes.length){
							tagAttributes(node.childNodes, item);
						}
						if(item.drawable == 'g' || item.drawable == 'composite'){
							item.items = [];
							parseSubNodes(node.childNodes, item);
						}
						console.log(current)
						console.log(item)
						// TODO Add code for creating class objects for each item type
						current.items.push(item);
					}
				}
			}
			//return items;
		}

		var xml = (new DOMParser()).parseFromString(xml , "text/xml");
		if(xml.firstChild.nodeName.split(':')[1] == 'nvg'){//check that we actually are parsing NVG but ignore namespace
			this.version = xml.firstChild.getAttribute('version');
			this.items = [];
			var nodes = xml.firstChild.childNodes;
			// This find all items
			//this.items =
			parseSubNodes(nodes, this);
			// This looks for other data

		}
	}
	toGeoJSON(){
		//parse this to GeoJSON
	}
	toXML(){
		//parse this to NVG XML
	}

};

/*
NVG.Arc = class {
	constructor(cx,cy,rx,ry,startangle,endangle, uri, properties) {
		this.drawable = 'arc';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Arcband = class {
	constructor(cx,cy,minr,maxr,startangle,endangle, uri, properties) {
		this.drawable = 'arcband';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Arrow = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'arrow';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Circle = class {
	constructor(cx, cy, r, uri, properties) {
		this.drawable = 'circle';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Composite = class {
	constructor(items, uri, properties) {
		this.drawable = 'composite';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};
*/
/*
NVG.ContentItem = class {
	constructor(xml, uri) {
		this.drawable = 'content-item';
		this.uri = uri;
	}
};
*/
/*
NVG.Corridor = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'corridor';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Ellipse = class {
	constructor(cx,cy,rx,ry, uri, properties) {
		this.drawable = 'ellipse';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Group = class {
	constructor(items, properties) {
		this.drawable = 'g';
		this.items = items;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
	getItems(){
		return this.items;
	}
};

NVG.Multipoint = class {
	constructor(points, uri, properties) {
		this.drawable = 'multipoint';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Orbit = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'orbit';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Point = class {
	constructor(x, y, uri, properties) {
		this.drawable = 'point';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Polygon = class {
	constructor(points, uri, properties) {
		this.drawable = 'polygon';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Polyline = class {
	constructor(points, uri, properties) {
		this.drawable = 'polyline';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Rect = class {
	constructor(cx,cy,rx,ry, uri, properties) {
		this.drawable = 'rect';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Text = class {
	constructor(x,y,content,uri, properties) {
		this.x = x;
		this.y = y;
		this.content = content;

		this.drawable = 'text';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};*/<commit_msg>Nos supports everything except extension and metadata<commit_after>'use strict';

var NVG = class {
	constructor(input) {
		this.document = 'nvg';
		this.items = [];
		this.version = '2.0.2'
		if (typeof input == 'string'){
			//do stuff with input object
			try {
				input = JSON.parse(input);
				for (var key in input){
					this[key] = input[key];
				}
			}catch (e) {
				//So parse as JSON failed, try to parse it as xml
				this.parseXML(input);
			}
		}
	}
	getItems(){ //returns all items
		return this.items;
	}
	parseXML(xml){
		//parse XML string to JSON
		function tagAttributes(nodes, current){
			for (var i = 0; i < nodes.length; i++){
				var node = nodes[i];
				var nodeName = node.nodeName.split(':')[1];
				if(node.nodeType == 1 && nodeName &&
				//Do not try to get drawables as attributes
				['arc','arcband','arrow','circle','composite','content-item','corridor','ellipse','g','multipoint','orbit','point','polygon','polyline','rect','text'].lastIndexOf(nodeName) == -1){
					nodeName = nodeName.toLowerCase();
					switch (nodeName) {
						case 'begin':
							current[nodeName] = node.textContent;
							break;
						case 'end':
							current[nodeName] = node.textContent;
							break;
						case 'content':
							current[nodeName] = node.textContent;
							break;
						case 'exclude':
							if (!current.hasOwnProperty(nodeName)){
								current.exclusion = [];
							}
							tagAttributes(node.childNodes, current.exclusion);
							break;
						case 'extendeddata':
							if (!current.hasOwnProperty(nodeName)){
								current[nodeName] = {};
								current[nodeName].simpledata = [];
							}
							nodeAttibutes(node, current[nodeName]);
							parseSubNodes(node.childNodes, current[nodeName]);
							break;
						case 'extension':
							console.log('TODO tagAttributes: '  + nodeName);
							// TODO How to handle extended data
							current[nodeName] = [];//this is for node
							break;
						case 'textinfo':
							current[nodeName] = node.textContent;
							break;
						case 'timespan':
							current[nodeName] = {};
							tagAttributes(node.childNodes, current[nodeName]);
							break;
						case 'timestamp':
							current[nodeName] = node.textContent;
							break;
						case 'simplefield':
							if (!current.hasOwnProperty(nodeName)){
								current[nodeName] = [];
							}
							var field = {};
							nodeAttibutes(node, field);
							current[nodeName].push(field);
							break;
						case 'arcband-ring':
						case 'circular-ring':
						case 'elliptic-ring':
						case 'linear-ring':
						case 'rect-ring':
							var exclude = {};
							exclude.drawable = nodeName.replace('-','');
							nodeAttibutes(node, exclude);
							current.push(exclude);
							break;
						default:
							console.log('TODO tagAttributes default: ' + nodeName);
					}
				}
			}
		}
		function nodeAttibutes(node, current){
			Array.prototype.slice.call(node.attributes).forEach(function(attr) {
				if (attr.name == 'modifiers' || attr.name == 'style') {
					current[attr.name] = {};
					var attr_list = attr.value.trim().split(';');
					for (var j = 0; j < attr_list.length; j++){
						if(attr_list[j]){
							var s = attr_list[j].split(':');
							if(s[0] && s[1])current[attr.name][s[0].trim()] = isNaN(Number(s[1].trim()))?s[1].trim():Number(s[1].trim());
						}
					}
				return;
				}
				if (attr.name == 'points') {
					current[attr.name] = [];
					var attr_list = attr.value.trim().split(' ');
					for (var j = 0; j < attr_list.length; j++){
						if(attr_list[j]){
							var s = attr_list[j].split(',');
							if(s[0] && s[1])current[attr.name].push([Number(s[0]),Number(s[1])]);
						}
					}
				return;
				}
				current[attr.name] = isNaN(Number(attr.value))?attr.value:Number(attr.value);
			});
		}
		function parseSubNodes(nodes, current){
			for (var i = 0; i < nodes.length; i++){
				var node = nodes[i];
				if(node.nodeType == 1){
					var nodeName = node.nodeName.split(':')[1].toLowerCase();
					var item = {};
					if (['extendeddata','extension','metadata','schema','section','simpledata','simplefield'].lastIndexOf(nodeName) != -1){

						switch (nodeName) {
							case 'extendeddata':
								current[nodeName] = item;
								nodeAttibutes(node, item);
								tagAttributes(node.childNodes, item);
								break;
							case 'extension':
								console.log('TODO parsesubnodes: ' + nodeName)
								// TODO How to handle extended data
								current[nodeName] = [];//this is for root level
								break;
							case 'metadata':
								console.log('TODO parsesubnodes: ' + nodeName)
								// TODO How to handle metadata data
								current[nodeName] = item;
								break;
							case 'schema':
								if (!current.hasOwnProperty(nodeName)){
									current[nodeName] = [];
								}
								current[nodeName].push(item);
								nodeAttibutes(node, item);
								tagAttributes(node.childNodes, item);
								break;
							case 'section':
								if (!current.hasOwnProperty('simpledatasection')){
									current.simpledatasection = [];
								}
								current.simpledatasection.push(item);
								nodeAttibutes(node, item);
								item.simpledata = [];
								parseSubNodes(node.childNodes, item);
								break;
							case 'simpledata':
								nodeAttibutes(node, item);
								item.value = node.textContent;
								current.simpledata.push(item);
								tagAttributes(node.childNodes, item);
								break;
							case 'simplefield':
								current[nodeName] = item;
								nodeAttibutes(node, item);
								tagAttributes(node.childNodes, item);
								break;
							default:
								console.log('TODO parsesubnodes default: ' + nodeName)
						}
					}else{ //This is all drawables
						nodeAttibutes(node, item);
						item.drawable = nodeName;

						if(node.childNodes.length){
							tagAttributes(node.childNodes, item);
						}
						if(item.drawable == 'g' || item.drawable == 'composite'){
							item.items = [];
							parseSubNodes(node.childNodes, item);
						}
						current.items.push(item);
					}
				}
			}
		}

		var xml = (new DOMParser()).parseFromString(xml , "text/xml");
		if(xml.firstChild.nodeName.split(':')[1] == 'nvg'){//check that we actually are parsing NVG but ignore namespace
			this.version = xml.firstChild.getAttribute('version');
			this.items = [];
			var nodes = xml.firstChild.childNodes;
			parseSubNodes(nodes, this);
		}
	}
	toGeoJSON(){
		//parse this to GeoJSON
	}
	toXML(){
		//parse this to NVG XML
	}

};

/*
NVG.Arc = class {
	constructor(cx,cy,rx,ry,startangle,endangle, uri, properties) {
		this.drawable = 'arc';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Arcband = class {
	constructor(cx,cy,minr,maxr,startangle,endangle, uri, properties) {
		this.drawable = 'arcband';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Arrow = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'arrow';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Circle = class {
	constructor(cx, cy, r, uri, properties) {
		this.drawable = 'circle';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Composite = class {
	constructor(items, uri, properties) {
		this.drawable = 'composite';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};
*/
/*
NVG.ContentItem = class {
	constructor(xml, uri) {
		this.drawable = 'content-item';
		this.uri = uri;
	}
};
*/
/*
NVG.Corridor = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'corridor';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Ellipse = class {
	constructor(cx,cy,rx,ry, uri, properties) {
		this.drawable = 'ellipse';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Group = class {
	constructor(items, properties) {
		this.drawable = 'g';
		this.items = items;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
	getItems(){
		return this.items;
	}
};

NVG.Multipoint = class {
	constructor(points, uri, properties) {
		this.drawable = 'multipoint';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}

	}
};

NVG.Orbit = class {
	constructor(width, points, uri, properties) {
		this.drawable = 'orbit';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Point = class {
	constructor(x, y, uri, properties) {
		this.drawable = 'point';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Polygon = class {
	constructor(points, uri, properties) {
		this.drawable = 'polygon';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Polyline = class {
	constructor(points, uri, properties) {
		this.drawable = 'polyline';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Rect = class {
	constructor(cx,cy,rx,ry, uri, properties) {
		this.drawable = 'rect';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};

NVG.Text = class {
	constructor(x,y,content,uri, properties) {
		this.x = x;
		this.y = y;
		this.content = content;

		this.drawable = 'text';
		this.uri = uri;

		if(properties){
			for (key in properties){
				this[key] = properties[key];
			}
		}
	}
};*/<|endoftext|>


<commit_before>var assert = require('assert');
var references = require('mapnik-reference');

describe('datasources', function() {
    for (var key in references.version) {
        var spec = references.version[key];
        if (spec.datasources) {
            it('show provide metadata for '+key, function() {
                var ds_spec = spec.datasources['postgis'];
                assert.ok(ds_spec['table'].type,'string');
                assert.equal(ds_spec['table'].required,true);
            });
        } else {
            it.skip('show provide metadata for '+key, function() {});
        }
    }
});

describe('styles', function() {
    for (var key in references.version) {
        var spec = references.version[key];
        it('show report correct version for '+key, function() {
            assert.equal(spec.version,key);
        });
    }

    it('show reveal new property in Mapnik 2.3.0', function() {
        assert.ok(references.version['2.3.0'].symbolizers.markers['geometry-transform']);
        assert.ok(!references.version['2.0.0'].symbolizers.markers['geometry-transform']);
    });

});<commit_msg>tests: detect versions via globbing<commit_after>var assert = require('assert');
var references = require('mapnik-reference');
var glob = require('glob');
var path = require('path');

describe('datasources', function() {
    for (var key in references.version) {
        var spec = references.version[key];
        if (spec.datasources) {
            it('show provide metadata for '+key, function() {
                var ds_spec = spec.datasources['postgis'];
                assert.ok(ds_spec['table'].type,'string');
                assert.equal(ds_spec['table'].required,true);
            });
        } else {
            it.skip('show provide metadata for '+key, function() {});
        }
    }
});

describe('styles', function() {
    for (var key in references.version) {
        (function(key) {
            it('show report correct version for '+key, function() {
                assert.equal(references.version[key].version,key);
            });
        })(key)
    }

    it('show reveal new property in Mapnik 2.3.0', function() {
        assert.ok(references.version['2.3.0'].symbolizers.markers['geometry-transform']);
        assert.ok(!references.version['2.0.0'].symbolizers.markers['geometry-transform']);
    });
});

describe('versions', function() {
    it('show report all versions', function() {
        var versions = glob.sync("./*.*.*");
        var versions2 = Object.keys(references.version);
        versions = versions.map(function(e) { return path.basename(e) })
        assert.deepEqual(versions,versions2);
    });
});

<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const fs = require('fs');
const paths = require('./paths');

// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  throw new Error(
    'The NODE_ENV environment variable is required but was not specified.'
  );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
  `${paths.dotenv}.${NODE_ENV}.local`,
  `${paths.dotenv}.${NODE_ENV}`,
  `${paths.dotenv}.local`,
  paths.dotenv,
];
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
dotenvFiles.forEach(dotenvFile => {
  if (fs.existsSync(dotenvFile)) {
    require('dotenv').config({
      path: dotenvFile,
    });
  }
});

// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;

function getClientEnvironment(publicUrl) {
  const raw = Object.keys(process.env)
    .filter(key => REACT_APP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        // Useful for determining whether we’re running in production mode.
        // Most importantly, it switches React into the correct mode.
        NODE_ENV: process.env.NODE_ENV || 'development',
        // Useful for resolving the correct path to static assets in `public`.
        // For example, .
        // This should only be used as an escape hatch. Normally you would put
        // images into the `src` and `import` them in code to get their paths.
        PUBLIC_URL: publicUrl,
      }
    );
  // Stringify all values so we can feed into Webpack DefinePlugin
  const stringified = {
    'process.env': Object.keys(raw).reduce(
      (env, key) => {
        env[key] = JSON.stringify(raw[key]);
        return env;
      },
      {}
    ),
  };

  return { raw, stringified };
}

module.exports = getClientEnvironment;
<commit_msg>Ignore .env.local in test environment (#2250)<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const fs = require('fs');
const paths = require('./paths');

// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  throw new Error(
    'The NODE_ENV environment variable is required but was not specified.'
  );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
  `${paths.dotenv}.${NODE_ENV}.local`,
  `${paths.dotenv}.${NODE_ENV}`,
  // Don't include `.env.local` for `test` environment
  // since normally you expect tests to produce the same
  // results for everyone
  NODE_ENV !== 'test' && `${paths.dotenv}.local`,
  paths.dotenv,
].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
dotenvFiles.forEach(dotenvFile => {
  if (fs.existsSync(dotenvFile)) {
    require('dotenv').config({
      path: dotenvFile,
    });
  }
});

// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;

function getClientEnvironment(publicUrl) {
  const raw = Object.keys(process.env)
    .filter(key => REACT_APP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        // Useful for determining whether we’re running in production mode.
        // Most importantly, it switches React into the correct mode.
        NODE_ENV: process.env.NODE_ENV || 'development',
        // Useful for resolving the correct path to static assets in `public`.
        // For example, .
        // This should only be used as an escape hatch. Normally you would put
        // images into the `src` and `import` them in code to get their paths.
        PUBLIC_URL: publicUrl,
      }
    );
  // Stringify all values so we can feed into Webpack DefinePlugin
  const stringified = {
    'process.env': Object.keys(raw).reduce(
      (env, key) => {
        env[key] = JSON.stringify(raw[key]);
        return env;
      },
      {}
    ),
  };

  return { raw, stringified };
}

module.exports = getClientEnvironment;
<|endoftext|>


<commit_before>'use strict';

module.exports = function() {
  var date = function(d) { return d.date; },
      high = function(d) { return d.high; },
      low = function(d) { return d.low; },
      spread = function(d) { return d.spread; };

  function accessor(d) {
    return accessor.c(d);
  }

  // TODO use d3.rebind to obtain this from 'super class'
  accessor.date = function(_) {
    if (!arguments.length) return date;
    date = _;
    return bind();
  };

  accessor.high = function(_) {
    if (!arguments.length) return high;
    high = _;
    return bind();
  };

  accessor.low = function(_) {
    if (!arguments.length) return low;
    low = _;
    return bind();
  };

  accessor.spread = function(_) {
    if (!arguments.length) return spread;
    spread = _;
    return bind();
  };

  function bind() {
    // TODO These methods will need to know if the variables are functions or values and execute as such
    accessor.d = date;
    accessor.h = high;
    accessor.l = low;
    accessor.s = spread;

    return accessor;
  }

  return bind();
};<commit_msg>fixup the constructor<commit_after>'use strict';

module.exports = function() {
  var date = function(d) { return d.date; },
      high = function(d) { return d.high; },
      low = function(d) { return d.low; },
      spread = function(d) { return d.spread; };

  function accessor(d) {
    bind();
  }

  // TODO use d3.rebind to obtain this from 'super class'
  accessor.date = function(_) {
    if (!arguments.length) return date;
    date = _;
    return bind();
  };

  accessor.high = function(_) {
    if (!arguments.length) return high;
    high = _;
    return bind();
  };

  accessor.low = function(_) {
    if (!arguments.length) return low;
    low = _;
    return bind();
  };

  accessor.spread = function(_) {
    if (!arguments.length) return spread;
    spread = _;
    return bind();
  };

  function bind() {
    accessor.d = date;
    accessor.h = high;
    accessor.l = low;
    accessor.s = spread;

    return accessor;
  }

  return bind();
};<|endoftext|>


<commit_before>import Base from '../Base/Base'

/**
 * Left and Right controllers for gallery
 * Uses `Base` as the base class
 */
class Controls extends Base {
  constructor(parent, rootEl, config) {
    super(parent)
    /* Saving the configurations */
    this.addToStore('root', rootEl)
    this.addToStore('config', config)
  }
}

export default Controls
<commit_msg>Added docs for Controls class<commit_after>import Base from '../Base/Base'

/**
 * Left and Right controllers for gallery
 * Uses `Base` as the parent class
 */
class Controls extends Base {
  /**
   * Initialize controls
   * @param {Base} parent Parent class that invokes Controls
   * @param {Snap} paper SnapSvg instance
   * @param {Object} config Parsed configurations objetc
   */
  constructor(parent, paper, config) {
    super(parent)
    /* Saving the configurations */
    this.addToStore('paper', paper)
    this.addToStore('config', config)
  }
}

export default Controls
<|endoftext|>


<commit_before>// global variable containing the current AJAX request, needed if it must be aborted
ajax = null;

function getGuardianNews(amount, scope, section, keyword){
	today = new Date(); // dates are entered relatively, today is needed

	start_time = new Date();
	end_time = today;
	//section = section;

	// get correct start time
	switch (scope) {
		case 'days': start_time.setDate(today.getDate()-amount); break;
		case 'weeks': start_time.setDate(today.getDate()-amount*7); break;
		case 'months': start_time.setMonth(today.getMonth()-amount); break;
	}

	// make asynchronous ajax request, calls handle
	ajaxGuardian(start_time, end_time, section, keyword);
}

function ajaxGuardian(start_time, end_time, section, keyword){
	ajax = $.ajax({
		url: 'guardian_feeds.php',
		type: 'GET',
		dataType: 'json',
		data: {start_time: start_time.f('yyyy-MM-dd'), end_time: end_time.f('yyyy-MM-dd'), section: section, keyword: keyword},
		success: function(data, textStatus, xhr) {
			// replace JSON date format with JavaScript Date Objects
			$.each(data, function(index, story) {
				 story[2] = new Date(story[2]);
			});

			// call handleGuardianNews function of main.js
			handleGuardianNews(data);
		},
		error: function(xhr, textStatus, errorThrown) {
            $('.news').html('
Couldn’t scoop the news for you…
');
			console.log('ERROR: ' + errorThrown);
		}
	});
}

function getSummary (object) {
	ajax = $.ajax({
		url: 'ots.php',
		type: 'GET',
		dataType: 'html',
		data: {to_sum: $(object).next('article').find('a.read-more').attr('href'), ratio: 10},
		success: function(data, textStatus, xhr) {
			data = $('
').html(data).text();
			if (data == 'null') {
				data = 'No summary found.'
			}
			$(object).next('article').find('.summary--content').slideUp(300, function(){
				$(object).next('article').find('.summary--content').html('
' + data + '
');
			}).slideDown(300);
            object.addClass('loaded');
		},
		error: function(xhr, textStatus, errorThrown) {
			$(object).next('article').find('.summary--content').html('
Couldn’t get summary.
');
			console.log('ERROR: ' + xhr);
		}
	});

}<commit_msg>Add "Try again" link to error messages<commit_after>// global variable containing the current AJAX request, needed if it must be aborted
ajax = null;

function getGuardianNews(amount, scope, section, keyword){
	today = new Date(); // dates are entered relatively, today is needed

	start_time = new Date();
	end_time = today;
	//section = section;

	// get correct start time
	switch (scope) {
		case 'days': start_time.setDate(today.getDate()-amount); break;
		case 'weeks': start_time.setDate(today.getDate()-amount*7); break;
		case 'months': start_time.setMonth(today.getMonth()-amount); break;
	}

	// make asynchronous ajax request, calls handle
	ajaxGuardian(start_time, end_time, section, keyword);
}

function ajaxGuardian(start_time, end_time, section, keyword){
	ajax = $.ajax({
		url: 'guardian_feeds.php',
		type: 'GET',
		dataType: 'json',
		data: {start_time: start_time.f('yyyy-MM-dd'), end_time: end_time.f('yyyy-MM-dd'), section: section, keyword: keyword},
		success: function(data, textStatus, xhr) {
			// replace JSON date format with JavaScript Date Objects
			$.each(data, function(index, story) {
				 story[2] = new Date(story[2]);
			});

			// call handleGuardianNews function of main.js
			handleGuardianNews(data);
		},
		error: function(xhr, textStatus, errorThrown) {
            $('.news').html('
Couldn’t scoop the news for you… Try again
');
			console.log('ERROR: ' + errorThrown);
		}
	});
}

function getSummary (object) {
	ajax = $.ajax({
		url: 'ots.php',
		type: 'GET',
		dataType: 'html',
		data: {to_sum: $(object).next('article').find('a.read-more').attr('href'), ratio: 10},
		success: function(data, textStatus, xhr) {
			data = $('
').html(data).text();
			if (data == 'null') {
				data = 'No summary found.'
			}
			$(object).next('article').find('.summary--content').slideUp(300, function(){
				$(object).next('article').find('.summary--content').html('
' + data + '
');
			}).slideDown(300);
            object.addClass('loaded');
		},
		error: function(xhr, textStatus, errorThrown) {
			$(object).next('article').find('.summary--content').html('
Couldn’t get summary…Try again
');
			console.log('ERROR: ' + xhr);
		}
	});

}<|endoftext|>


<commit_before>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Tf from '../_Tf';

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';
import Direction from '../_statics/Direction';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';
import ScrollBar from '../_vendors/ScrollBar';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    getColumnsSpan = () => {
        const {columns, data, onRequestColumnsSpan} = this.props;
        return onRequestColumnsSpan ?
            onRequestColumnsSpan(TableFragment.FOOT, columns, data)
            :
            TC.getColumnsSpan(TableFragment.FOOT, columns, data);
    };

    getStyle = (column, colIndex) => {
        const {columns, columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll} = this.props;
        return {
            ...column.footStyle,
            ...TC.getStickyColumnStyle(column?.fixed, colIndex, columns,
                columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll)
        };
    };

    handleClick = e => {
        const {data, disabled, onFootClick} = this.props;
        !disabled && onFootClick && onFootClick(data, e);
    };

    render() {

        const {
                className, data, disabled, ignoreColumnSpan, scrollEl, hasVerticalScroll, hasFixedRightColumn,
                onCellClick
            } = this.props,
            columnsSpan = this.getColumnsSpan(),
            verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

        return (

                    {
                        columnsSpan && columnsSpan.map(({column, span}, colIndex) =>
                            <Tf key={colIndex}
                                className={classNames(column.footClassName, {
                                    'fixed-left': column.fixed === HorizontalAlign.LEFT,
                                    'last-fixed-left': column.fixed === HorizontalAlign.LEFT
                                        && columnsSpan?.[colIndex + 1]?.column?.fixed !== HorizontalAlign.LEFT,
                                    'fixed-right': column.fixed === HorizontalAlign.RIGHT,
                                    'first-fixed-right': column.fixed === HorizontalAlign.RIGHT
                                        && columnsSpan?.[colIndex - 1]?.column?.fixed !== HorizontalAlign.RIGHT
                                })}
                                style={this.getStyle(column, colIndex)}
                                colIndex={colIndex}
                                data={data}
                                title={column.footTitle}
                                renderer={column.footRenderer}
                                align={column.footAlign || column.align}
                                span={ignoreColumnSpan ? null : span}
                                noWrap={TC.handleNoWrap(column.footNoWrap, column.noWrap, {
                                    data,
                                    rowIndex: 0,
                                    colIndex: colIndex,
                                    tableData: data
                                })}
                                disabled={disabled}
                                scrollEl={scrollEl}
                                onCellClick={onCellClick}/>
                        )
                    }

                    {
                        hasVerticalScroll && columnsSpan && verticalScrollBarSize > 0 ?
                            <td className={classNames('scroll-bar-tf', {
                                'fixed-right': hasFixedRightColumn
                            })}
                                style={{
                                    width: verticalScrollBarSize,
                                    ...(hasFixedRightColumn ? {
                                        position: 'sticky',
                                        right: 0
                                    } : null)
                                }}>

                            :
                            null
                    }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    disabled: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,

    /**
     * scroll
     */
    scrollEl: PropTypes.object,
    hasVerticalScroll: PropTypes.bool,

    /**
     * fixed
     */
    hasFixedRightColumn: PropTypes.bool,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {

    columnKeyField: 'key',
    disabled: false,
    ignoreColumnSpan: false,

    /**
     * scroll
     */
    hasVerticalScroll: false,

    /**
     * fixed
     */
    hasFixedRightColumn: false,

    /**
     * column resizable
     */
    defaultColumnWidth: 100

};

export default Tfoot;
<commit_msg>update Tfoot<commit_after>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Tf from '../_Tf';

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';
import Direction from '../_statics/Direction';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';
import ScrollBar from '../_vendors/ScrollBar';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    shouldComponentUpdate(nextProps) {
        return !nextProps.resizingColumn;
    }

    getColumnsSpan = () => {
        const {columns, data, onRequestColumnsSpan} = this.props;
        return onRequestColumnsSpan ?
            onRequestColumnsSpan(TableFragment.FOOT, columns, data)
            :
            TC.getColumnsSpan(TableFragment.FOOT, columns, data);
    };

    getStyle = (column, colIndex) => {
        const {columns, columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll} = this.props;
        return {
            ...column.footStyle,
            ...TC.getStickyColumnStyle(column?.fixed, colIndex, columns,
                columnKeyField, columnsWidth, defaultColumnWidth, hasVerticalScroll)
        };
    };

    handleClick = e => {
        const {data, disabled, onFootClick} = this.props;
        !disabled && onFootClick && onFootClick(data, e);
    };

    render() {

        const {
                className, data, disabled, ignoreColumnSpan, scrollEl, hasVerticalScroll, hasFixedRightColumn,
                onCellClick
            } = this.props,
            columnsSpan = this.getColumnsSpan(),
            verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

        return (

                    {
                        columnsSpan && columnsSpan.map(({column, span}, colIndex) =>
                            <Tf key={colIndex}
                                className={classNames(column.footClassName, {
                                    'fixed-left': column.fixed === HorizontalAlign.LEFT,
                                    'last-fixed-left': column.fixed === HorizontalAlign.LEFT
                                        && columnsSpan?.[colIndex + 1]?.column?.fixed !== HorizontalAlign.LEFT,
                                    'fixed-right': column.fixed === HorizontalAlign.RIGHT,
                                    'first-fixed-right': column.fixed === HorizontalAlign.RIGHT
                                        && columnsSpan?.[colIndex - 1]?.column?.fixed !== HorizontalAlign.RIGHT
                                })}
                                style={this.getStyle(column, colIndex)}
                                colIndex={colIndex}
                                data={data}
                                title={column.footTitle}
                                renderer={column.footRenderer}
                                align={column.footAlign || column.align}
                                span={ignoreColumnSpan ? null : span}
                                noWrap={TC.handleNoWrap(column.footNoWrap, column.noWrap, {
                                    data,
                                    rowIndex: 0,
                                    colIndex: colIndex,
                                    tableData: data
                                })}
                                disabled={disabled}
                                scrollEl={scrollEl}
                                onCellClick={onCellClick}/>
                        )
                    }

                    {
                        hasVerticalScroll && columnsSpan && verticalScrollBarSize > 0 ?
                            <td className={classNames('scroll-bar-tf', {
                                'fixed-right': hasFixedRightColumn
                            })}
                                style={{
                                    width: verticalScrollBarSize,
                                    ...(hasFixedRightColumn ? {
                                        position: 'sticky',
                                        right: 0
                                    } : null)
                                }}>

                            :
                            null
                    }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    disabled: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,

    /**
     * scroll
     */
    scrollEl: PropTypes.object,
    hasVerticalScroll: PropTypes.bool,

    /**
     * fixed
     */
    hasFixedRightColumn: PropTypes.bool,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,
    resizingColumn: PropTypes.object,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {

    columnKeyField: 'key',
    disabled: false,
    ignoreColumnSpan: false,

    /**
     * scroll
     */
    hasVerticalScroll: false,

    /**
     * fixed
     */
    hasFixedRightColumn: false,

    /**
     * column resizable
     */
    defaultColumnWidth: 100

};

export default Tfoot;
<|endoftext|>


<commit_before>'use strict';

var Promise = require('bluebird');
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var tildify = require('tildify');
var gulp = require('gulp');
var rimraf = require('rimraf');
var gutil = require('gulp-util');
var rename = require('gulp-rename');

// installer plugins to handle the npm and bower packages installation
function installer (rootPath, command, description, nextStepFn, newFolderName, callback) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray('[-log:]'), description);
  process.chdir(rootPath);
  return exec(command, function (error, stdout, stderr) {
    // process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log(gutil.colors.red('[-Error:] ' + log));
      if (command === 'npm install') {
        gutil.log(gutil.colors.red('[-Error:] npm install failed dramatically.'));
        gutil.log(
          gutil.colors.red('[-Error:] Need to manually do \'npm install\' and \'bower install\' ')
        );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else if (command === 'bower install') {
        gutil.log(gutil.colors.red('[-Error:] bower install failed dramatically.'));
        gutil.log(gutil.colors.red('[-Error:] Need to manually do \'bower install\''));
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] initialize git repository failed dramatically.')
        );
        gutil.log(gutil.colors.red('[-Error:] Need to manually do'));
        gutil.log(gutil.colors.red('[-Error:] \'git init && git add . && git commit -m\''));
      }
      return callback(log);
    }
    nextStepFn(rootPath, newFolderName, callback);
  });
}

function gitInit (rootPath, newFolderName, callback) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    gutil.colors.cyan('em-cli'),
    'is doing REALLY hard to initialize your repo ...'
  );

  rootPath = rootPath || process.cwd();
  process.chdir(rootPath);

  var month = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  ];
  var today = new Date();
  var todayDate = today.getDate();
  var todayMonth = month[today.getMonth()];
  var todayYear = today.getFullYear();
  var command = 'git init && git add . && git commit -m \'Initial Commit @ ' +
    todayMonth + ' ' + todayDate + ', ' + todayYear + '\'';

  return exec(command, function (error, stdout, stderr) {
    if (error !== null) {
      var log = stderr.toString();
      gutil.log(gutil.colors.red('[-Error:] ' + log));
      return callback(log);
    }
    gutil.log(
      gutil.colors.green('[-done:] Initialized a new git repo and did a first commit')
    );
    gutil.log(
      gutil.colors.bold('[-copy:] =>'),
      gutil.colors.cyan('cd ' + newFolderName),
      gutil.colors.gray('# navigate to the newly created application')
    );
    gutil.log(
      gutil.colors.bold('[-copy:] =>'),
      gutil.colors.cyan('em serve'),
      gutil.colors.gray(' # kick start the server, open project in favorite browser,'),
      gutil.colors.gray('auto watch file changes and rebuild the project')
    );
    callback();
  });
}

function installBower (rootPath, newFolderName, callback) {
  installer(
    rootPath,
    'bower install',
    'Bower is installing javascript packages...',
    gitInit,
    newFolderName,
    callback
  );
}

function installNpm (rootPath, newFolderName, callback) {
  installer(
    rootPath,
    'npm install',
    'NPM is installing node packages...',
    installBower,
    newFolderName,
    callback
  );
}

function simpleLogger () {
  gutil.log(
    gutil.colors.green('[-done:] A new'),
    gutil.colors.cyan('Ember.js'),
    gutil.colors.green('mvc application have been successfully created!')
  );
}

function runningCallback (isRunningTest, dest, newFolderName, callback) {
  // switch to the newly generated folder
  process.chdir(dest);

  // rename `gitignore` to `.gitignore`
  // then remove the originial `gitignore`
  gulp.src('./gitignore')
    .pipe(rename('.gitignore'))
    .on('end', function () {
      rimraf('./gitignore', function () {
      });
    })
    .pipe(gulp.dest(dest));

  if (!isRunningTest) {
    installNpm(dest, newFolderName, callback);
  } else {
    callback();
  }
}

function scaffoldFiles () {

}

function setupTask (newFolderName, options) {
  var dest = path.resolve(newFolderName);
  gutil.log(
    gutil.colors.gray('[-log:]'),
    'Starting to generate an application at',
    gutil.colors.magenta(tildify(dest))
  );

  // check for the mode, is running test or not
  var isRunningTest = options.test || false;
  // Pass in a valid git url for installing ember-application-template
  var re = /^http(?:s)?:\/\//;
  var userInputPath = options.path;
  // check for remote URL path
  var remoteUrl = (userInputPath) ?
    (re.test(userInputPath)) ?
      userInputPath : ('http://' + userInputPath) : undefined;

  // get the full path to the ember application or take the generator from github or an URL
  // skeletonsAppPath = ( userInputPath ) ? remoteUrl : getSkeletonsAppPath();
  var appSrcPath = getSkeletonsAppPath();

  if (remoteUrl !== undefined) {
    appSrcPath = remoteUrl;
  }

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath();
  var coreSrc = [skeletonsCorePath + '/**/*'];
  var appSrc = ( appSrcPath.indexOf('http') !== -1 ) ? appSrcPath : [appSrcPath + '/**/*'];

  return gulp.task('generator', function (callback) {
    gulp.src(coreSrc, {dot: true})
      .on('end', function () {
        gutil.log(
          gutil.colors.green('[-done:] A new'),
          gutil.colors.cyan('Node.js'),
          gutil.colors.green('web server have been successfully created!')
        );
        gutil.log(
          gutil.colors.gray('[-log:]'),
          gutil.colors.magenta('It may take up to 1 minute and half!')
        );
        gutil.log(
          gutil.colors.gray('[-log:]'),
          gutil.colors.magenta('Be patient, fetching packages from internet ...')
        );
      })
      .pipe(gulp.dest(dest));

    // if option.path exist and it is a git url, it will be fetched
    // Otherwise, it will use the default scaffold folder app
    if (typeof appSrc === 'string') {
      var command = 'git clone ' + appSrc + ' app';
      var rootPath = dest || process.cwd();
      var clientPath = rootPath + '/client';

      // if client/ folder is not existed, simply create one
      if (!fs.existsSync(clientPath)) {
        fs.mkdirSync(clientPath);
      }

      gutil.log(
        gutil.colors.gray('[-log:]'),
        'Going to fetch the app template from ',
        gutil.colors.cyan(appSrc)
      );

      // change to the client folder to install app template
      process.chdir(path.resolve(clientPath));

      // fetch the git url now
      exec(command, function (error, stdout, stderr) {
        if (error !== null) {
          var log = stderr.toString();
          gutil.log(gutil.colors.red('[-Error:] ' + log));
          gutil.log(gutil.colors.red('[-Error:] --path ' + appSrc + ' cannot be fetched!'));
          process.exit(0);
        }

        gutil.log(
          gutil.colors.green('[-done:] Successfully fetched and installed the app template ')
        );

        simpleLogger();

        // After fetching a git repo, then remove the .git folder
        return rimraf(path.join(dest, 'client', 'app', '.git'), function (error) {
          if (error !== null) {
            var log = stderr.toString();
            gutil.log(gutil.colors.red('[-Error:] ' + log));
            process.exit(0);
          }
          // running npm install callback
          runningCallback(isRunningTest, dest, newFolderName, callback);
        });
      });
    } else {
      gulp.src(appSrc, {dot: true})
        .on('end', function () {
          simpleLogger();
          runningCallback(isRunningTest, dest, newFolderName, callback);
        })
        .pipe(gulp.dest(dest + '/client/app'));
    }
  });
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath () {
  var skeletonsAppPath = pathResolver('skeletons/app');
  return skeletonsAppPath;
}

var create = function (generatorPath, options) {
  if (!generatorPath || typeof generatorPath !== 'string') {
    gutil.log(gutil.colors.red('[-Error:] Missing directory name.'), 'ex: em new my-app');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em new --help\'');
    process.exit(0);
  }

  // Create the folder if it is not existed
  // If existed, do what? maybe just empty it and start scaffolding???
  if (fs.existsSync(generatorPath)) {
    gutil.log(
      gutil.colors.red('[-Error:]'), 'The folder name',
      gutil.colors.red(generatorPath), 'has existed in this directory tree!'
    );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  // Setup gulp task, copy the source files into the newly create folder
  setupTask(generatorPath, options);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;
<commit_msg>move the logic into the right place<commit_after>'use strict';

var Promise = require('bluebird');
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var tildify = require('tildify');
var gulp = require('gulp');
var rimraf = require('rimraf');
var gutil = require('gulp-util');
var rename = require('gulp-rename');

// installer plugins to handle the npm and bower packages installation
function installer (rootPath, command, description, nextStepFn, newFolderName, callback) {
  rootPath = rootPath || process.cwd();
  gutil.log(gutil.colors.gray('[-log:]'), description);
  process.chdir(rootPath);
  return exec(command, function (error, stdout, stderr) {
    // process.chdir(rootPath);
    if (error !== null) {
      var log = stderr.toString();
      gutil.log(gutil.colors.red('[-Error:] ' + log));
      if (command === 'npm install') {
        gutil.log(gutil.colors.red('[-Error:] npm install failed dramatically.'));
        gutil.log(
          gutil.colors.red('[-Error:] Need to manually do \'npm install\' and \'bower install\' ')
        );
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else if (command === 'bower install') {
        gutil.log(gutil.colors.red('[-Error:] bower install failed dramatically.'));
        gutil.log(gutil.colors.red('[-Error:] Need to manually do \'bower install\''));
        gutil.log(
          gutil.colors.red('[-Error:] Before the project is fully ready for development')
        );
      } else {
        gutil.log(
          gutil.colors.red('[-Error:] initialize git repository failed dramatically.')
        );
        gutil.log(gutil.colors.red('[-Error:] Need to manually do'));
        gutil.log(gutil.colors.red('[-Error:] \'git init && git add . && git commit -m\''));
      }
      return callback(log);
    }
    nextStepFn(rootPath, newFolderName, callback);
  });
}

function gitInit (rootPath, newFolderName, callback) {
  gutil.log(
    gutil.colors.gray('[-log:]'),
    gutil.colors.cyan('em-cli'),
    'is doing REALLY hard to initialize your repo ...'
  );

  rootPath = rootPath || process.cwd();
  process.chdir(rootPath);

  var month = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  ];
  var today = new Date();
  var todayDate = today.getDate();
  var todayMonth = month[today.getMonth()];
  var todayYear = today.getFullYear();
  var command = 'git init && git add . && git commit -m \'Initial Commit @ ' +
    todayMonth + ' ' + todayDate + ', ' + todayYear + '\'';

  return exec(command, function (error, stdout, stderr) {
    if (error !== null) {
      var log = stderr.toString();
      gutil.log(gutil.colors.red('[-Error:] ' + log));
      return callback(log);
    }
    gutil.log(
      gutil.colors.green('[-done:] Initialized a new git repo and did a first commit')
    );
    gutil.log(
      gutil.colors.bold('[-copy:] =>'),
      gutil.colors.cyan('cd ' + newFolderName),
      gutil.colors.gray('# navigate to the newly created application')
    );
    gutil.log(
      gutil.colors.bold('[-copy:] =>'),
      gutil.colors.cyan('em serve'),
      gutil.colors.gray(' # kick start the server, open project in favorite browser,'),
      gutil.colors.gray('auto watch file changes and rebuild the project')
    );
    callback();
  });
}

function installBower (rootPath, newFolderName, callback) {
  installer(
    rootPath,
    'bower install',
    'Bower is installing javascript packages...',
    gitInit,
    newFolderName,
    callback
  );
}

function installNpm (rootPath, newFolderName, callback) {
  installer(
    rootPath,
    'npm install',
    'NPM is installing node packages...',
    installBower,
    newFolderName,
    callback
  );
}

function simpleLogger () {
  gutil.log(
    gutil.colors.green('[-done:] A new'),
    gutil.colors.cyan('Ember.js'),
    gutil.colors.green('mvc application have been successfully created!')
  );
}

function runningCallback (isRunningTest, dest, newFolderName, callback) {
  // switch to the newly generated folder
  process.chdir(dest);

  // rename `gitignore` to `.gitignore`
  // then remove the originial `gitignore`
  gulp.src('./gitignore')
    .pipe(rename('.gitignore'))
    .on('end', function () {
      rimraf('./gitignore', function () {
      });
    })
    .pipe(gulp.dest(dest));

  if (!isRunningTest) {
    installNpm(dest, newFolderName, callback);
  } else {
    callback();
  }
}

function scaffoldFiles () {

}

function setupTask (newFolderName, options) {
  var dest = path.resolve(newFolderName);
  gutil.log(
    gutil.colors.gray('[-log:]'),
    'Starting to generate an application at',
    gutil.colors.magenta(tildify(dest))
  );

  // check for the mode, is running test or not
  var isRunningTest = options.test || false;

  // get the full path to the core of application. ( Server && Client )
  var skeletonsCorePath = getSkeletonsCorePath();
  var coreSrc = [skeletonsCorePath + '/**/*'];

  // get the full path to the ember application or take the generator from github or an URL
  var appSrcPath = getSkeletonsAppPath(options);
  var appSrc = ( appSrcPath.indexOf('http') !== -1 ) ? appSrcPath : [appSrcPath + '/**/*'];

  return gulp.task('generator', function (callback) {
    gulp.src(coreSrc, {dot: true})
      .on('end', function () {
        gutil.log(
          gutil.colors.green('[-done:] A new'),
          gutil.colors.cyan('Node.js'),
          gutil.colors.green('web server have been successfully created!')
        );
        gutil.log(
          gutil.colors.gray('[-log:]'),
          gutil.colors.magenta('It may take up to 1 minute and half!')
        );
        gutil.log(
          gutil.colors.gray('[-log:]'),
          gutil.colors.magenta('Be patient, fetching packages from internet ...')
        );
      })
      .pipe(gulp.dest(dest));

    // if option.path exist and it is a git url, it will be fetched
    // Otherwise, it will use the default scaffold folder app
    if (typeof appSrc === 'string') {
      var command = 'git clone ' + appSrc + ' app';
      var rootPath = dest || process.cwd();
      var clientPath = rootPath + '/client';

      // if client/ folder is not existed, simply create one
      if (!fs.existsSync(clientPath)) {
        fs.mkdirSync(clientPath);
      }

      gutil.log(
        gutil.colors.gray('[-log:]'),
        'Going to fetch the app template from ',
        gutil.colors.cyan(appSrc)
      );

      // change to the client folder to install app template
      process.chdir(path.resolve(clientPath));

      // fetch the git url now
      exec(command, function (error, stdout, stderr) {
        if (error !== null) {
          var log = stderr.toString();
          gutil.log(gutil.colors.red('[-Error:] ' + log));
          gutil.log(gutil.colors.red('[-Error:] --path ' + appSrc + ' cannot be fetched!'));
          process.exit(0);
        }

        gutil.log(
          gutil.colors.green('[-done:] Successfully fetched and installed the app template ')
        );

        simpleLogger();

        // After fetching a git repo, then remove the .git folder
        return rimraf(path.join(dest, 'client', 'app', '.git'), function (error) {
          if (error !== null) {
            var log = stderr.toString();
            gutil.log(gutil.colors.red('[-Error:] ' + log));
            process.exit(0);
          }
          // running npm install callback
          runningCallback(isRunningTest, dest, newFolderName, callback);
        });
      });
    } else {
      gulp.src(appSrc, {dot: true})
        .on('end', function () {
          simpleLogger();
          runningCallback(isRunningTest, dest, newFolderName, callback);
        })
        .pipe(gulp.dest(dest + '/client/app'));
    }
  });
}

function pathResolver (relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

function getSkeletonsCorePath () {
  var skeletonsCorePath = pathResolver('skeletons/core');
  return skeletonsCorePath;
}

function getSkeletonsAppPath (options) {
  // Pass in a valid git url for installing ember-application-template
  var re = /^http(?:s)?:\/\//;
  var userInputPath = options.path;
  // check for remote URL path
  var remoteUrl = (userInputPath) ?
    (re.test(userInputPath)) ?
      userInputPath : ('http://' + userInputPath) : undefined;

  var skeletonsAppPath = (remoteUrl !== undefined) ? remoteUrl : pathResolver('skeletons/app');
  return skeletonsAppPath;
}

var create = function (generatorPath, options) {
  if (!generatorPath || typeof generatorPath !== 'string') {
    gutil.log(gutil.colors.red('[-Error:] Missing directory name.'), 'ex: em new my-app');
    gutil.log(gutil.colors.red('[-Error:]'), 'See \'em new --help\'');
    process.exit(0);
  }

  // Create the folder if it is not existed
  // If existed, do what? maybe just empty it and start scaffolding???
  if (fs.existsSync(generatorPath)) {
    gutil.log(
      gutil.colors.red('[-Error:]'), 'The folder name',
      gutil.colors.red(generatorPath), 'has existed in this directory tree!'
    );
    process.exit(0);
  } else {
    // Create a new directory name what user passed in
    fs.mkdirSync(generatorPath);
  }

  // Setup gulp task, copy the source files into the newly create folder
  setupTask(generatorPath, options);
  // Trigger the generator task
  gulp.start('generator');
};

module.exports = create;
<|endoftext|>