<commit_before>var Hapi = require('hapi'),
    TagService = require('../services/tagService.js');

module.exports = function IdeaController(config) {
    var logger = config.logger,
        db = config.db,
        authenticationProvider = config.authProvider || null,
        tagSvc = new TagService(db),
        getAuth = function() { return authenticationProvider; };

    var routes = [
        {
            path: '/tags',
            method: 'GET',
            handler: function(request, reply) {
                console.log("TESTING");
                tagSvc.getMany(
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(obj) {
                        if (obj === null) {
                            reply([]);
                        }
                        else {
                            reply(obj);
                        }
                    }
                );
            },
            config: {
                description: 'Get all tags',
                auth: getAuth(),
                validate: { }
            }
        },
        {
            path: '/tags/{tag}',
            method: 'PUT',
            handler: function(request, reply) {
                tagSvc.save(request.params.tag,
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(doc, created) {
                        if (doc === null) {
                            reply(Hapi.error.internal());
                        }
                        else {
                            reply(Hapi.response.Empty()).code(created ? 201 : 204);
                        }
                    }
                );
            },
            config: {
                description: 'Creates or updates a tag',
                auth: getAuth(),
                validate: {
                    path: {
                        tag: Hapi.types.String().required()
                    }
                }
            }
        },
        {
            path: '/tags/{tag}',
            method: 'DELETE',
            handler: function(request, reply) {
                tagSvc.remove(request.params.tag,
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(successful) {
                        if (!successful) {
                            reply(Hapi.error.notFound());
                        }
                        else {
                            reply(Hapi.response.Empty()).code(204);
                        }
                    }
                );
            },
            config: {
                description: 'Remove an existing tag',
                auth: getAuth(),
                validate: {
                    path: {
                        tag: Hapi.types.String().required()
                    }
                }
            }
        }
    ];

    this.getRoutes = function() {
        return routes;
    };

};<commit_msg>removed debugging console output<commit_after>var Hapi = require('hapi'),
    TagService = require('../services/tagService.js');

module.exports = function IdeaController(config) {
    var logger = config.logger,
        db = config.db,
        authenticationProvider = config.authProvider || null,
        tagSvc = new TagService(db),
        getAuth = function() { return authenticationProvider; };

    var routes = [
        {
            path: '/tags',
            method: 'GET',
            handler: function(request, reply) {
                tagSvc.getMany(
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(obj) {
                        if (obj === null) {
                            reply([]);
                        }
                        else {
                            reply(obj);
                        }
                    }
                );
            },
            config: {
                description: 'Get all tags',
                auth: getAuth(),
                validate: { }
            }
        },
        {
            path: '/tags/{tag}',
            method: 'PUT',
            handler: function(request, reply) {
                tagSvc.save(request.params.tag,
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(doc, created) {
                        if (doc === null) {
                            reply(Hapi.error.internal());
                        }
                        else {
                            reply(Hapi.response.Empty()).code(created ? 201 : 204);
                        }
                    }
                );
            },
            config: {
                description: 'Creates or updates a tag',
                auth: getAuth(),
                validate: {
                    path: {
                        tag: Hapi.types.String().required()
                    }
                }
            }
        },
        {
            path: '/tags/{tag}',
            method: 'DELETE',
            handler: function(request, reply) {
                tagSvc.remove(request.params.tag,
                    function(err) {
                        reply(Hapi.error.internal());
                    },
                    function(successful) {
                        if (!successful) {
                            reply(Hapi.error.notFound());
                        }
                        else {
                            reply(Hapi.response.Empty()).code(204);
                        }
                    }
                );
            },
            config: {
                description: 'Remove an existing tag',
                auth: getAuth(),
                validate: {
                    path: {
                        tag: Hapi.types.String().required()
                    }
                }
            }
        }
    ];

    this.getRoutes = function() {
        return routes;
    };

};<|endoftext|>


<commit_before>if (Posts.find().count() === 0 && process.env.NODE_ENV != "production" ) {

  var peteId = Meteor.users.insert({
    username: 'pam3961',
    profile: {
      displayName: 'Pete Mikitsh',
      givenName: 'Pete',
      initials: 'PAM',
      sn: 'Mikitsh'
    }
  });
  var pete = Meteor.users.findOne(peteId);
  Roles.addUsersToRoles(peteId, ['admin']);

  // Post with 7-day history

  var postId_seven_day = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: moment().subtract(7, 'days').valueOf(),
    title: "Build more affordable, on-campus housing.",
    description: "As there is only enough housing for half the student population, it creates a challenge to find affordably priced off-campus housing.",
    upvoters: [pete._id],
    votes: 50
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(7, 'days').valueOf(),
    score: 1,
    votes: 1
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(6, 'days').valueOf(),
    score: 10,
    votes: 10
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(5, 'days').valueOf(),
    score: 22,
    votes: 22
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(4, 'days').valueOf(),
    score: 30,
    votes: 30
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(3, 'days').valueOf(),
    score: 44,
    votes: 44
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(2, 'days').valueOf(),
    score: 47,
    votes: 47
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(1, 'day').valueOf(),
    score: 50,
    votes: 50
  });

  // Post with 3-day history

  var postId_three_day = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: moment().subtract(3, 'days').valueOf(),
    title: "Extend hours for RIT Computer Labs at peak times.",
    description: "Students often work late near the end of semester; extended lab time will allow more students to utilize this on-campus resource.",
    upvoters: [pete._id],
    votes: 4
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(3, 'days').valueOf(),
    score: 1,
    votes: 1
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(2, 'days').valueOf(),
    score: 2,
    votes: 2
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(1, 'day').valueOf(),
    score: 4,
    votes: 4
  });

  // Post with 0-day history

  var postId_no_history = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: new Date().getTime(),
    title: "Offer more options for students with unique dietary needs.",
    description: "Increase the number of options for vegan students at on-campus Dining Service locations.",
    upvoters: [pete._id],
    votes: 1
  });

  // Extra posts for testing scalability and pagination

  for (var i = 0; i < 30; i++) {
    Posts.insert({
      userId: pete._id,
      author: pete.profile.displayName,
      submitted: new Date().getTime(),
      title: 'Test post #' + i,
      description: "Foo",
      upvoters: [pete._id],
      votes: 1
    });
  }

  // Initialize Post Count singleton

  PostsCount.insert({
    count: Posts.find().count()
  });

}<commit_msg>contextual fixtures based on enviornment settings<commit_after>// Add test posts to non-production instances

if (Posts.find().count() === 0 && process.env.NODE_ENV != "production" ) {

  var peteId = Meteor.users.insert({
    username: 'pam3961',
    profile: {
      displayName: 'Pete Mikitsh',
      givenName: 'Pete',
      initials: 'PAM',
      sn: 'Mikitsh'
    }
  });
  var pete = Meteor.users.findOne(peteId);

  // Post with 7-day history

  var postId_seven_day = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: moment().subtract(7, 'days').valueOf(),
    title: "Build more affordable, on-campus housing.",
    description: "As there is only enough housing for half the student population, it creates a challenge to find affordably priced off-campus housing.",
    upvoters: [pete._id],
    votes: 50
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(7, 'days').valueOf(),
    score: 1,
    votes: 1
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(6, 'days').valueOf(),
    score: 10,
    votes: 10
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(5, 'days').valueOf(),
    score: 22,
    votes: 22
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(4, 'days').valueOf(),
    score: 30,
    votes: 30
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(3, 'days').valueOf(),
    score: 44,
    votes: 44
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(2, 'days').valueOf(),
    score: 47,
    votes: 47
  });

  Scores.insert({
    postId: postId_seven_day,
    created_at: moment().subtract(1, 'day').valueOf(),
    score: 50,
    votes: 50
  });

  // Post with 3-day history

  var postId_three_day = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: moment().subtract(3, 'days').valueOf(),
    title: "Extend hours for RIT Computer Labs at peak times.",
    description: "Students often work late near the end of semester; extended lab time will allow more students to utilize this on-campus resource.",
    upvoters: [pete._id],
    votes: 4
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(3, 'days').valueOf(),
    score: 1,
    votes: 1
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(2, 'days').valueOf(),
    score: 2,
    votes: 2
  });

  Scores.insert({
    postId: postId_three_day,
    created_at: moment().subtract(1, 'day').valueOf(),
    score: 4,
    votes: 4
  });

  // Post with 0-day history

  var postId_no_history = Posts.insert({
    userId: pete._id,
    author: pete.profile.displayName,
    submitted: new Date().getTime(),
    title: "Offer more options for students with unique dietary needs.",
    description: "Increase the number of options for vegan students at on-campus Dining Service locations.",
    upvoters: [pete._id],
    votes: 1
  });

  // Extra posts for testing scalability and pagination

  for (var i = 0; i < 30; i++) {
    Posts.insert({
      userId: pete._id,
      author: pete.profile.displayName,
      submitted: new Date().getTime(),
      title: 'Test post #' + i,
      description: "Foo",
      upvoters: [pete._id],
      votes: 1
    });
  }

}

// Initialize Post Count singleton

if (PostsCount.find().count() === 0) {
  PostsCount.insert({
    count: Posts.find().count()
  });
}

// Configure initial admin user

if (Meteor.users.find({username: "sgweb"}).count() === 0) {
  var sgwebId = Meteor.users.insert({
    username: 'sgweb',
    profile: {
      displayName: 'Pete Mikitsh (Student Employee)',
      givenName: 'Pete',
      initials: 'PAM',
      sn: 'Mikitsh'
    }
  });
  var sgweb = Meteor.users.findOne(sgwebId);
}
Roles.addUsersToRoles(sgweb, ['admin']);<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react'
import PropTypes from 'prop-types'
import { ListGroup } from 'reactstrap'
import EventsListItem from './EventsListItem'
import MinimizeButton from './MinimizeButton'
import './styles.scss'

class EventsList extends Component {
  state = {
    events: [],
    loading: true,
    noData: false,
    minimized: false
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    // If we had an array of events but they were eith filtered/researched

    if (prevState.events[0] && !nextProps.events[0]) {
      return {
        events: [],
        noData: true,
        loading: nextProps.isFetching
      }
    }

    return {
      events: nextProps.events,
      loading: nextProps.isFetching
    }
  }

  componentDidMount () {
    const timeout = 5000 // try this for 5 seconds
    const startingTime = Date.now()
    this.interval = setInterval(() => {
      // if more than 5 seconds have passed
      if (this.interval && Date.now() - startingTime > timeout) {
        this.setState({
          noData: true
        })
        clearInterval(this.interval)
      }
    }, 1000)
  }

  componentWillUnmount () {
    clearInterval(this.interval)
    this.interval = null
  }

  render () {
    const {
      events,
      loading,
      noData,
      minimized
    } = this.state

    const {
      userLocation
    } = this.props

    return (
      <Fragment>

            {this.props.children} {/* Search Box */}

          <ListGroup>
            {events && events.map((event, index) => {
              return (
                <EventsListItem
                  key={index}
                  item={event}
                  userLocation={userLocation}
                  onItemClick={this.props.toggleInfoWindow}
                />
              )
            })}
          </ListGroup>
          {(loading || !noData) && (

looking for events near you...

          )}
          {noData && (

Sorry, we couldn't find anything

around you...

          )}

        <MinimizeButton onMinimize={this.toggleMinimize} minimized={minimized} />
      </Fragment>
    )
  }

  toggleMinimize = () => {
    this.setState({ minimized: !this.state.minimized })
  }
}

EventsList.propTypes = {
  events: PropTypes.array.isRequired,
  userLocation: PropTypes.object,
  isFetching: PropTypes.bool,
  toggleInfoWindow: PropTypes.func.isRequired
}

export default EventsList
<commit_msg>fix hiding of no-events msg<commit_after>import React, { Component, Fragment } from 'react'
import PropTypes from 'prop-types'
import { ListGroup } from 'reactstrap'
import EventsListItem from './EventsListItem'
import MinimizeButton from './MinimizeButton'
import './styles.scss'

class EventsList extends Component {
  state = {
    events: [],
    loading: true,
    noData: false,
    minimized: false
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    // If we had an array of events but they were eith filtered/researched

    if (prevState.events[0] && !nextProps.events[0]) {
      return {
        events: [],
        noData: true,
        loading: nextProps.isFetching
      }
    }

    return {
      events: nextProps.events,
      loading: nextProps.isFetching
    }
  }

  componentDidMount () {
    const timeout = 5000 // try this for 5 seconds
    const startingTime = Date.now()
    this.interval = setInterval(() => {
      // if more than 5 seconds have passed
      if (this.interval && Date.now() - startingTime > timeout) {
        this.setState({
          noData: true
        })
        clearInterval(this.interval)
      }
    }, 1000)
  }

  componentWillUnmount () {
    clearInterval(this.interval)
    this.interval = null
  }

  render () {
    const {
      events,
      loading,
      noData,
      minimized
    } = this.state

    const {
      userLocation
    } = this.props

    const hasData = !!events[0]

    return (
      <Fragment>

            {this.props.children} {/* Search Box */}

          <ListGroup>
            {events && events.map((event, index) => {
              return (
                <EventsListItem
                  key={index}
                  item={event}
                  userLocation={userLocation}
                  onItemClick={this.props.toggleInfoWindow}
                />
              )
            })}
          </ListGroup>
          {(loading || !noData) && (

looking for events near you...

          )}
          {(noData && !hasData) && (

Sorry, we couldn't find anything

around you...

          )}

        <MinimizeButton onMinimize={this.toggleMinimize} minimized={minimized} />
      </Fragment>
    )
  }

  toggleMinimize = () => {
    this.setState({ minimized: !this.state.minimized })
  }
}

EventsList.propTypes = {
  events: PropTypes.array.isRequired,
  userLocation: PropTypes.object,
  isFetching: PropTypes.bool,
  toggleInfoWindow: PropTypes.func.isRequired
}

export default EventsList
<|endoftext|>


<commit_before>var Sizzle = require('sizzle');

module.exports = {
    getUniqueElement: getUniqueElement,
    getElementCount: getElementCount,
    getElementClasses: getElementClasses,
    getElementText: getElementText
};

function getUniqueElement(selectorOrElement) {
    if (typeof selectorOrElement === 'string') {
        var elements = Sizzle(selectorOrElement);
        var count = elements.length;
        if (count !== 1) {
            var errorMessage = 'Exactly one element must match selector "' + selectorOrElement + '" but found ' + count;
            throw new Error(errorMessage);
        }
        return elements[0];
    }
    if (selectorOrElement instanceof HTMLElement) {
        return selectorOrElement;
    }
    throw new Error('Illegal argument: Must be selector or HTMLElement');
}

function getElementCount(selector) {
    return Sizzle(selector).length;
}

function getElementClasses(selector) {
    var element = getUniqueElement(selector);
    return Array.from(element.classList);
}

function getElementText(selector) {
    var element = getUniqueElement(selector);
    return element.innerText;
}<commit_msg>assert.elementText now uses element.textContent instead of element.innerText<commit_after>var Sizzle = require('sizzle');

module.exports = {
    getUniqueElement: getUniqueElement,
    getElementCount: getElementCount,
    getElementClasses: getElementClasses,
    getElementText: getElementText
};

function getUniqueElement(selectorOrElement) {
    if (typeof selectorOrElement === 'string') {
        var elements = Sizzle(selectorOrElement);
        var count = elements.length;
        if (count !== 1) {
            var errorMessage = 'Exactly one element must match selector "' + selectorOrElement + '" but found ' + count;
            throw new Error(errorMessage);
        }
        return elements[0];
    }
    if (selectorOrElement instanceof HTMLElement) {
        return selectorOrElement;
    }
    throw new Error('Illegal argument: Must be selector or HTMLElement');
}

function getElementCount(selector) {
    return Sizzle(selector).length;
}

function getElementClasses(selector) {
    var element = getUniqueElement(selector);
    return Array.from(element.classList);
}

function getElementText(selector) {
    var element = getUniqueElement(selector);
    return element.textContent;
}<|endoftext|>


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

'use strict';

const assert = require('assert');
const semver = require('semver');
const _ = require('lodash');
const conf = require('./conf');
const log = require('./log');

checkNodeVersion();

const stateChangeCallbacks = [];
let shutdownInProgress = false;

const shutdownOrder = {
    beforeShutdown: 1,
    shutdown: 2,
    afterShutdown: 3
};

process.on('unhandledRejection', (reason, p) => {
    log.warn(`Unhandled Rejection at: Promise ${p}, reason: ${reason}`);
    throw reason;
});

exports.configureProcess = function configureProcess(serverName) {
    const processName = `mas-${serverName}-${conf.get('common:env')}`;

    process.umask(18); // file: rw-r--r-- directory: rwxr-xr-x
    process.title = processName;

    log.warn(`${serverName} starting...`);

    process.on('SIGINT', execShutdown);
    process.on('SIGTERM', execShutdown);

    process.on('message', msg => {
        // Message from PM2
        if (msg === 'shutdown') {
            execShutdown();
        }
    });
};

exports.on = function on(state, callback) {
    assert(shutdownOrder[state]);

    stateChangeCallbacks.push({ state, cb: callback });
};

exports.shutdown = function shutdown() {
    execShutdown();
};

async function execShutdown() {
    if (shutdownInProgress) {
        return;
    }

    shutdownInProgress = true;

    log.warn('Shutdown sequence started.');

    const entries = _.sortBy(stateChangeCallbacks, entry => shutdownOrder[entry.state]);

    for (const entry of entries) {
        await entry.cb();

        console.log('Shutdown complete.'); // eslint-disable-line no-console
        process.exit(0);
    }
}

function checkNodeVersion() {
    if (semver.lt(process.version, 'v4.0.0')) {
        const msg = 'ERROR: Installed Node.js version must be at least v5.0.0';
        console.log(msg); // eslint-disable-line no-console
        process.exit(1);
    }
}
<commit_msg>Require node 6<commit_after>//
//   Copyright 2014-2015 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

const assert = require('assert');
const semver = require('semver');
const _ = require('lodash');
const conf = require('./conf');
const log = require('./log');

checkNodeVersion();

const stateChangeCallbacks = [];
let shutdownInProgress = false;

const shutdownOrder = {
    beforeShutdown: 1,
    shutdown: 2,
    afterShutdown: 3
};

process.on('unhandledRejection', (reason, p) => {
    log.warn(`Unhandled Rejection at: Promise ${p}, reason: ${reason}`);
    throw reason;
});

exports.configureProcess = function configureProcess(serverName) {
    const processName = `mas-${serverName}-${conf.get('common:env')}`;

    process.umask(18); // file: rw-r--r-- directory: rwxr-xr-x
    process.title = processName;

    log.warn(`${serverName} starting...`);

    process.on('SIGINT', execShutdown);
    process.on('SIGTERM', execShutdown);

    process.on('message', msg => {
        // Message from PM2
        if (msg === 'shutdown') {
            execShutdown();
        }
    });
};

exports.on = function on(state, callback) {
    assert(shutdownOrder[state]);

    stateChangeCallbacks.push({ state, cb: callback });
};

exports.shutdown = function shutdown() {
    execShutdown();
};

async function execShutdown() {
    if (shutdownInProgress) {
        return;
    }

    shutdownInProgress = true;

    log.warn('Shutdown sequence started.');

    const entries = _.sortBy(stateChangeCallbacks, entry => shutdownOrder[entry.state]);

    for (const entry of entries) {
        await entry.cb();

        console.log('Shutdown complete.'); // eslint-disable-line no-console
        process.exit(0);
    }
}

function checkNodeVersion() {
    if (semver.lt(process.version, 'v6.0.0')) {
        const msg = 'ERROR: Installed Node.js version must be at least v6.0.0';
        console.log(msg); // eslint-disable-line no-console
        process.exit(1);
    }
}
<|endoftext|>


<commit_before>module.exports = exports = function(dust){
	var _ = require('lodash');
	var self = this;
	dust.helpers["route"] = function(chunk, context, bodies, params){
		var path = params.route;
		if ( self._ns && self._ns !== "/" ) {
			chunk.write(self._ns);
		}
	    return _.isFunction(path) ? path(chunk, context) : chunk.write(path);
	}
	dust.helpers["form"] = function(chunk, context, bodies, params){
		var path = params.route, method, hiddenmethod, enctype;
		if ( params.method ) {
			method = params.method;
		}
		if ( params.model ) {
			hiddenmethod = 'put';
		}
		enctype = params.enctype || "application/x-www-form-urlencoded";

		method = method || "post";
		method = dust.helpers.tap(method, chunk, context);
		if ( method !== "get" && method !== "post") {
			hiddenmethod = method;
			method = "post";
		}
		chunk.write('<form method="');
		chunk.write(method);

		chunk.write('" action="');
		if ( self._ns && self._ns !== "/" ) {
			chunk.write(self._ns);
		}
	    _.isFunction(path) ? path(chunk, context) : chunk.write(path);

	    chunk.write('" enctype="')
	    _.isFunction(enctype) ? enctype(chunk, context) : chunk.write(enctype);
	    if ( params.class ) {
	    	chunk.write('" class="')
	    	_.isFunction(params.class) ? params.class(chunk, context) : chunk.write(params.class);
	    }
		chunk.write('">')
		if ( hiddenmethod ) {
			chunk.write('<input type="hidden" name="_method" value="'+hiddenmethod+'"/>')
		}

		chunk.write('<input type="hidden" name="_csrf" value=""/>')
		if ( bodies.block ) {
			bodies.block(chunk, context);
		}
	    return chunk.write('</form>');

	}
	dust.helpers["param"] = function(chunk, context, bodies, params) {
		var name = params.name;
		context.current()[name]=function(chunk){
			bodies.block(chunk, context);
			return chunk;
		}
		return chunk;
	}
	var moment = require('moment');
	dust.helpers["date"] = function(chunk, context, bodies,params) {
		var key = params.key;
		var format = params.format;
		console.log(key,format,"what the fuck");

		return chunk.write(moment(key).zone(8).format(format));
	}
}<commit_msg>removing zone from moment<commit_after>module.exports = exports = function(dust){
	var _ = require('lodash');
	var self = this;
	dust.helpers["route"] = function(chunk, context, bodies, params){
		var path = params.route;
		if ( self._ns && self._ns !== "/" ) {
			chunk.write(self._ns);
		}
	    return _.isFunction(path) ? path(chunk, context) : chunk.write(path);
	}
	dust.helpers["form"] = function(chunk, context, bodies, params){
		var path = params.route, method, hiddenmethod, enctype;
		if ( params.method ) {
			method = params.method;
		}
		if ( params.model ) {
			hiddenmethod = 'put';
		}
		enctype = params.enctype || "application/x-www-form-urlencoded";

		method = method || "post";
		method = dust.helpers.tap(method, chunk, context);
		if ( method !== "get" && method !== "post") {
			hiddenmethod = method;
			method = "post";
		}
		chunk.write('<form method="');
		chunk.write(method);

		chunk.write('" action="');
		if ( self._ns && self._ns !== "/" ) {
			chunk.write(self._ns);
		}
	    _.isFunction(path) ? path(chunk, context) : chunk.write(path);

	    chunk.write('" enctype="')
	    _.isFunction(enctype) ? enctype(chunk, context) : chunk.write(enctype);
	    if ( params.class ) {
	    	chunk.write('" class="')
	    	_.isFunction(params.class) ? params.class(chunk, context) : chunk.write(params.class);
	    }
		chunk.write('">')
		if ( hiddenmethod ) {
			chunk.write('<input type="hidden" name="_method" value="'+hiddenmethod+'"/>')
		}

		chunk.write('<input type="hidden" name="_csrf" value=""/>')
		if ( bodies.block ) {
			bodies.block(chunk, context);
		}
	    return chunk.write('</form>');

	}
	dust.helpers["param"] = function(chunk, context, bodies, params) {
		var name = params.name;
		context.current()[name]=function(chunk){
			bodies.block(chunk, context);
			return chunk;
		}
		return chunk;
	}
	var moment = require('moment');
	dust.helpers["date"] = function(chunk, context, bodies,params) {
		var key = params.key;
		var format = params.format;

		return chunk.write(moment(key).format(format));
	}
}<|endoftext|>


<commit_before>/**
 * CoverCouch 0.1.1 default _design/acl
 * Created by ermouth on 21.01.15.
 */

module.exports = function(){

	// To make JSON, pasteable in CouchDB as new doc,
	// use JSON editor http://cloudwall.me/etc/json-editor.html –
	// just paste raw ddoc definition from below.

	var ddoc = {
		_id:"_design/acl",
		options:{
			local_seq:true,
			include_design:true
		},

		type:"ddoc",
		stamp:Date.now(),
		version:"0.1.0",

		acl:[],
		/*
		restrict:{
			"*":[]
		},
		dbacl:{
			_r:[],
			_w:[],
			_d:[]
		},
		*/
		views:{
			acl:{
				map: function(doc) {

					// Map fn that generates ACL index

					var r = {
							s:doc._local_seq,
							p:"",
							_r:{},
							_w:{},
							_d:{}
						},
						tmp="", i, ctr = 0,
						cr = doc.creator, acl = doc.acl, ow = doc.owners,
						S = "string", O = "object", F = "function",
						rr = /^r-/, ru = /^u-/;

					if (typeof cr == S && cr) {
						tmp = cr;
						if (!ru.test(tmp)) tmp = 'u-'+tmp;
						r._r[tmp] =  r._w[tmp] =  r._d[tmp] = 1;
						ctr+=1;
					}

					if (acl != null && typeof acl == O && typeof acl.slice == F ) {
						for (i=0;i<acl.length;i++) {
							tmp = acl[i];
							if (typeof tmp == S) {
								if (rr.test(tmp) || ru.test(tmp)) r._r[tmp] = 1;
								else r._r['u-'+tmp] = 1;
							}
						}
						ctr+=1;
					}

					if (ow != null && typeof ow == O && typeof ow.slice == F ) {
						for (i=0;i<ow.length;i++) {
							tmp = ow[i];
							if (typeof tmp == S) {
								if (!rr.test(tmp) && !ru.test(tmp)) tmp = 'u-'+tmp;
								r._r[tmp] =  r._w[tmp] = 1;
							}
						}
						ctr+=1;
					}

					if (!ctr) {
						tmp = "r-*";
						if (/^_design/.test(doc._id)) r._r[tmp] = 1;
						else r._r[tmp] =  r._w[tmp] =  r._d[tmp] = 1;
					}

					if (typeof doc.parent == S) r.p = doc.parent;

					emit(doc._id, r);
				}
			}
		},
		validate_doc_update:function(nd, od, userCtx, secObj) {
			var adm =!!( userCtx.roles.indexOf("_admin")>=0 ),
				u = userCtx.name,
				uu = 'u-'+ u,
				O = 'object',
				F = 'function',
				isA = function(o){
					return (typeof o == O && typeof o.slice == F);
				};

			if (!adm) {
				if (!od) {
					// Insert
					if (nd.creator && nd.creator != u && nd.creator != uu)
						throw({forbidden: 'Can’t create doc on behalf of other user.'});
				} else {
					// Update
					var odc = od.creator,
						odw = (isA(od.owners)?od.owners:[]).sort(),
						oda = isA(od.acl)?od.acl.sort()+'':'',
						ndc = nd.creator,
						ndw = (isA(nd.owners)?nd.owners:[]).sort(),
						nda = isA(nd.acl)?nd.acl.sort()+'':'';

					if (odc && odc != ndc) throw({
						forbidden: 'Creator can not be changed.'
					});

					var notCreator = (ndc != u && ndc != uu),
						notOwner = notCreator && odw.indexOf(u)==-1 && odw.indexOf(uu)==-1;

					if (notCreator && odw+'' != ndw +'') throw({
						forbidden: 'Owners list can not be changed.'
					});

					if (notOwner && oda != nda) throw({
						forbidden: 'Readers list can not be changed.'
					});
				}
			}
		}
	}

	return ddoc;

}<commit_msg>0.1.3 default ddoc update<commit_after>/**
 * CoverCouch 0.1.1 default _design/acl
 * Created by ermouth on 21.01.15.
 */

module.exports = function(){

	// To make JSON, pasteable in CouchDB as new doc,
	// use JSON editor http://cloudwall.me/etc/json-editor.html –
	// just paste raw ddoc definition from below.

	var ddoc = {
		_id:"_design/acl",
		options:{
			local_seq:true,
			include_design:true
		},

		type:"ddoc",
		stamp:Date.now(),
		version:"0.1.3",

		acl:[],
		/*
		restrict:{
			"*":[]
		},
		dbacl:{
			_r:[],
			_w:[],
			_d:[]
		},
		*/
		views:{
			acl:{
				map: function(doc) {

					// Map fn that generates ACL index

					var r = {
							s:doc._local_seq,
							p:"",
							_r:{},
							_w:{},
							_d:{}
						},
						tmp="", i, ctr = 0,
						cr = doc.creator, acl = doc.acl, ow = doc.owners,
						S = "string", O = "object", F = "function",
						rr = /^r-/, ru = /^u-/;

					if (typeof cr == S && cr) {
						tmp = cr;
						if (!ru.test(tmp)) tmp = 'u-'+tmp;
						r._r[tmp] =  r._w[tmp] =  r._d[tmp] = 1;
						ctr+=1;
					}

					if (acl != null && typeof acl == O && typeof acl.slice == F ) {
						for (i=0;i<acl.length;i++) {
							tmp = acl[i];
							if (typeof tmp == S) {
								if (rr.test(tmp) || ru.test(tmp)) r._r[tmp] = 1;
								else r._r['u-'+tmp] = 1;
							}
						}
						ctr+=1;
					}

					if (ow != null && typeof ow == O && typeof ow.slice == F ) {
						for (i=0;i<ow.length;i++) {
							tmp = ow[i];
							if (typeof tmp == S) {
								if (!rr.test(tmp) && !ru.test(tmp)) tmp = 'u-'+tmp;
								r._r[tmp] =  r._w[tmp] = 1;
							}
						}
						ctr+=1;
					}

					if (!ctr) {
						tmp = "r-*";
						if (/^_design/.test(doc._id)) r._r[tmp] = 1;
						else r._r[tmp] =  r._w[tmp] =  r._d[tmp] = 1;
					}

					if (typeof doc.parent == S) r.p = doc.parent;

					emit(doc._id, r);
				}
			}
		},
		validate_doc_update:function(nd, od, userCtx, secObj) {
			var adm =!!( userCtx.roles.indexOf("_admin")>=0 ),
				u = userCtx.name,
				uu = 'u-'+ u,
				O = 'object',
				F = 'function',
				isA = function(o){
					return (typeof o == O && typeof o.slice == F);
				};

			if (!adm) {
				if (!od) {
					// Insert
					if (nd.creator && nd.creator != u && nd.creator != uu)
						throw({forbidden: 'Can’t create doc on behalf of other user.'});
				} else {
					// Update or delete
					var odc = od.creator,
						odw = (isA(od.owners)?od.owners:[]).sort(),
						oda = isA(od.acl)?od.acl.sort()+'':'',
						ndc = nd.creator,
						ndw = (isA(nd.owners)?nd.owners:[]).sort(),
						nda = isA(nd.acl)?nd.acl.sort()+'':'',
						notCreator = (odc != u && odc != uu),
						notOwner = notCreator && odw.indexOf(u)==-1 && odw.indexOf(uu)==-1;

					if (!nd._deleted) {
						if (odc && odc != ndc) throw({
							forbidden: 'Creator can not be changed.'
						});

						if (notCreator && odw+'' != ndw +'') throw({
							forbidden: 'Owners list can not be changed.'
						});

						if (notOwner && oda != nda) throw({
							forbidden: 'Readers list can not be changed.'
						});
					}
					else {
						// Delete
						if (notOwner) throw({
							forbidden: 'You can’t delete doc.'
						});
					}

				}
			}
		}
	}

	return ddoc;

}<|endoftext|>


<commit_before>/**
 * Created by Omnius on 18/07/2016.
 */
'use strict';

const Confidence = require('confidence');

const defaultCriteria = {
    env: process.env.NODE_ENV
};

const manifest = {
    server: {
        app: {},
        connections: {
            routes: {
                files: {relativeTo: process.cwd() + '/views'}
            },
            router: {
                isCaseSensitive: false,
                stripTrailingSlash: true
            }
        }
    },
    connections: [
        {
            host: 'localhost',
            // $lab:coverage:off$
            port: process.env.PORT || 8088,
            // $lab:coverage:on$
            labels: ['web']
        }
    ],
    registrations: [
        // Templates, views, UI-related
        {plugin: 'inert'},
        {plugin: 'vision'},
        {
            plugin: {
                register: 'visionary',
                options: {
                    path: 'views/layouts',
                    partialsPath: 'views/layouts/partials',
                    engines: {mustache: 'handlebars'}
                }
            }
        },

        // Auuthentication, CSP's, headers, and user-agent-related
        {plugin: 'hapi-auth-basic'},
        {plugin: 'hapi-auth-hawk'},
        {plugin: './auth/basic/basicLoginAuth.js'},
        // customLoginAuth.js for showing custom plugin demo only
        {plugin: './auth/custom/customLoginAuth.js'},
        {plugin: './auth/hawk/hawkAuth.js'},
        // {
        //     plugin: {
        //         register: 'blankie',
        //         options: {
        //             defaultSrc: 'self'
        //         }
        //     }
        // },
        // {
        //     plugin: {
        //         register: 'crumb',
        //         options: {
        //             key: 'crumb',
        //             size: 43,
        //             restful: false,
        //             autoGenerate: true,
        //             addToViewContext: true,
        //             cookieOptions: {clearInvalid: true}
        //         }
        //     }
        // },
        {plugin: 'scooter'},

        // Routes, handlers, methods auto-injection-related
        {
            plugin: {
                register: 'acquaint',
                options: {
                    routes: [
                        {
                            includes: ['server/routes/**/*.js'],
                            ignores: ['server/routes/preauth/*.js', 'server/routes/schemas/*.js']
                        }
                    ],
                    handlers: [
                        {includes: ['server/handlers/**/*.js']}
                    ],
                    methods: [
                        {
                            prefix: 'dao',
                            includes: ['server/methods/dao/*.js']
                        }
                    ]
                }
            }
        },

        // Params, query, and payload-related
        {
            plugin: {
                register: 'disinfect',
                options: {
                    deleteEmpty: true,
                    deleteWhitespace: true,
                    disinfectQuery: true,
                    disinfectParams: true,
                    disinfectPayload: true
                }
            }
        },

        // Cache and database-related
        {
            plugin: {
                register: 'hapi-ioredis',
                options: {
                    url: 'redis://127.0.0.1:6379'
                }
            }
        },

        // Logs-related
        {
            plugin: {
                register: 'good',
                options: {
                    ops: {interval: 3600 * 1000},
                    reporters: {
                        console: [
                            {
                                module: 'good-squeeze',
                                name: 'Squeeze',
                                args: [{
                                    ops: '*',
                                    log: '*',
                                    error: '*',
                                    response: '*'
                                }]
                            },
                            {module: 'good-console'},
                            'stdout'
                        ]
                    }
                }
            }
        }
    ]
};

const store = new Confidence.Store(manifest);

exports.get = (key, criteria) => {

    return store.get(key, criteria || defaultCriteria);
};
<commit_msg>Add plugin blankie and crumb cookie options<commit_after>/**
 * Created by Omnius on 18/07/2016.
 */
'use strict';

const Confidence = require('confidence');

const defaultCriteria = {
    env: process.env.NODE_ENV
};

const manifest = {
    server: {
        app: {},
        connections: {
            routes: {
                files: {relativeTo: process.cwd() + '/views'}
            },
            router: {
                isCaseSensitive: false,
                stripTrailingSlash: true
            }
        }
    },
    connections: [
        {
            host: 'localhost',
            // $lab:coverage:off$
            port: process.env.PORT || 8088,
            // $lab:coverage:on$
            labels: ['web']
        }
    ],
    registrations: [
        // Templates, views, UI-related
        {plugin: 'inert'},
        {plugin: 'vision'},
        {
            plugin: {
                register: 'visionary',
                options: {
                    path: 'views/layouts',
                    partialsPath: 'views/layouts/partials',
                    engines: {mustache: 'handlebars'}
                }
            }
        },

        // Auuthentication, CSP's, headers, and user-agent-related
        {plugin: 'hapi-auth-basic'},
        {plugin: 'hapi-auth-hawk'},
        {plugin: './auth/basic/basicLoginAuth.js'},
        // customLoginAuth.js for showing custom plugin demo only
        {plugin: './auth/custom/customLoginAuth.js'},
        {plugin: './auth/hawk/hawkAuth.js'},
        {
            plugin: {
                register: 'blankie',
                options: {
                    defaultSrc: 'self'
                }
            }
        },
        {
            plugin: {
                register: 'crumb',
                options: {
                    key: 'crumbz',
                    size: 43,
                    autoGenerate: true,
                    addToViewContext: true,
                    restful: false,
                    cookieOptions: {
                        ttl: 1000,
                        isSecure: false,
                        isHttpOnly: true,
                        clearInvalid: true,
                        domain: '127.0.0.1',
                        encoding: 'none'
                    }
                }
            }
        },
        {plugin: 'scooter'},

        // Routes, handlers, methods auto-injection-related
        {
            plugin: {
                register: 'acquaint',
                options: {
                    routes: [
                        {
                            includes: ['server/routes/**/*.js'],
                            ignores: ['server/routes/preauth/*.js', 'server/routes/schemas/*.js']
                        }
                    ],
                    handlers: [
                        {includes: ['server/handlers/**/*.js']}
                    ],
                    methods: [
                        {
                            prefix: 'dao',
                            includes: ['server/methods/dao/*.js']
                        }
                    ]
                }
            }
        },

        // Params, query, and payload-related
        {
            plugin: {
                register: 'disinfect',
                options: {
                    deleteEmpty: true,
                    deleteWhitespace: true,
                    disinfectQuery: true,
                    disinfectParams: true,
                    disinfectPayload: true
                }
            }
        },

        // Cache and database-related
        {
            plugin: {
                register: 'hapi-ioredis',
                options: {
                    url: 'redis://127.0.0.1:6379'
                }
            }
        },

        // Logs-related
        {
            plugin: {
                register: 'good',
                options: {
                    ops: {interval: 3600 * 1000},
                    reporters: {
                        console: [
                            {
                                module: 'good-squeeze',
                                name: 'Squeeze',
                                args: [{
                                    ops: '*',
                                    log: '*',
                                    error: '*',
                                    response: '*'
                                }]
                            },
                            {module: 'good-console'},
                            'stdout'
                        ]
                    }
                }
            }
        }
    ]
};

const store = new Confidence.Store(manifest);

exports.get = (key, criteria) => {

    return store.get(key, criteria || defaultCriteria);
};
<|endoftext|>


<commit_before>/*
* errorParser - Function
* @description: Parse the errors to humanize for the final user
*/

module.exports = function(errors){

  var parsedErrors = '';
  var stringErrors = [];
  var objectErrors = [];

  /* If errors type isn't Array return parsing error */
  if(!_.isArray(errors)) return 'Error parsing the errors, Array required.';

  /* Diference the String type errors and Object type errors */
  _.each(errors, function(error){
    if(typeof error === 'string'){
      stringErrors.push(error);
    }else{
      objectErrors.push(error);
    }
  });

  /* If we only have one string type error use is instead of are */
  if(stringErrors.length === 1){
    parsedErrors += stringErrors[0] + ' is required.';
  }else if(stringErrors.length > 1){
    parsedErrors += stringErrors.join(', ') + ' are required.'
  }

  /* Parse the object type errors */
  if(objectErrors.length){
    parsedErrors += '\n';
    _.each(objectErrors, function(value){
      if(value.error){
        parsedErrors += value.error + '\n';
      }
    });
  }

  return parsedErrors;

};
<commit_msg>Fixed some typo error<commit_after>/*
* errorParser - Function
* @description: Parse the errors to humanize for the final user
*/

module.exports = function(errors){

  var parsedErrors = '';
  var stringErrors = [];
  var objectErrors = [];

  /* If errors type isn't Array return parsing error */
  if(!_.isArray(errors)) return 'Error parsing the errors, Array required.';

  /* Diference the String type errors and Object type errors */
  _.each(errors, function(error){
    if(typeof error === 'string'){
      stringErrors.push(error);
    }else{
      objectErrors.push(error);
    }
  });

  /* If we only have one string type error use is instead of are */
  if(stringErrors.length === 1){
    parsedErrors += stringErrors[0] + ' is required.';
  }else if(stringErrors.length > 1){
    parsedErrors += stringErrors.join(', ') + ' are required.'
  }

  /* Parse the object type errors */
  if(objectErrors.length){
    _.each(objectErrors, function(value){
      if(value.error){
        parsedErrors += ' ' + value.error;
      }
    });
  }

  return parsedErrors;

};
<|endoftext|>


<commit_before>
/*

  Metadata.js

  Metadata is stored as comments near the beginning of an HTML file.
  e.g. DATA=recipes:/api/recipes{slug,url}?recipe.key=<slug>,/users

*/

var Utils     = require("./utils"),
    Universql = require("universql"),
    Metadata  = {};

module.exports = Metadata;

/*

  function extract

  Extracts pertinent metadata for querying.

*/

Metadata.extract = function(str) {

  var names = ["QUERY", "COOKIES", "SESSION"],
      re    = new RegExp("(\\b(?:" + names.join("|") + ")\\=[^\\n\\r]+)", "g"),
      meta  = {};

  Utils.getRegExpMatches(str, re, 1).map(Metadata.parse).forEach(function(metadata) {
    meta[metadata["name"]] = meta[metadata["name"]] || [];
    meta[metadata["name"]].push(metadata.value);
  });

  return meta;

}

/*

  function parse

  Parse query string

*/

Metadata.parse = function(str) {

  var matches = str.trim().split(/\=/),
      name = matches.shift().toLowerCase(),
      value;

  // Handle different types of metadata differently
  switch (name) {
    case "cookies":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    case "session":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    default:
      value = Metadata.parseQuery(matches.join("="));
      break;
  }

  return { name : name, value : value };

}

/*

  function parseQuery

  Parses a specific metadata query.

*/

Universql.addAdapter(require("universql-json"));
var queryCache = {};

Metadata.parseQuery = function(str) {

  var key, idx;

  // Remove index if possible
  if (idx = Utils.getRegExpMatches(str, /\[(\d+)\]$/g, 1)[0])
    str = str.replace(/\[\d+\]$/, "");

  // Allow assignment to key
  if (/^[a-zA-Z_$][0-9a-zA-Z_$]*:["']/.test(str)) {
    str = str.split(":");
    key = str.shift();
    str = str.join(":");
  }

  // Remove quotes
  if (str.length > 1 && str[0] === str[str.length-1] && ("'" === str[0] || '"' === str[0]))
    str = str.slice(1, -1);

  query = queryCache[str] || (queryCache[str] = new Universql(str));

  return { idx : idx, key : key, query : query }

}
<commit_msg>Metadata#parseQuery: refactors<commit_after>
/*

  Metadata.js

  Metadata is stored as comments near the beginning of an HTML file.
  e.g. DATA=recipes:/api/recipes{slug,url}?recipe.key=<slug>,/users

*/

var Utils     = require("./utils"),
    Universql = require("universql"),
    Metadata  = {};

module.exports = Metadata;

/*

  function extract

  Extracts pertinent metadata for querying.

*/

Metadata.extract = function(str) {

  var names = ["QUERY", "COOKIES", "SESSION"],
      re    = new RegExp("(\\b(?:" + names.join("|") + ")\\=[^\\n\\r]+)", "g"),
      meta  = {};

  Utils.getRegExpMatches(str, re, 1).map(Metadata.parse).forEach(function(metadata) {
    meta[metadata["name"]] = meta[metadata["name"]] || [];
    meta[metadata["name"]].push(metadata.value);
  });

  return meta;

}

/*

  function parse

  Parse query string

*/

Metadata.parse = function(str) {

  var matches = str.trim().split(/\=/),
      name = matches.shift().toLowerCase(),
      value;

  // Handle different types of metadata differently
  switch (name) {
    case "cookies":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    case "session":
      value = JSON.parse("{" + matches[1] + "}");
      break;
    default:
      value = Metadata.parseQuery(matches.join("="));
      break;
  }

  return { name : name, value : value };

}

/*

  function parseQuery

  Parses a specific metadata query.

*/

Universql.addAdapter(require("universql-json"));
var queryCache = {};

Metadata.parseQuery = function(str) {

  var key, idx;

  if (!str || !str.length) throw new Error("No query string provided");

  // Allow assignment to key: QUERY=key:"query..." or QUERY=key:'query...'
  // Final portion allows for index selection
  if (/^[a-zA-Z_$][0-9a-zA-Z_$]*:".+"(\[(\d+)\])?$/.test(str) || /^[a-zA-Z_$][0-9a-zA-Z_$]*:'.+'(\[(\d+)\])?$/.test(str)) {
    str = str.split(":");
    key = str.shift();
    str = str.join(":");
  }

  // If quotes...
  if ("'" === str[0] || '"' === str[0]) {

    // But not before removing index...
    if (idx = Utils.getRegExpMatches(str, /\[(\d+)\]$/g, 1)[0])
      str = str.replace(/\[\d+\]$/, "");

    // Check to see properly formed
    if (str[0] !== str[str.length-1])
      throw new Error("Query quotes are mismatched");

    // Finally, remove the quotes...
    str = str.slice(1, -1);

  }

  // Queries can be cached as we are simply storing translation
  query = queryCache[str] || (queryCache[str] = new Universql(str));

  return { idx : idx, key : key, query : query }

}
<|endoftext|>


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

$(function() {
    $('[data-toggle="tooltip"]').tooltip()
})

//--- cards -------------------------------------
$('.card-primary,.card-success,.card-info,.card-danger,.card-warning').addClass('card-colored');

var types = {
    array: {href: "/types#Array & List"}
    ,boolean: {href: "/types#Boolean"}
    ,float: {href: "/types#Float"}
    ,int: {href: "/types#Integer"}
    ,integer: {href: "/types#Integer"}
    ,string: {href: "/types#String"}
    ,vector: {href: "/types#Vector"}

    ,duration: {href: "/types#Duration"}
};
var modules = {
    'extents': {
     href: "/modules/extents"
    }, 'boolean': {
     href: "/types#Boolean"
    }
};
$('mark,code').each(function (item) {
    var e = $(this);
    var text = e.text();
    // Terminate as this is most likely a block of code, rather than just a type name.
    if (text.length > 64) {
        return;
    }
    var classToAdd = 'data-type';
    var foundType = types[text.trim().toLowerCase()];
    if (!foundType) {
        foundType = modules[text.trim().toLowerCase()];
        classToAdd = 'module-type';
    }
    if (foundType) {
        e.text(""); // Remove original text
        var anchor = document.createElement("a");
        anchor.href = foundType.href;
        anchor.innerHTML = text; // add original text in the anchor tag
        e.addClass(classToAdd);
        e.append(anchor);
    }
});
$(function(){
    $('pre code').each(function() {
        var lines = $(this).text().split('\s').length - 1;
        var $numbering = $('<ul/>').addClass('pre-numbering');
        $(this)
            .addClass('has-numbering')
            .parent()
            .append($numbering);
        for(i=1;i<=lines;i++){
            $numbering.append($('<li/>').text(i));
        }
    });
});
<commit_msg>Add extent and filter types in custom.js.<commit_after>/*
 * Copyright 2016 Ali Moghnieh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

$(function() {
    $('[data-toggle="tooltip"]').tooltip()
})

//--- cards -------------------------------------
$('.card-primary,.card-success,.card-info,.card-danger,.card-warning').addClass('card-colored');

var types = {
    array: {href: "/types#Array & List"}
    ,boolean: {href: "/types#Boolean"}
    ,float: {href: "/types#Float"}
    ,int: {href: "/types#Integer"}
    ,integer: {href: "/types#Integer"}
    ,string: {href: "/types#String"}
    ,vector: {href: "/types#Vector"}

    ,duration: {href: "/types#Duration"}

    ,extent: {href: "/types#Extent"}
    ,filter: {href: "/types#Filter"}
};
var modules = {
    'extents': {
     href: "/modules/extents"
    }, 'boolean': {
     href: "/types#Boolean"
    }
};
$('mark,code').each(function (item) {
    var e = $(this);
    var text = e.text();
    // Terminate as this is most likely a block of code, rather than just a type name.
    if (text.length > 64) {
        return;
    }
    var classToAdd = 'data-type';
    var foundType = types[text.trim().toLowerCase()];
    if (!foundType) {
        foundType = modules[text.trim().toLowerCase()];
        classToAdd = 'module-type';
    }
    if (foundType) {
        e.text(""); // Remove original text
        var anchor = document.createElement("a");
        anchor.href = foundType.href;
        anchor.innerHTML = text; // add original text in the anchor tag
        e.addClass(classToAdd);
        e.append(anchor);
    }
});
$(function(){
    $('pre code').each(function() {
        var lines = $(this).text().split('\s').length - 1;
        var $numbering = $('<ul/>').addClass('pre-numbering');
        $(this)
            .addClass('has-numbering')
            .parent()
            .append($numbering);
        for(i=1;i<=lines;i++){
            $numbering.append($('<li/>').text(i));
        }
    });
});
<|endoftext|>


<commit_before>// Userlist data array for filling in info box
var userListData = [];

// DOM Ready =============================================================
$(document).ready(function() {

  // Populate the user table on initial page load
  populateTable();

  // Username link click
  $('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);

  // Add User button click
  $('#btnAddUser').on('click', addUser);

  // Delete User link click
  $('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);

});

// Functions =============================================================

// Fill table with data
function populateTable() {

  // Empty content string
  var tableContent = '';

  // jQuery AJAX call for JSON
  $.getJSON( '/userlist', function( data ) {

    // Stick our user data array into a userlist variable in the global object
    userListData = data;

    // For each item in our JSON, add a table row and cells to the content string
    $.each(data, function(){
      tableContent += '
';
      tableContent += '' + this.username + '	';
      tableContent += '' + this.email + '	';
      tableContent += 'delete	'
    });

    // Inject the whole content string into our existing HTML table
    $('#userList table tbody').html(tableContent);
  });
};

// Show User Info
function showUserInfo(event) {

  // Prevent Link from Firing
  event.preventDefault();

  // Retrieve username from link rel attribute
  var thisUserName = $(this).attr('rel');

  // Get Index of object based on id value
  var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);

  // Get our User Object
  var thisUserObject = userListData[arrayPosition];

  //Populate Info Box
  $('#userInfoName').text(thisUserObject.fullname);
  $('#userInfoAge').text(thisUserObject.age);
  $('#userInfoGender').text(thisUserObject.gender);
  $('#userInfoLocation').text(thisUserObject.location);
};

// Add User
function addUser(event) {
  event.preventDefault();

  // Super basic validation - increase errorCount variable if any fields are blank
  var errorCount = 0;
  $('#addUser input').each(function(index, val) {
    if($(this).val() === '') { errorCount++; }
  });

  // Check and make sure errorCount's still at zero
  if(errorCount === 0) {

    // If it is, compile all user info into one object
    var newUser = {
      'username': $('#addUser fieldset input#inputUserName').val(),
      'email': $('#addUser fieldset input#inputUserEmail').val(),
      'fullname': $('#addUser fieldset input#inputUserFullname').val(),
      'age': $('#addUser fieldset input#inputUserAge').val(),
      'location': $('#addUser fieldset input#inputUserLocation').val(),
      'gender': $('#addUser fieldset input#inputUserGender').val()
    }

    // Use AJAX to post the object to our adduser service
    $.ajax({
      type: 'POST',
      data: newUser,
      url: '/adduser',
      dataType: 'JSON'
    }).done(function( response ) {

      // Check for successful (blank) response
      if (response.msg === '') {

        // Clear the form inputs
        $('#addUser fieldset input').val('');

        // Update the table
        populateTable();

      }
      else {

        // If something goes wrong, alert the error message that our service returned
        alert('Error: ' + response.msg);

      }
    });
  }
  else {
    // If errorCount is more than 0, error out
    alert('Please fill in all fields');
    return false;
  }
};

// Delete User
function deleteUser(event) {

  event.preventDefault();

  // Pop up a confirmation dialog
  var confirmation = confirm('Are you sure you want to delete this user?');

  // Check and make sure the user confirmed
  if (confirmation === true) {

    // If they did, do our delete
    $.ajax({
      type: 'DELETE',
      url: '/deleteuser/' + $(this).attr('rel')
    }).done(function( response ) {

      // Check for a successful (blank) response
      if (response.msg === '') {
      }
      else {
        alert('Error: ' + response.msg);
      }

      // Update the table
      populateTable();

    });

  }
  else {

    // If they said no to the confirm, do nothing
    return false;

  }

};<commit_msg>Added a proper closing table row to the populateTable function<commit_after>// Userlist data array for filling in info box
var userListData = [];

// DOM Ready =============================================================
$(document).ready(function() {

  // Populate the user table on initial page load
  populateTable();

  // Username link click
  $('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);

  // Add User button click
  $('#btnAddUser').on('click', addUser);

  // Delete User link click
  $('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);

});

// Functions =============================================================

// Fill table with data
function populateTable() {

  // Empty content string
  var tableContent = '';

  // jQuery AJAX call for JSON
  $.getJSON( '/userlist', function( data ) {

    // Stick our user data array into a userlist variable in the global object
    userListData = data;

    // For each item in our JSON, add a table row and cells to the content string
    $.each(data, function(){
      tableContent += '
';
      tableContent += '' + this.username + '	';
      tableContent += '' + this.email + '	';
      tableContent += 'delete	';
      tableContent += '
';
    });

    // Inject the whole content string into our existing HTML table
    $('#userList table tbody').html(tableContent);
  });
};

// Show User Info
function showUserInfo(event) {

  // Prevent Link from Firing
  event.preventDefault();

  // Retrieve username from link rel attribute
  var thisUserName = $(this).attr('rel');

  // Get Index of object based on id value
  var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);

  // Get our User Object
  var thisUserObject = userListData[arrayPosition];

  //Populate Info Box
  $('#userInfoName').text(thisUserObject.fullname);
  $('#userInfoAge').text(thisUserObject.age);
  $('#userInfoGender').text(thisUserObject.gender);
  $('#userInfoLocation').text(thisUserObject.location);
};

// Add User
function addUser(event) {
  event.preventDefault();

  // Super basic validation - increase errorCount variable if any fields are blank
  var errorCount = 0;
  $('#addUser input').each(function(index, val) {
    if($(this).val() === '') { errorCount++; }
  });

  // Check and make sure errorCount's still at zero
  if(errorCount === 0) {

    // If it is, compile all user info into one object
    var newUser = {
      'username': $('#addUser fieldset input#inputUserName').val(),
      'email': $('#addUser fieldset input#inputUserEmail').val(),
      'fullname': $('#addUser fieldset input#inputUserFullname').val(),
      'age': $('#addUser fieldset input#inputUserAge').val(),
      'location': $('#addUser fieldset input#inputUserLocation').val(),
      'gender': $('#addUser fieldset input#inputUserGender').val()
    }

    // Use AJAX to post the object to our adduser service
    $.ajax({
      type: 'POST',
      data: newUser,
      url: '/adduser',
      dataType: 'JSON'
    }).done(function( response ) {

      // Check for successful (blank) response
      if (response.msg === '') {

        // Clear the form inputs
        $('#addUser fieldset input').val('');

        // Update the table
        populateTable();

      }
      else {

        // If something goes wrong, alert the error message that our service returned
        alert('Error: ' + response.msg);

      }
    });
  }
  else {
    // If errorCount is more than 0, error out
    alert('Please fill in all fields');
    return false;
  }
};

// Delete User
function deleteUser(event) {

  event.preventDefault();

  // Pop up a confirmation dialog
  var confirmation = confirm('Are you sure you want to delete this user?');

  // Check and make sure the user confirmed
  if (confirmation === true) {

    // If they did, do our delete
    $.ajax({
      type: 'DELETE',
      url: '/deleteuser/' + $(this).attr('rel')
    }).done(function( response ) {

      // Check for a successful (blank) response
      if (response.msg === '') {
      }
      else {
        alert('Error: ' + response.msg);
      }

      // Update the table
      populateTable();

    });

  }
  else {

    // If they said no to the confirm, do nothing
    return false;

  }

};<|endoftext|>


<commit_before><commit_msg>Javascript to run the site<commit_after>var wordList = [
    'adjective',
    'noun',
    'proper noun'
];

var textLines = [
    'Foo test {0} bar {1}',
    'bat {2}.'
];

var fieldList = [];

$(document).ready(function() {
    buildLibzForm();
});

function buildLibzForm()
{
    var tableContents = $('#formGrid > table > tbody');
    $('#response').hide();
    for (var i = 0; i < wordList.length; i++) {
	tableContents.append('
'+wordList[i]+'	<input type="text" id="word-'+i+'" />
');
	fieldList[i] = $('#word-'+i);
    }
    tableContents.append('
<input type="button" value="Submit" onClick="submitLibzForm();"/>
');
}

function submitLibzForm()
{
    $('#form').hide(500);
    var str = '';
    for (var i = 0; i < textLines.length; i++) {
	str = str.concat(textLines[i]+'
');
    }
    for (var i = 0; i < wordList.length; i++) {
	str = str.replace('{'+i+'}', ''+$('#word-'+i).val()+'');
    }
    $('#response').append('
'+str+'

Your email: <input type="text" id="email" /> <input type="button" value="Send" onClick="sendLibzResponses();" />
').show(500);
}

function sendLibzResponses()
{
    var submitUrl = '/responses';
    var responses = [];
    for (var i = 0; i < wordList.length; i++) {
	responses[i] = $('#word-'+i).val();
    }
    var submission = {
	'email' : $('#email').val(),
	'responses' : responses
    };
    $.post(submitUrl, submission, function(d,s,x) {
	location.reload();
    });
}
<|endoftext|>


<commit_before>//Lightweight JSONP fetcher - www.nonobtrusive.com
OPT_REMOTE = 'http://embed.optemo.com';
var JSONP=(function(){var a=0,c,f,b,d=this;function e(j){var i=document.createElement("script"),h=false;i.src=j;i.async=true;i.onload=i.onreadystatechange=function(){if(!h&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){h=true;i.onload=i.onreadystatechange=null;if(i&&i.parentNode){i.parentNode.removeChild(i)}}};if(!c){c=document.getElementsByTagName("head")[0]}c.appendChild(i)}function g(h,j,k){f="?";j=j||{};for(b in j){if(j.hasOwnProperty(b)){f+=encodeURIComponent(b)+"="+encodeURIComponent(j[b])+"&"}}var i="json"+(++a);d[i]=function(l){k(opt_parse_data_by_pattern(l, "<img[^>]+>", (function(mystring){return mystring.replace(/(\/images\/[^?]+)/, OPT_REMOTE + "$1");})));d[i]=null;try{delete d[i]}catch(m){}};e(h+f+"callback="+i);return i}return{get:g}}());
//Function for executing code at DOMReady
function opt_s(f){/in/.test(document.readyState)?setTimeout('opt_s('+f+')',9):f()}
//Load the correct history on reload
var opt_history = location.hash.replace(/^#/, '');
if (opt_history.length > 0)
    var opt_options = {embedding:'true',hist:opt_history};
else
    var opt_options = {embedding:'true'};
JSONP.get(OPT_REMOTE, opt_options, function(data){
    var opt_t = document.getElementById("optemo_embedder");
    var se = document.createElement("div");
    se.id = "opt_new";
    se.innerHTML = data;
    if (opt_t) {
        opt_t.appendChild(se);
    } else {
        se.setAttribute("style","display:none;");
        var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
        iebody.appendChild(se);
        opt_s(function(){
            var n = document.getElementById("opt_new");
            document.getElementById("optemo_embedder").appendChild(n);
            n.setAttribute("style","display:block;");
        });
    }
});
// Private function for the register_remote socket. Takes data, splits according to rules, does replace() according to rules.
function opt_parse_data_by_pattern(mydata, split_pattern_string, replacement_function) {
	var data_to_add, data_to_append, split_regexp = new RegExp(split_pattern_string, "gi");
    images = mydata.match(split_regexp);
    data_to_add = mydata.split(split_regexp);
    data_to_append = new Array();
    data_to_append.push(data_to_add[0]);
    for (i = 0; i < images.length; i++) {
        if (images[i].match(new RegExp("http:\/\/")))
            data_to_append.push(images[i]);
        else
            data_to_append.push(replacement_function(images[i]));
        data_to_append.push(data_to_add[i+1]);
    }
    return data_to_append.join("\n");
}<commit_msg>Forgot to add new loader as well<commit_after>//Lightweight JSONP fetcher - www.nonobtrusive.com
OPT_REMOTE = 'http://embed.optemo.com';
var JSONP=(function(){var a=0,c,f,b,d=this;function e(j){var i=document.createElement("script"),h=false;i.src=j;i.async=true;i.onload=i.onreadystatechange=function(){if(!h&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){h=true;i.onload=i.onreadystatechange=null;if(i&&i.parentNode){i.parentNode.removeChild(i)}}};if(!c){c=document.getElementsByTagName("head")[0]}c.appendChild(i)}function g(h,j,k){f="?";j=j||{};for(b in j){if(j.hasOwnProperty(b)){f+=encodeURIComponent(b)+"="+encodeURIComponent(j[b])+"&"}}var i="json"+(++a);d[i]=function(l){k(opt_parse_data_by_pattern(l, "<img[^>]+>", (function(mystring){return mystring.replace(/(\/images\/[^?]+)/, OPT_REMOTE + "$1");})));d[i]=null;try{delete d[i]}catch(m){}};e(h+f+"callback="+i);return i}return{get:g}}());
//Function for executing code at DOMReady
function opt_s(f){/in/.test(document.readyState)?setTimeout('opt_s('+f+')',9):f()}
//Load the correct history on reload
var opt_history = location.hash.replace(/^#/, '');
if (opt_history.length > 0)
    var opt_options = {embedding:'true',hist:opt_history};
else
    var opt_options = {embedding:'true'};
JSONP.get(OPT_REMOTE, opt_options, function(data){
    function checkInit(){
        if (typeof optemo_module != "undefined") {
            optemo_module.domready();
        }
    }
    var opt_t = document.getElementById("optemo_embedder");
    var se = document.createElement("div");
    se.id = "opt_new";
    se.innerHTML = data;
    if (opt_t) {
        opt_t.appendChild(se);
        checkInit();
    } else {
        se.setAttribute("style","display:none;");
        var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
        iebody.appendChild(se);
        opt_s(function(){
            var n = document.getElementById("opt_new");
            document.getElementById("optemo_embedder").appendChild(n);
            n.setAttribute("style","display:block;");
            checkInit();
        });
    }

});
// Private function for the register_remote socket. Takes data, splits according to rules, does replace() according to rules.
function opt_parse_data_by_pattern(mydata, split_pattern_string, replacement_function) {
	var data_to_add, data_to_append, split_regexp = new RegExp(split_pattern_string, "gi");
    images = mydata.match(split_regexp);
    data_to_add = mydata.split(split_regexp);
    data_to_append = new Array();
    data_to_append.push(data_to_add[0]);
    for (i = 0; i < images.length; i++) {
        if (images[i].match(new RegExp("http:\/\/")))
            data_to_append.push(images[i]);
        else
            data_to_append.push(replacement_function(images[i]));
        data_to_append.push(data_to_add[i+1]);
    }
    return data_to_append.join("\n");
}<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var events = require('events');
var minimatch = require('minimatch');
var File = require('./file');

/**
 * file-emitter
 *
 * **opt_options**
 *  - `{string} mode` The mode of operation; `stats`, `buffer`, defaults to `buffer`
 *  - `{boolean} autorun` ..., defaults to `true`
 *  - `{RegExp} pattern` Test files before emitting/reading, defaults to `false`
 *  - `{Array<string>} ignore` An array of glob patterns to ignore
 *  - `{boolean} followSymLinks` ..., defaults to `false`
 *  - `{number} maxFDs` The maximum number of open fds, defaults to `Infinity`
 *  - `{number} maxFileSize` The max size for a file to buffer, defaults to `10485760` (=10MiB)
 *
 * @param {string} folder
 * @param {?Object} opt_options
 *
 * @constructor
 */
function FileEmitter(folder, opt_options) {
  if (!(this instanceof FileEmitter)) {
    return new FileEmitter(folder, opt_options);
  }
  events.EventEmitter.call(this);
  opt_options = opt_options || {};

  this.root = path.resolve(process.cwd(), folder);
  this.mode = opt_options.mode || 'buffer';

  this.followSymLinks = opt_options.followSymLinks || false;
  this.pattern = opt_options.pattern || false;
  this.ignore = opt_options.ignore || false;
  this.maxFileSize = opt_options.maxFileSize || 10485760; // 10 MiB

  // @type {Array<string>}
  this._readdirQueue = [''];

  // @type {Array<string>}
  this._statQueue = [];

  // @type {Array<Object>}
  this._readQueue = [];

  this._hadError = false;

  this._maxFDs = opt_options.maxFDs || Infinity;
  this._numFDs = 0;

  var self = this;

  if (opt_options.autorun !== false) {
    setImmediate(function() {
      self.run();
    });
  }
}
util.inherits(FileEmitter, events.EventEmitter);
module.exports = FileEmitter;

FileEmitter.prototype.isIgnored = function(file) {
  var i;

  if (this.ignore) {
    file = file.substr(1); // cut off leading slash

    for (i = 0; i < this.ignore.length; ++i) {
      if (minimatch(file, this.ignore[i])) {
        return true;
      }
    }
  }

  return false;
};

/**
 * @param {string} action
 * @param {string|Object} item
 * @param {?Error=} opt_err
 */
FileEmitter.prototype._return = function(action, item, opt_err) {
  var queue;

  --this._numFDs;

  switch (action) {
    case 'readdir':
      queue = this._readdirQueue;
      break;
    case 'stat':
      queue = this._statQueue;
      break;
    case 'read':
      queue = this._readQueue;
      break;
  }

  if (opt_err) {

    // maximum number of file descriptors exceeded, see `ulimit -n`
    if (opt_err.code === 'EMFILE') {
      queue.unshift(item); // re-add item

      if (this._maxFDs > this._numFDs) {
        this._maxFDs = this._numFDs;
      } else {
        this._maxFDs = Math.max(--this._maxFDs, 1); // ensure > 0
      }

    } else {
      this._hadError = true;
      this.emit('error', opt_err, item);
    }
  }

  this.run();
};

/**
 * @param {string} directory
 * @return {void}
 */
FileEmitter.prototype._readdir = function(directory) {
  var self = this;
  var absolutePath = this.root + directory;

  fs.readdir(absolutePath, function(err, files) {
    if (err) {
      return self._return('readdir', directory, err);
    }
    var i, file;

    for (i = 0; i < files.length; ++i) {
      file = directory + '/' + files[i];

      if (!self.isIgnored(file)) {
        self._statQueue.push(file);
      }
    }

    self._return('readdir', directory);
  });
};

/**
 * @param {string} file The
 * @return {void}
 */
FileEmitter.prototype._stat = function(file) {
  var self = this;
  var absolutePath = this.root + file;
  var obj;

  fs.lstat(absolutePath, function(err, stats) {
    if (err) {
      return self._return('stat', file, err);
    }

    if (stats.isSymbolicLink() && !self.followSymLinks) {
      // TODO: maybe emit an event that we ignored a symlink
      return self._return('stat', file);
    }

    if (stats.isDirectory()) {
      self._readdirQueue.push(file);

    } else if (stats.isFile() && (!self.pattern || self.pattern.test(file))) {
      obj = new File(self, file, stats);

      if (self.mode === 'buffer' && stats.size <= self.maxFileSize) {
        self._readQueue.push(obj);
      } else {
        self.emit('file', obj);
      }
    }

    self._return('stat', file);
  });
};

/**
 * @param {Object} item
 * @return {void}
 */
FileEmitter.prototype._read = function(item) {
  var self = this;
  var absolutePath = this.root + item.name;

  fs.readFile(absolutePath, function(err, data) {
    if (err) {
      return self._return('read', item, err);
    }
    item.buffer = data;

    self.emit('file', item);

    self._return('read', item);
  });
};

FileEmitter.prototype.run = function() {
  var i, limit;
  var x = 0;

  limit = Math.min(this._maxFDs - this._numFDs, this._readdirQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._readdir(this._readdirQueue.shift());
    }
    x += limit;
  }

  limit = Math.min(this._maxFDs - this._numFDs, this._statQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._stat(this._statQueue.shift());
    }
    x += limit;
  }

  limit = Math.min(this._maxFDs - this._numFDs, this._readQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._read(this._readQueue.shift());
    }
    x += limit;
  }

  if (x + this._numFDs === 0) {
    this.emit('end', this._hadError);
  }
};
<commit_msg>win: fix path seperator<commit_after>'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var events = require('events');
var minimatch = require('minimatch');
var File = require('./file');

/**
 * file-emitter
 *
 * **opt_options**
 *  - `{string} mode` The mode of operation; `stats`, `buffer`, defaults to `buffer`
 *  - `{boolean} autorun` ..., defaults to `true`
 *  - `{RegExp} pattern` Test files before emitting/reading, defaults to `false`
 *  - `{Array<string>} ignore` An array of glob patterns to ignore
 *  - `{boolean} followSymLinks` ..., defaults to `false`
 *  - `{number} maxFDs` The maximum number of open fds, defaults to `Infinity`
 *  - `{number} maxFileSize` The max size for a file to buffer, defaults to `10485760` (=10MiB)
 *
 * @param {string} folder
 * @param {?Object} opt_options
 *
 * @constructor
 */
function FileEmitter(folder, opt_options) {
  if (!(this instanceof FileEmitter)) {
    return new FileEmitter(folder, opt_options);
  }
  events.EventEmitter.call(this);
  opt_options = opt_options || {};

  this.root = path.resolve(process.cwd(), folder);
  this.mode = opt_options.mode || 'buffer';

  this.followSymLinks = opt_options.followSymLinks || false;
  this.pattern = opt_options.pattern || false;
  this.ignore = opt_options.ignore || false;
  this.maxFileSize = opt_options.maxFileSize || 10485760; // 10 MiB

  // @type {Array<string>}
  this._readdirQueue = [''];

  // @type {Array<string>}
  this._statQueue = [];

  // @type {Array<Object>}
  this._readQueue = [];

  this._hadError = false;

  this._maxFDs = opt_options.maxFDs || Infinity;
  this._numFDs = 0;

  var self = this;

  if (opt_options.autorun !== false) {
    setImmediate(function() {
      self.run();
    });
  }
}
util.inherits(FileEmitter, events.EventEmitter);
module.exports = FileEmitter;

FileEmitter.prototype.isIgnored = function(file) {
  var i;

  if (this.ignore) {
    file = file.substr(1); // cut off leading slash

    for (i = 0; i < this.ignore.length; ++i) {
      if (minimatch(file, this.ignore[i])) {
        return true;
      }
    }
  }

  return false;
};

/**
 * @param {string} action
 * @param {string|Object} item
 * @param {?Error=} opt_err
 */
FileEmitter.prototype._return = function(action, item, opt_err) {
  var queue;

  --this._numFDs;

  switch (action) {
    case 'readdir':
      queue = this._readdirQueue;
      break;
    case 'stat':
      queue = this._statQueue;
      break;
    case 'read':
      queue = this._readQueue;
      break;
  }

  if (opt_err) {

    // maximum number of file descriptors exceeded, see `ulimit -n`
    if (opt_err.code === 'EMFILE') {
      queue.unshift(item); // re-add item

      if (this._maxFDs > this._numFDs) {
        this._maxFDs = this._numFDs;
      } else {
        this._maxFDs = Math.max(--this._maxFDs, 1); // ensure > 0
      }

    } else {
      this._hadError = true;
      this.emit('error', opt_err, item);
    }
  }

  this.run();
};

/**
 * @param {string} directory
 * @return {void}
 */
FileEmitter.prototype._readdir = function(directory) {
  var self = this;
  var absolutePath = this.root + directory;

  fs.readdir(absolutePath, function(err, files) {
    if (err) {
      return self._return('readdir', directory, err);
    }
    var i, file;

    for (i = 0; i < files.length; ++i) {
      file = directory + path.sep + files[i];

      if (!self.isIgnored(file)) {
        self._statQueue.push(file);
      }
    }

    self._return('readdir', directory);
  });
};

/**
 * @param {string} file The
 * @return {void}
 */
FileEmitter.prototype._stat = function(file) {
  var self = this;
  var absolutePath = this.root + file;
  var obj;

  fs.lstat(absolutePath, function(err, stats) {
    if (err) {
      return self._return('stat', file, err);
    }

    if (stats.isSymbolicLink() && !self.followSymLinks) {
      // TODO: maybe emit an event that we ignored a symlink
      return self._return('stat', file);
    }

    if (stats.isDirectory()) {
      self._readdirQueue.push(file);

    } else if (stats.isFile() && (!self.pattern || self.pattern.test(file))) {
      obj = new File(self, file, stats);

      if (self.mode === 'buffer' && stats.size <= self.maxFileSize) {
        self._readQueue.push(obj);
      } else {
        self.emit('file', obj);
      }
    }

    self._return('stat', file);
  });
};

/**
 * @param {Object} item
 * @return {void}
 */
FileEmitter.prototype._read = function(item) {
  var self = this;
  var absolutePath = this.root + item.name;

  fs.readFile(absolutePath, function(err, data) {
    if (err) {
      return self._return('read', item, err);
    }
    item.buffer = data;

    self.emit('file', item);

    self._return('read', item);
  });
};

FileEmitter.prototype.run = function() {
  var i, limit;
  var x = 0;

  limit = Math.min(this._maxFDs - this._numFDs, this._readdirQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._readdir(this._readdirQueue.shift());
    }
    x += limit;
  }

  limit = Math.min(this._maxFDs - this._numFDs, this._statQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._stat(this._statQueue.shift());
    }
    x += limit;
  }

  limit = Math.min(this._maxFDs - this._numFDs, this._readQueue.length);

  if (limit > 0) {
    for (i = 0; i < limit; ++i) {
      ++this._numFDs;
      this._read(this._readQueue.shift());
    }
    x += limit;
  }

  if (x + this._numFDs === 0) {
    this.emit('end', this._hadError);
  }
};
<|endoftext|>


<commit_before>/*
* @Author: zoujie.wzj
* @Date:   2016-01-23 18:25:37
* @Last Modified by:   zoujie.wzj
* @Last Modified time: 2016-10-13 15:18:00
*/

'use strict'

const path = require('path')
const utils = require('./utils')

function matchName (text, name) {
  if (!name) {
    return true
  }

  return text.match(name)
}

const finders = {
  darwin (cond) {
    return new Promise((resolve, reject) => {
      let cmd
      if ('pid' in cond) {
        cmd = `ps -p ${cond.pid} -ww -o pid,ppid,uid,gid,args`
      } else {
        cmd = `ps ax -ww -o pid,ppid,uid,gid,args`
      }

      utils.exec(cmd, function (err, stdout, stderr) {
        if (err) {
          if ('pid' in cond) {
            // when pid not exists, call `ps -p ...` will cause error, we have to
            // ignore the error and resolve with empty array
            resolve([])
          } else {
            reject(err)
          }
        } else {
          err = stderr.toString().trim()
          if (err) {
            reject(err)
            return
          }

          let data = utils.stripLine(stdout.toString(), 1)
          let columns = utils.extractColumns(data, [0, 1, 2, 3, 4], 5).filter(column => {
            if (column[0]) {
              return matchName(column[4], cond.name)
            } else {
              return false
            }
          })

          let list = columns.map(column => {
            let cmd = String(column[4]).split(' ', 1)[0]

            return {
              pid: column[0],
              ppid: column[1],
              uid: column[2],
              gid: column[3],
              name: path.basename(cmd),
              cmd: column[4]
            }
          })

          resolve(list)
        }
      })
    })
  },
  linux: 'darwin',
  sunos: 'darwin',
  freebsd: 'darwin',
  win32 (cond) {
    return new Promise((resolve, reject) => {
      const cmd = 'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline'
      const lines = []

      const proc = utils.spawn('cmd', ['/c', cmd], { detached: false, windowsHide: true })
      proc.stdout.on('data', data => {
        lines.push(data.toString())
      })
      proc.on('close', code => {
        if (code !== 0) {
          return reject('Command \'' + cmd + '\' terminated with code: ' + code)
        }
        let list = utils.parseTable(lines.join('\n'))
          .filter(row => {
            if ('pid' in cond) {
              return row.ProcessId === String(cond.pid)
            } else {
              return matchName(row.CommandLine, cond.name)
            }
          })
          .map(row => ({
            pid: row.ProcessId,
            ppid: row.ParentProcessId,
            uid: null,
            gid: null,
            name: row.Name,
            cmd: row.CommandLine
          }))
        resolve(list)
      })
    })
  }
}

function findProcess (cond) {
  let platform = process.platform

  return new Promise((resolve, reject) => {
    if (!(platform in finders)) {
      reject(new Error(`platform ${platform} is unsupported`))
    }

    let find = finders[platform]
    if (typeof find === 'string') {
      find = finders[find]
    }

    find(cond).then(resolve, reject)
  })
}

module.exports = findProcess
<commit_msg>fix bug on unsupported platform<commit_after>/*
* @Author: zoujie.wzj
* @Date:   2016-01-23 18:25:37
* @Last Modified by:   zoujie.wzj
* @Last Modified time: 2016-10-13 15:18:00
*/

'use strict'

const path = require('path')
const utils = require('./utils')

function matchName (text, name) {
  if (!name) {
    return true
  }

  return text.match(name)
}

const finders = {
  darwin (cond) {
    return new Promise((resolve, reject) => {
      let cmd
      if ('pid' in cond) {
        cmd = `ps -p ${cond.pid} -ww -o pid,ppid,uid,gid,args`
      } else {
        cmd = `ps ax -ww -o pid,ppid,uid,gid,args`
      }

      utils.exec(cmd, function (err, stdout, stderr) {
        if (err) {
          if ('pid' in cond) {
            // when pid not exists, call `ps -p ...` will cause error, we have to
            // ignore the error and resolve with empty array
            resolve([])
          } else {
            reject(err)
          }
        } else {
          err = stderr.toString().trim()
          if (err) {
            reject(err)
            return
          }

          let data = utils.stripLine(stdout.toString(), 1)
          let columns = utils.extractColumns(data, [0, 1, 2, 3, 4], 5).filter(column => {
            if (column[0]) {
              return matchName(column[4], cond.name)
            } else {
              return false
            }
          })

          let list = columns.map(column => {
            let cmd = String(column[4]).split(' ', 1)[0]

            return {
              pid: column[0],
              ppid: column[1],
              uid: column[2],
              gid: column[3],
              name: path.basename(cmd),
              cmd: column[4]
            }
          })

          resolve(list)
        }
      })
    })
  },
  linux: 'darwin',
  sunos: 'darwin',
  freebsd: 'darwin',
  win32 (cond) {
    return new Promise((resolve, reject) => {
      const cmd = 'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline'
      const lines = []

      const proc = utils.spawn('cmd', ['/c', cmd], { detached: false, windowsHide: true })
      proc.stdout.on('data', data => {
        lines.push(data.toString())
      })
      proc.on('close', code => {
        if (code !== 0) {
          return reject('Command \'' + cmd + '\' terminated with code: ' + code)
        }
        let list = utils.parseTable(lines.join('\n'))
          .filter(row => {
            if ('pid' in cond) {
              return row.ProcessId === String(cond.pid)
            } else {
              return matchName(row.CommandLine, cond.name)
            }
          })
          .map(row => ({
            pid: row.ProcessId,
            ppid: row.ParentProcessId,
            uid: null,
            gid: null,
            name: row.Name,
            cmd: row.CommandLine
          }))
        resolve(list)
      })
    })
  }
}

function findProcess (cond) {
  let platform = process.platform

  return new Promise((resolve, reject) => {
    if (!(platform in finders)) {
      return reject(new Error(`platform ${platform} is unsupported`))
    }

    let find = finders[platform]
    if (typeof find === 'string') {
      find = finders[find]
    }

    find(cond).then(resolve, reject)
  })
}

module.exports = findProcess
<|endoftext|>


<commit_before>define(['js/core/Component', "sprd/error/ProductCreationError"],
    function (Component, ProductCreationError) {
        return Component.inherit("sprd.manager.ProductCreationErrorManager", {
            defaults: {
                errorMessage: null,
                copyrightErrorMessage: null
            },

            getErrorMessage: function(message) {

                var ret = message;
                try {
                    var payload = JSON.parse(message);
                    message = payload.message;
                } catch (e) {
                }

                return ret;
            },

            getErrorMessages: function (err) {
                var customerErrorMessage,
                    detailedErrorMessage,
                    copyrightWord;

                if (err instanceof ProductCreationError) {
                    if (err.baseError && err.baseError.xhr) {
                        detailedErrorMessage = this.getErrorMessage(err.baseError.xhr.responses.text);
                    }
                }

                if (err.xhr) {
                    if (err.xhr.status === 400) {
                        detailedErrorMessage = this.getErrorMessage(err.xhr.responses.text);
                    } else {
                        // 503 and 502 errors are handled somewhere else
                        return;
                    }
                }

                if (detailedErrorMessage && detailedErrorMessage.indexOf("blacklisted terms") !== -1) {
                    var matches = /.*'(.+)'.*\[(.+)\]/.exec(detailedErrorMessage);
                    // copy right error
                    copyrightWord = matches[2];
                    customerErrorMessage = this.$.copyrightErrorMessage.replace("%0", matches[1]).replace("%1", matches[2]);
                } else {
                    customerErrorMessage = this.$.errorMessage;
                }

                return {
                    customerErrorMessage: customerErrorMessage,
                    detailedErrorMessage: detailedErrorMessage,
                    copyrightWord: copyrightWord
                };
            }
        });
    });<commit_msg>DEV-63722 - No error message is shown if product is created with copyright word<commit_after>define(['js/core/Component', "sprd/error/ProductCreationError"],
    function (Component, ProductCreationError) {
        return Component.inherit("sprd.manager.ProductCreationErrorManager", {
            defaults: {
                errorMessage: null,
                copyrightErrorMessage: null
            },

            getErrorMessage: function(message) {

                var ret = message;
                try {
                    var payload = JSON.parse(message);
                    ret = payload.message;
                } catch (e) {
                }

                return ret;
            },

            getErrorMessages: function (err) {
                var customerErrorMessage,
                    detailedErrorMessage,
                    copyrightWord;

                if (err instanceof ProductCreationError) {
                    if (err.baseError && err.baseError.xhr) {
                        detailedErrorMessage = this.getErrorMessage(err.baseError.xhr.responses.text);
                    }
                }

                if (err.xhr) {
                    if (err.xhr.status === 400) {
                        detailedErrorMessage = this.getErrorMessage(err.xhr.responses.text);
                    } else {
                        // 503 and 502 errors are handled somewhere else
                        return;
                    }
                }

                if (detailedErrorMessage && detailedErrorMessage.indexOf("blacklisted terms") !== -1) {
                    var matches = /.*'(.+)'.*\[(.+)\]/.exec(detailedErrorMessage);
                    // copy right error
                    copyrightWord = matches[2];
                    customerErrorMessage = this.$.copyrightErrorMessage.replace("%0", matches[1]).replace("%1", matches[2]);
                } else {
                    customerErrorMessage = this.$.errorMessage;
                }

                return {
                    customerErrorMessage: customerErrorMessage,
                    detailedErrorMessage: detailedErrorMessage,
                    copyrightWord: copyrightWord
                };
            }
        });
    });<|endoftext|>