<commit_before>var express = require('express');
var router = express.Router();

var mongodb = require('mongodb');
var dbClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectId;
var database = 'trand';
var dbUrl = 'mongodb://localhost/' + database;

var request = require('request');
var _ = require('underscore');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

router.use(bodyParser.json());
router.use(cookieParser());

router.get('/', function (req, res) {
  var dbPromise = new Promise(function(resolve, reject) {
    dbClient.connect(dbUrl, function (err, db) {
      var lists = db.collection('lists');
      lists.find({type: 'body-list'}).toArray(function (err, results) {
        var bodylist = results[0].body;
        db.close();
        resolve(bodylist);
      })
    });
  });
  dbPromise.then(function (bodylist) {
    dbClient.connect(dbUrl, function (err, db) {
      if (!err) {
        var collections = db.collection('collections');
        collections.find({email: req.currentUser.email}).toArray(function (err, results) {
          if (results.length>0) {
            var resPromise = new Promise(function(resolve, reject) {
              function findMatch(array, arrayCompare) {
                var found = [];
                _.each(array, function (item) {
                  for (var i = 0; i < arrayCompare.length; i++) {
                    if (item.item.categories[0].id === arrayCompare[i]) {
                      found.push(item);
                      break;
                    }
                  }
                })
                console.log(found.length);
                return found;
              }
              if (req.query.sort === 'date') {
                results = _.sortBy(results, 'date').reverse();
                resolve(results);
              }
              if (req.query.sort === 'cat') {
                results = _.sortBy(results, 'category').reverse();
                resolve(results);
              }
              if (req.query.sort === 'top') {
                results = findMatch(results, bodylist.top);
                resolve(results);
              }
              if (req.query.sort === 'bot') {
                results = findMatch(results, bodylist.bot);
                resolve(results);
              }
              if (req.query.sort === 'accessories') {
                results = findMatch(results, bodylist.ace);
                resolve(results);
              }
              if (req.query.sort === 'foot') {
                results = findMatch(results, bodylist.sho);
                resolve(results);
              }
              if (req.query.sort === 'fullbody') {
                results = findMatch(results, bodylist.ful);
                resolve(results);
              }
              if (req.query.sort === 'bags') {
                results = findMatch(results, bodylist.bag);
                resolve(results);
              }
              if (req.query.sort === 'eye') {
                results = findMatch(results, bodylist.eye);
                resolve(results);
              }
              if (req.query.sort === 'neck') {
                results = findMatch(results, bodylist.nec);
                resolve(results);
              }
              if (req.query.sort === 'head') {
                results = findMatch(results, bodylist.hed);
                resolve(results);
              }
            });
            resPromise.then(function (body) {
              res.json(body);
              db.close();
            })
          } else {
            res.sendStatus(404);
            db.close();
          }
        })
      } else {
        res.sendStatus(404);
        db.close();
      }
    });
  })
})

router.get('/item/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    res.json(response);
  })
})

router.put('/update/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    dbClient.connect(dbUrl, function (err, db) {
      if (!err) {
        var collections = db.collection('collections');
        collections.update({email: req.currentUser.email, item: {id: response.id }}, {
          $set: {
            item: response,
            date: new Date(),
          }
        }, {
            upsert: true,
          }, function (err, results) {
          res.sendStatus(200);
          db.close();
        })
      } else {
        res.sendStatus(404);
        db.close();
      }
    })
  })
})

router.put('/update-withcat/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    var p2 = new Promise(function(resolve, reject) {
      request('http://api.shopstyle.com/api/v2/categories?pid=uid41-33788821-64' + '&cat=' + response.categories[0].id, function (err, res, body) {
        resolve(body);
      })
    });
    p2.then(function (body) {
      var categoriesJSON = JSON.parse(body);
      var category = categoriesJSON.metadata.root.parentId;
      dbClient.connect(dbUrl, function (err, db) {
        if (!err) {
          var collections = db.collection('collections');
          collections.update({email: req.currentUser.email, item: {id: response.id }}, {
            $set: {
              item: response,
              date: new Date(),
              category: category,
              body: 'body',
            }
          }, {
              upsert: true,
            }, function (err, results) {
            res.sendStatus(200);
            db.close();
          })
        } else {
          res.sendStatus(404);
          db.close();
        }
      })
    })
  })
})

router.put('/remove/:id', function (req, res) {
  dbClient.connect(dbUrl, function (err, db) {
    if (!err) {
      var collections = db.collection('collections');
      collections.remove({email: req.currentUser.email, item: {id: parseInt(req.params.id) }}, function (err, result) {
        res.sendStatus(200);
        db.close;
      });
    } else {
      res.sendStatus(404);
      db.close;
    }
  })
});

router.get('/update-lists', function (req, res) {
  var promise = new Promise(function(resolve, reject) {
    var p1 = new Promise(function(resolve, reject) {
      request('http://api.shopstyle.com/api/v2/categories?pid=uid41-33788821-64', function (err, res, body) {
        resolve(body);
      })
    });
    p1.then(function (body) {
      var top = [];
      var bot = [];
      var sho = [];
      var ful = [];
      var nec = [];
      var hed = [];
      var eye = [];
      var ace = [];
      var bag = [];

      var response = JSON.parse(body);
      var list = [];
      for (var i = 0; i < response.categories.length; i++) {
        list.push(response.categories[i].id);
      }
      _.each(list, function (item) {
        function push(item, category, kind) {
          if (item.indexOf(kind)>-1) {category.push(item)};
        }
        push(item, top, 'tops');
        push(item, top, 'womens-clothes');
        push(item, top, 'mens-clothes');
        push(item, top, 'outerwear');
        push(item, top, 'sweaters');
        push(item, top, 'sweatshirts');
        push(item, top, 'jackets');

        push(item, bot, 'pants');
        push(item, bot, 'jeans');
        push(item, bot, 'skirts');

        push(item, sho, 'shoes');
        push(item, sho, 'boots');
        push(item, sho, 'flats');
        push(item, sho, 'pumps');
        push(item, sho, 'wedges');
        push(item, sho, 'sandals');
        push(item, sho, 'sneakers');

        push(item, ful, 'intimates');
        push(item, ful, 'suits');
        push(item, ful, 'dresses');
        push(item, ful, 'swimshirts');
        push(item, ful, 'bridal');

        push(item, ace, 'beauty');
        push(item, ace, 'mens-accessories');
        push(item, ace, 'womens-accessories');
        push(item, ace, 'jewelry');
        push(item, ace, 'jewelery');
        push(item, ace, 'diamond');
        push(item, ace, 'makeup');
        push(item, ace, 'wallets');
        push(item, ace, 'necklaces');
        push(item, ace, 'rings');
        push(item, ace, 'ring');
        push(item, ace, 'watches');

        push(item, bag, 'bags');
        push(item, bag, 'satchels');

        push(item, hed, 'caps');
        push(item, hed, 'hats');

        push(item, nec, 'necklaces');
        push(item, nec, 'scarves');

        push(item, eye, 'sunglasses');

      });
      var body = {
        top: _.uniq(top.sort()),
        bot: _.uniq(bot.sort()),
        sho: _.uniq(sho.sort()),
        ful: _.uniq(ful.sort()),
        bag: _.uniq(bag.sort()),
        ace: _.uniq(ace.sort()),
        hed: _.uniq(hed.sort()),
        nec: _.uniq(nec.sort()),
        eye: _.uniq(eye.sort()),
      }
      resolve(body);
    })
  });
  promise.then(function (body) {
    dbClient.connect(dbUrl, function (err, db) {
      var allLists = db.collection('lists');
      if (!err) {
        allLists.remove({}, function () {
          allLists.insert({type: 'body-list', body: body}, function (err, result) {
            db.close();
            res.sendStatus(200);
          })
        });
      } else {
        res.sendStatus(404);
      }
    })
  })
})

module.exports = router;
<commit_msg>Fix the backend remove from collections.#1<commit_after>var express = require('express');
var router = express.Router();

var mongodb = require('mongodb');
var dbClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectId;
var database = 'trand';
var dbUrl = 'mongodb://localhost/' + database;

var request = require('request');
var _ = require('underscore');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

router.use(bodyParser.json());
router.use(cookieParser());

router.get('/', function (req, res) {
  var dbPromise = new Promise(function(resolve, reject) {
    dbClient.connect(dbUrl, function (err, db) {
      var lists = db.collection('lists');
      lists.find({type: 'body-list'}).toArray(function (err, results) {
        var bodylist = results[0].body;
        db.close();
        resolve(bodylist);
      })
    });
  });
  dbPromise.then(function (bodylist) {
    dbClient.connect(dbUrl, function (err, db) {
      if (!err) {
        var collections = db.collection('collections');
        collections.find({email: req.currentUser.email}).toArray(function (err, results) {
          if (results.length>0) {
            var resPromise = new Promise(function(resolve, reject) {
              function findMatch(array, arrayCompare) {
                var found = [];
                _.each(array, function (item) {
                  for (var i = 0; i < arrayCompare.length; i++) {
                    if (item.item.categories[0].id === arrayCompare[i]) {
                      found.push(item);
                      break;
                    }
                  }
                })
                console.log(found.length);
                return found;
              }
              if (req.query.sort === 'date') {
                results = _.sortBy(results, 'date').reverse();
                resolve(results);
              }
              if (req.query.sort === 'cat') {
                results = _.sortBy(results, 'category').reverse();
                resolve(results);
              }
              if (req.query.sort === 'top') {
                results = findMatch(results, bodylist.top);
                resolve(results);
              }
              if (req.query.sort === 'bot') {
                results = findMatch(results, bodylist.bot);
                resolve(results);
              }
              if (req.query.sort === 'accessories') {
                results = findMatch(results, bodylist.ace);
                resolve(results);
              }
              if (req.query.sort === 'foot') {
                results = findMatch(results, bodylist.sho);
                resolve(results);
              }
              if (req.query.sort === 'fullbody') {
                results = findMatch(results, bodylist.ful);
                resolve(results);
              }
              if (req.query.sort === 'bags') {
                results = findMatch(results, bodylist.bag);
                resolve(results);
              }
              if (req.query.sort === 'eye') {
                results = findMatch(results, bodylist.eye);
                resolve(results);
              }
              if (req.query.sort === 'neck') {
                results = findMatch(results, bodylist.nec);
                resolve(results);
              }
              if (req.query.sort === 'head') {
                results = findMatch(results, bodylist.hed);
                resolve(results);
              }
            });
            resPromise.then(function (body) {
              res.json(body);
              db.close();
            })
          } else {
            res.sendStatus(404);
            db.close();
          }
        })
      } else {
        res.sendStatus(404);
        db.close();
      }
    });
  })
})

router.get('/item/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    res.json(response);
  })
})

router.put('/update/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    dbClient.connect(dbUrl, function (err, db) {
      if (!err) {
        var collections = db.collection('collections');
        collections.update({email: req.currentUser.email, item: {id: response.id }}, {
          $set: {
            item: response,
            date: new Date(),
          }
        }, {
            upsert: true,
          }, function (err, results) {
          res.sendStatus(200);
          db.close();
        })
      } else {
        res.sendStatus(404);
        db.close();
      }
    })
  })
})

router.put('/update-withcat/:id', function (req, res) {
  var p1 = new Promise(function(resolve, reject) {
    request('http://api.shopstyle.com/api/v2/products/' + parseInt(req.params.id) + '?pid=uid41-33788821-64', function (err, res, body) {
      resolve(body);
    })
  });
  p1.then(function (body) {
    var response = JSON.parse(body);
    var p2 = new Promise(function(resolve, reject) {
      request('http://api.shopstyle.com/api/v2/categories?pid=uid41-33788821-64' + '&cat=' + response.categories[0].id, function (err, res, body) {
        resolve(body);
      })
    });
    p2.then(function (body) {
      var categoriesJSON = JSON.parse(body);
      var category = categoriesJSON.metadata.root.parentId;
      dbClient.connect(dbUrl, function (err, db) {
        if (!err) {
          var collections = db.collection('collections');
          collections.update({email: req.currentUser.email, item: {id: response.id }}, {
            $set: {
              item: response,
              date: new Date(),
              category: category,
              body: 'body',
            }
          }, {
              upsert: true,
            }, function (err, results) {
            res.sendStatus(200);
            db.close();
          })
        } else {
          res.sendStatus(404);
          db.close();
        }
      })
    })
  })
})

router.put('/remove/:id', function (req, res) {
  dbClient.connect(dbUrl, function (err, db) {
    if (!err) {
      var collections = db.collection('collections');
      collections.find({email: req.currentUser.email}).toArray(function (err, results) {
        var p1 = new Promise(function(resolve, reject) {
          for (var i = 0; i < results.length; i++) {
            if (results[i].item.id === parseInt(req.params.id)) {
              var matched = results[i];
            }
          }
          resolve(matched);
        });
        p1.then(function (matched) {
          collections.remove(matched, function (err, results) {
            res.sendStatus(200);
            db.close();
          })
        })
      });
    } else {
      res.sendStatus(404);
      db.close;
    }
  })
});

router.get('/update-lists', function (req, res) {
  var promise = new Promise(function(resolve, reject) {
    var p1 = new Promise(function(resolve, reject) {
      request('http://api.shopstyle.com/api/v2/categories?pid=uid41-33788821-64', function (err, res, body) {
        resolve(body);
      })
    });
    p1.then(function (body) {
      var top = [];
      var bot = [];
      var sho = [];
      var ful = [];
      var nec = [];
      var hed = [];
      var eye = [];
      var ace = [];
      var bag = [];

      var response = JSON.parse(body);
      var list = [];
      for (var i = 0; i < response.categories.length; i++) {
        list.push(response.categories[i].id);
      }
      _.each(list, function (item) {
        function push(item, category, kind) {
          if (item.indexOf(kind)>-1) {category.push(item)};
        }
        push(item, top, 'tops');
        push(item, top, 'womens-clothes');
        push(item, top, 'mens-clothes');
        push(item, top, 'outerwear');
        push(item, top, 'sweaters');
        push(item, top, 'sweatshirts');
        push(item, top, 'jackets');

        push(item, bot, 'pants');
        push(item, bot, 'jeans');
        push(item, bot, 'skirts');

        push(item, sho, 'shoes');
        push(item, sho, 'boots');
        push(item, sho, 'flats');
        push(item, sho, 'pumps');
        push(item, sho, 'wedges');
        push(item, sho, 'sandals');
        push(item, sho, 'sneakers');

        push(item, ful, 'intimates');
        push(item, ful, 'suits');
        push(item, ful, 'dresses');
        push(item, ful, 'swimshirts');
        push(item, ful, 'bridal');

        push(item, ace, 'beauty');
        push(item, ace, 'mens-accessories');
        push(item, ace, 'womens-accessories');
        push(item, ace, 'jewelry');
        push(item, ace, 'jewelery');
        push(item, ace, 'diamond');
        push(item, ace, 'makeup');
        push(item, ace, 'wallets');
        push(item, ace, 'necklaces');
        push(item, ace, 'rings');
        push(item, ace, 'ring');
        push(item, ace, 'watches');

        push(item, bag, 'bags');
        push(item, bag, 'satchels');

        push(item, hed, 'caps');
        push(item, hed, 'hats');

        push(item, nec, 'necklaces');
        push(item, nec, 'scarves');

        push(item, eye, 'sunglasses');

      });
      var body = {
        top: _.uniq(top.sort()),
        bot: _.uniq(bot.sort()),
        sho: _.uniq(sho.sort()),
        ful: _.uniq(ful.sort()),
        bag: _.uniq(bag.sort()),
        ace: _.uniq(ace.sort()),
        hed: _.uniq(hed.sort()),
        nec: _.uniq(nec.sort()),
        eye: _.uniq(eye.sort()),
      }
      resolve(body);
    })
  });
  promise.then(function (body) {
    dbClient.connect(dbUrl, function (err, db) {
      var allLists = db.collection('lists');
      if (!err) {
        allLists.remove({}, function () {
          allLists.insert({type: 'body-list', body: body}, function (err, result) {
            db.close();
            res.sendStatus(200);
          })
        });
      } else {
        res.sendStatus(404);
      }
    })
  })
})

module.exports = router;
<|endoftext|>


<commit_before>import GitRepo from 'git-repository';
import run from './run';
import fetch from './lib/fetch';

// TODO: Update deployment URL
// For more information visit http://gitolite.com/deploy.html
const getRemote = (slot) => ({
    name: slot ? slot : 'production',
    url: 'https://git.heroku.com/social-mon.git',
    website: 'http://social-mon.herokuapp.com/'
});

/**
 * Deploy the contents of the `/build` folder to a remote
 * server via Git. Example: `npm run deploy -- production`
 */
async function deploy() {
    // By default deploy to the staging deployment slot
    const remote = getRemote(process.argv.includes('--production') ? null : 'staging');

    // Initialize a new Git repository inside the `/build` folder
    // if it doesn't exist yet
    const repo = await GitRepo.open('build', { init: true });
    await repo.setRemote(remote.name, remote.url);

    // Fetch the remote repository if it exists
    if ((await repo.hasRef(remote.url, 'master'))) {
        await repo.fetch(remote.name);
        await repo.reset(`${remote.name}/master`, { hard: true });
        await repo.clean({ force: true });
    }

    // Build the project in RELEASE mode which
    // generates optimized and minimized bundles
    process.argv.push('--release');
    await run(require('./build'));

    // Push the contents of the build folder to the remote server via Git
    await repo.add('--all .');
    await repo.commit('Update');
    await repo.push(remote.name, 'master');

    // Check if the site was successfully deployed
    const response = await fetch(remote.website);
    console.log(`${remote.website} -> ${response.statusCode}`);
}

export default deploy;
<commit_msg>Fixed url for deploy to heroku<commit_after>import GitRepo from 'git-repository';
import run from './run';
import fetch from './lib/fetch';

// TODO: Update deployment URL
// For more information visit http://gitolite.com/deploy.html
const getRemote = (slot) => ({
    name: slot ? slot : 'production',
    url: 'git@heroku.com:social-mon.git',
    website: 'http://social-mon.herokuapp.com/'
});

/**
 * Deploy the contents of the `/build` folder to a remote
 * server via Git. Example: `npm run deploy -- production`
 */
async function deploy() {
    // By default deploy to the staging deployment slot
    const remote = getRemote(process.argv.includes('--production') ? null : 'staging');

    // Initialize a new Git repository inside the `/build` folder
    // if it doesn't exist yet
    const repo = await GitRepo.open('build', { init: true });
    await repo.setRemote(remote.name, remote.url);

    // Fetch the remote repository if it exists
    if ((await repo.hasRef(remote.url, 'master'))) {
        await repo.fetch(remote.name);
        await repo.reset(`${remote.name}/master`, { hard: true });
        await repo.clean({ force: true });
    }

    // Build the project in RELEASE mode which
    // generates optimized and minimized bundles
    process.argv.push('--release');
    await run(require('./build'));

    // Push the contents of the build folder to the remote server via Git
    await repo.add('--all .');
    await repo.commit('Update');
    await repo.push(remote.name, 'master');

    // Check if the site was successfully deployed
    const response = await fetch(remote.website);
    console.log(`${remote.website} -> ${response.statusCode}`);
}

export default deploy;
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
# deploy.js - portable deployment script

This portable Node.js script minifies both your application, its
libraries & the Enyo framework it is using.  The resulting application
is suitable for production usage, either hostet on a web-server or
embedded into a PhoneGap container.

The script is intended to be run from the application's root directory
(This is unlike previous deprecated incarnations of the scripts
`deploy.sh` and `deploy.bat` that shipped within the `bootplate`
application), where it expects to find a file called `package.js`
(unless the user specifies an alternate location using the `-p` flag).

This script comes along with Enyo.  It automatically uses & embeds the
Enyo version it is shipped with, unless the user specifies another
Enyo version using the `-e enyo_dir` flag.

When you application has library dependencies (for example
`lib/mylib`), this script uses the `lib/mylib/manifest.json` (if
present) or the old-fashioned deployment scripts `lib/mylib/deploy.sh`
(on Linux & Mac OSX) or `lib/mylib/deploy.bat` (on Windows).

This script also expects to find the following files & folders in the
application root directory.  Each of them is copied verbatim in the
output production/deployment folder (the one optionally given using
the `-o` flag).

* `index.html`, the application startup page
* `icon.png`, the application icon
* `assets/`holds the static application assets, such as images,
  videos... etc.

 */

// Load dependencies

var nopt = require("nopt"),
    path = require('path'),
    fs = require('fs'),
    util = require('util'),
    shell = require('shelljs');

var stat, ppwd, lib, script, scripts = {};

// Send message to parent node process, if any
process.on('uncaughtException', function (err) {
	var errMsg = err.toString() + err.stack;
	console.error(errMsg);
	if (process.send) {
		// only available if parent process is node
		process.send({error: errMsg});
	}
	process.exit(1);
});
// receive error messages from child node processes
process.on('message', function(msg) {
	console.dir(basename, msg);
	if (msg.error && msg.error.stack) {
		console.error(basename, msg.error.stack);
	}
	if (process.send) {
		process.send(msg);
	}
});

// Parse arguments

var node = process.argv[0],
    deploy = process.argv[1],
    sourceDir = process.cwd(),
    packageJs = path.resolve(sourceDir, "package.js"),
    enyoDir = path.resolve(__dirname, '..'),
    buildDir = path.resolve(sourceDir, "build"),
    name = path.basename(sourceDir),
    outDir = path.resolve(sourceDir, 'deploy', name),
    less = true, // LESS compilation, turned on by default
    verbose = false;

function printUsage() {
	// format generated using node-optimist...
	console.log('\n' +
		    'Usage: ' + node + ' ' + deploy + ' [-c][-e enyo_dir][-b build_dir][-o out_dir][-p package_js][-s source_dir]\n' +
		    '\n' +
		    'Options:\n' +
		    '  -v  verbose operation                     [boolean]  [default: ' + verbose + ']\n' +
		    '  -b  alternate build directory             [default: "' + buildDir + '"]\n' +
		    '  -c  do not run the LESS compiler          [boolean]  [default: ' + less + ']\n' +
		    '  -e  location of the enyo framework        [default: "' + enyoDir + '"]\n' +
		    '  -o  alternate output directory            [default: "' + outDir + '"]\n' +
		    '  -p  location of the main package.js file  [default: "' + packageJs + '"]\n' +
		    '  -s  source code root directory            [default: "' + sourceDir + '"]\n' +
		    '\n');
}

var opt = nopt(/*knownOpts*/ {
	"build":	path,
	"less":		Boolean,
	"enyo":		path,
	"out":		path,
	"packagejs":	path,
	"source":	path,
	"verbose":	Boolean,
	"help":		Boolean
}, /*shortHands*/ {
	"b": "--build",
	"c": "--no-less",
	"e": "--enyo",
	"o": "--out",
	"p": "--packagejs",
	"s": "--source",
	"v": "--verbose",
	"h": "--help",
	"?": "--help"
}, process.argv /*args*/, 2 /*slice*/);

if (opt.help) {
	printUsage();
	process.exit(1);
}

// nopt has not default values system
buildDir = opt.build || buildDir;
enyoDir = opt.enyo || enyoDir;
outDir = opt.out || outDir;
packageJs = opt.packagejs ||
	(opt.source ? path.join(opt.source, 'package.js') : undefined) ||
	packageJs;
sourceDir = opt.source ||
	(opt.packagejs ? path.dirname(opt.packagejs) : undefined) ||
	sourceDir;
less = (opt.less !== false) && less;
verbose = opt.verbose;

var minifier = path.resolve(enyoDir, 'tools', 'minifier', 'minify.js');
if (verbose) console.log("Using: build_dir=" + buildDir);
if (verbose) console.log("Using: enyo_dir=" + enyoDir);
if (verbose) console.log("Using: out_dir=" + outDir);
if (verbose) console.log("Using: packagejs=" + packageJs);
if (verbose) console.log("Using: source_dir=" + sourceDir);
if (verbose) console.log("Using: less=" + less);

// utils

function run(args) {
	var command = '"' + args.join('" "') + '"';
	var report;
	if (verbose) console.log("Running: '", command, "' from '", process.cwd(), "'");
	report = shell.exec(command, { silent: true });
	if (report.code !== 0) {
		throw new Error("Fail: '" + command + "'\n" + report.output);
	}
}

// Prepare target directory

shell.rm('-rf', path.resolve(outDir));
shell.rm('-rf', path.resolve(outDir));
shell.mkdir('-p', path.join(outDir));

// Build / Minify

console.log("Minify-ing Enyo...");
process.chdir(path.resolve(enyoDir, 'minify'));
run([node, minifier,
     '-no-alias',
     '-enyo', enyoDir,
     // XXX generates $buildDir/enyo.(js|css)' so this is
     // XXX rather an 'output_prefix' than an 'out_dir'...
     '-output', path.join(buildDir, 'enyo'),
     'package.js']);

console.log("Minify-ing the application...");
process.chdir(path.dirname(packageJs));
run([node, minifier,
     '-enyo', enyoDir,
     '-output', path.join(buildDir, 'app'),
     (less ? '-less' : '-no-less'),
     'package.js']);
process.chdir(sourceDir);

// Deploy / Copy

shell.mkdir('-p', path.join(outDir, 'lib'));
shell.cp(path.join(sourceDir, 'index.html'), path.join(sourceDir, 'icon.png'), outDir);
shell.cp('-r', buildDir, outDir);

var assetsSrcDir = path.join(sourceDir, 'assets');
if(shell.test('-d', assetsSrcDir)) {
	shell.cp('-r', assetsSrcDir, outDir);
}

var libSrcDir = path.join(sourceDir, 'lib');
if(shell.test('-d', libSrcDir)) {
	shell.ls(libSrcDir).forEach(deployLib);
}

function deployLib(lib) {
	var libOutdir = path.join(outDir, 'lib', lib);
	// load & execute sub-'deploy.js'
	try {
		script = path.join(sourceDir, 'lib', lib, 'deploy.js');
		stat = fs.statSync(script);
		if (!stat.isFile())
			throw new Error("*** Not a file: '" + script + "'");
		scripts[lib] = require(script);
		scripts[lib].deploy(libOutdir);
	} catch(e) {
		// backward compatibility: run deploy.sh or deploy.bat
		try {
			script = path.join(sourceDir, 'lib', lib, 'deploy.' + (process.platform === 'win32' ? 'bat' : 'sh'));
			stat = fs.statSync(script);
			if (!stat.isFile())
				throw new Error("*** Not a file: '" + script + "'");
			run([script, libOutdir]);
		} catch(e2) {
			// no deploy.(js|bat|sh): copy everything
			shell.cp('-r', path.join(sourceDir, 'lib', lib), path.join(outDir, 'lib'));
		}
	}
}

console.log("Success:  the deployable application is available in: ", outDir);
process.exit(0);

<commit_msg>Exclude .git dir when copying entire library in deploy.js<commit_after>#!/usr/bin/env node

/**
# deploy.js - portable deployment script

This portable Node.js script minifies both your application, its
libraries & the Enyo framework it is using.  The resulting application
is suitable for production usage, either hostet on a web-server or
embedded into a PhoneGap container.

The script is intended to be run from the application's root directory
(This is unlike previous deprecated incarnations of the scripts
`deploy.sh` and `deploy.bat` that shipped within the `bootplate`
application), where it expects to find a file called `package.js`
(unless the user specifies an alternate location using the `-p` flag).

This script comes along with Enyo.  It automatically uses & embeds the
Enyo version it is shipped with, unless the user specifies another
Enyo version using the `-e enyo_dir` flag.

When you application has library dependencies (for example
`lib/mylib`), this script uses the `lib/mylib/manifest.json` (if
present) or the old-fashioned deployment scripts `lib/mylib/deploy.sh`
(on Linux & Mac OSX) or `lib/mylib/deploy.bat` (on Windows).
If neither exist, then the entire library is copied (except for .git dir).

This script also expects to find the following files & folders in the
application root directory.  Each of them is copied verbatim in the
output production/deployment folder (the one optionally given using
the `-o` flag).

* `index.html`, the application startup page
* `icon.png`, the application icon
* `assets/`holds the static application assets, such as images,
  videos... etc.

 */

// Load dependencies

var nopt = require("nopt"),
    path = require('path'),
    fs = require('fs'),
    util = require('util'),
    shell = require('shelljs');

var stat, ppwd, lib, script, scripts = {};

// Send message to parent node process, if any
process.on('uncaughtException', function (err) {
	var errMsg = err.toString() + err.stack;
	console.error(errMsg);
	if (process.send) {
		// only available if parent process is node
		process.send({error: errMsg});
	}
	process.exit(1);
});
// receive error messages from child node processes
process.on('message', function(msg) {
	console.dir(basename, msg);
	if (msg.error && msg.error.stack) {
		console.error(basename, msg.error.stack);
	}
	if (process.send) {
		process.send(msg);
	}
});

// Parse arguments

var node = process.argv[0],
    deploy = process.argv[1],
    sourceDir = process.cwd(),
    packageJs = path.resolve(sourceDir, "package.js"),
    enyoDir = path.resolve(__dirname, '..'),
    buildDir = path.resolve(sourceDir, "build"),
    name = path.basename(sourceDir),
    outDir = path.resolve(sourceDir, 'deploy', name),
    less = true, // LESS compilation, turned on by default
    verbose = false;

function printUsage() {
	// format generated using node-optimist...
	console.log('\n' +
		    'Usage: ' + node + ' ' + deploy + ' [-c][-e enyo_dir][-b build_dir][-o out_dir][-p package_js][-s source_dir]\n' +
		    '\n' +
		    'Options:\n' +
		    '  -v  verbose operation                     [boolean]  [default: ' + verbose + ']\n' +
		    '  -b  alternate build directory             [default: "' + buildDir + '"]\n' +
		    '  -c  do not run the LESS compiler          [boolean]  [default: ' + less + ']\n' +
		    '  -e  location of the enyo framework        [default: "' + enyoDir + '"]\n' +
		    '  -o  alternate output directory            [default: "' + outDir + '"]\n' +
		    '  -p  location of the main package.js file  [default: "' + packageJs + '"]\n' +
		    '  -s  source code root directory            [default: "' + sourceDir + '"]\n' +
		    '\n');
}

var opt = nopt(/*knownOpts*/ {
	"build":	path,
	"less":		Boolean,
	"enyo":		path,
	"out":		path,
	"packagejs":	path,
	"source":	path,
	"verbose":	Boolean,
	"help":		Boolean
}, /*shortHands*/ {
	"b": "--build",
	"c": "--no-less",
	"e": "--enyo",
	"o": "--out",
	"p": "--packagejs",
	"s": "--source",
	"v": "--verbose",
	"h": "--help",
	"?": "--help"
}, process.argv /*args*/, 2 /*slice*/);

if (opt.help) {
	printUsage();
	process.exit(1);
}

// nopt has not default values system
buildDir = opt.build || buildDir;
enyoDir = opt.enyo || enyoDir;
outDir = opt.out || outDir;
packageJs = opt.packagejs ||
	(opt.source ? path.join(opt.source, 'package.js') : undefined) ||
	packageJs;
sourceDir = opt.source ||
	(opt.packagejs ? path.dirname(opt.packagejs) : undefined) ||
	sourceDir;
less = (opt.less !== false) && less;
verbose = opt.verbose;

var minifier = path.resolve(enyoDir, 'tools', 'minifier', 'minify.js');
if (verbose) console.log("Using: build_dir=" + buildDir);
if (verbose) console.log("Using: enyo_dir=" + enyoDir);
if (verbose) console.log("Using: out_dir=" + outDir);
if (verbose) console.log("Using: packagejs=" + packageJs);
if (verbose) console.log("Using: source_dir=" + sourceDir);
if (verbose) console.log("Using: less=" + less);

// utils

function run(args) {
	var command = '"' + args.join('" "') + '"';
	var report;
	if (verbose) console.log("Running: '", command, "' from '", process.cwd(), "'");
	report = shell.exec(command, { silent: true });
	if (report.code !== 0) {
		throw new Error("Fail: '" + command + "'\n" + report.output);
	}
}

// Prepare target directory

shell.rm('-rf', path.resolve(outDir));
shell.rm('-rf', path.resolve(outDir));
shell.mkdir('-p', path.join(outDir));

// Build / Minify

console.log("Minify-ing Enyo...");
process.chdir(path.resolve(enyoDir, 'minify'));
run([node, minifier,
     '-no-alias',
     '-enyo', enyoDir,
     // XXX generates $buildDir/enyo.(js|css)' so this is
     // XXX rather an 'output_prefix' than an 'out_dir'...
     '-output', path.join(buildDir, 'enyo'),
     'package.js']);

console.log("Minify-ing the application...");
process.chdir(path.dirname(packageJs));
run([node, minifier,
     '-enyo', enyoDir,
     '-output', path.join(buildDir, 'app'),
     (less ? '-less' : '-no-less'),
     'package.js']);
process.chdir(sourceDir);

// Deploy / Copy

shell.mkdir('-p', path.join(outDir, 'lib'));
shell.cp(path.join(sourceDir, 'index.html'), path.join(sourceDir, 'icon.png'), outDir);
shell.cp('-r', buildDir, outDir);

var assetsSrcDir = path.join(sourceDir, 'assets');
if(shell.test('-d', assetsSrcDir)) {
	shell.cp('-r', assetsSrcDir, outDir);
}

var libSrcDir = path.join(sourceDir, 'lib');
if(shell.test('-d', libSrcDir)) {
	shell.ls(libSrcDir).forEach(deployLib);
}

function deployLib(lib) {
	var libOutdir = path.join(outDir, 'lib', lib);
	// load & execute sub-'deploy.js'
	try {
		script = path.join(sourceDir, 'lib', lib, 'deploy.js');
		stat = fs.statSync(script);
		if (!stat.isFile())
			throw new Error("*** Not a file: '" + script + "'");
		scripts[lib] = require(script);
		scripts[lib].deploy(libOutdir);
	} catch(e) {
		// backward compatibility: run deploy.sh or deploy.bat
		try {
			script = path.join(sourceDir, 'lib', lib, 'deploy.' + (process.platform === 'win32' ? 'bat' : 'sh'));
			stat = fs.statSync(script);
			if (!stat.isFile())
				throw new Error("*** Not a file: '" + script + "'");
			run([script, libOutdir]);
		} catch(e2) {
			// no deploy.(js|bat|sh): copy everything (then remove ".git" dir, if any)
			shell.cp('-r', path.join(sourceDir, 'lib', lib), path.join(outDir, 'lib'));
			shell.rm('-rf', path.join(outDir, 'lib', lib, '.git'));
		}
	}
}

console.log("Success:  the deployable application is available in: ", outDir);
process.exit(0);

<|endoftext|>


<commit_before>var _ = require('underscore');
// var current_page_url = (process.env.local)?"http://localhost:3000/":"http://listingtest-u7yhjm.rhcloud.com/";
var current_page_url = (process.env.local)?"http://localhost:3000/":"http://listing.easysublease.org/";

exports.renderJade = function( req, res, next, is_editing){
  req.db_model.findOne({_id:req.params.id}, null,{},function(err, instance){
      if (err) {
        console.log(err.message);
        return next(err);
      }
      if(!instance) {
        res.status(404).send("requested resource cannot be found").end();
        return;
      }
      res.render("my_listing.jade",{
        "result":instance.toObject(),
        "current_page_url":current_page_url,
        "editing":is_editing
      });
  });
}
var global_res = "";
var global_next = "";

var updateAttr = function(instance, object, attr_path, value){
  var jb =3;
  // attr_path is one array
  if (attr_path.length == 1){
    // console.log("updateAttr updating value");
    // console.log(attr_path[0]);
    // console.log(value);
    if (value != null && typeof value != 'undefined'){
      // updating
      if (typeof value  =='object') {
        _.each( _.keys(object[attr_path[0]].toObject()), function(keyname, index, array){
          if (value[keyname]) {
            console.log("setting " + keyname + " true");
            object[attr_path[0]][keyname] = value[keyname];
          }
          else {
            console.log("setting " + keyname + " false");
            object[attr_path[0]][keyname] = false;
          }
        });

      } else {
        object[attr_path[0]] = value;
      }

    }
    else {
      console.log("value value is invalid")
    }
    instance.save( function(err, instance){
      if (err){ console.log("[! ERROR !]  NOT successfully saved");
        return global_next(err);
      }
      else {
        console.log("[INFO] "+ instance._id +" saved. ")
        global_res.status(200).send(instance.toObject());
      };
      global_next = "";
      global_res = "";
    });

    return
  }
  else{
    updateAttr( instance, object[attr_path.shift()], attr_path, value  );
  }
}

exports.dbUpdateAttr =function(req, res , next){
  global_res = res;
  global_next = next;
  _.each(req.body, function(element, key, list){
    console.log(element+"  " + key);
    req.body[key] = JSON.parse(req.body[key]);
  });
  // console.log(req.body);
  req.db_model.findOne({_id:req.params.id} , null, {}, function(err, instance){
    if (err) {
      return next(err);
    }
    if (!instance) {
      res.status(404).send("requested resource cannot be found").end();
      return;
    }

    updateAttr(instance, instance, req.body['attr_path'], req.body['value']);

    console.log("end of updateAttr()")
  });
}
<commit_msg>listing page now has title<commit_after>var _ = require('underscore');
// var current_page_url = (process.env.local)?"http://localhost:3000/":"http://listingtest-u7yhjm.rhcloud.com/";
var current_page_url = (process.env.local)?"http://localhost:3000/":"http://listing.easysublease.org/";

exports.renderJade = function( req, res, next, is_editing){
  req.db_model.findOne({_id:req.params.id}, null,{},function(err, instance){
      if (err) {
        console.log(err.message);
        return next(err);
      }
      if(!instance) {
        res.status(404).send("requested resource cannot be found").end();
        return;
      }
      var instance_result = instance.toObject();
      res.render("my_listing.jade",{
        "title": instance_result.listing_related.title,
        "result":instance_result,
        "current_page_url":current_page_url,
        "editing":is_editing
      });
  });
}
var global_res = "";
var global_next = "";

var updateAttr = function(instance, object, attr_path, value){
  var jb =3;
  // attr_path is one array
  if (attr_path.length == 1){
    // console.log("updateAttr updating value");
    // console.log(attr_path[0]);
    // console.log(value);
    if (value != null && typeof value != 'undefined'){
      // updating
      if (typeof value  =='object') {
        _.each( _.keys(object[attr_path[0]].toObject()), function(keyname, index, array){
          if (value[keyname]) {
            console.log("setting " + keyname + " true");
            object[attr_path[0]][keyname] = value[keyname];
          }
          else {
            console.log("setting " + keyname + " false");
            object[attr_path[0]][keyname] = false;
          }
        });

      } else {
        object[attr_path[0]] = value;
      }

    }
    else {
      console.log("value value is invalid")
    }
    instance.save( function(err, instance){
      if (err){ console.log("[! ERROR !]  NOT successfully saved");
        return global_next(err);
      }
      else {
        console.log("[INFO] "+ instance._id +" saved. ")
        global_res.status(200).send(instance.toObject());
      };
      global_next = "";
      global_res = "";
    });

    return
  }
  else{
    updateAttr( instance, object[attr_path.shift()], attr_path, value  );
  }
}

exports.dbUpdateAttr =function(req, res , next){
  global_res = res;
  global_next = next;
  _.each(req.body, function(element, key, list){
    console.log(element+"  " + key);
    req.body[key] = JSON.parse(req.body[key]);
  });
  // console.log(req.body);
  req.db_model.findOne({_id:req.params.id} , null, {}, function(err, instance){
    if (err) {
      return next(err);
    }
    if (!instance) {
      res.status(404).send("requested resource cannot be found").end();
      return;
    }

    updateAttr(instance, instance, req.body['attr_path'], req.body['value']);

    console.log("end of updateAttr()")
  });
}
<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_topic_module.js
 */

module.exports = {
    malloc: function (session_val) {
        return new topicObject(session_val);
    },
};

function topicObject (session_val) {
    "use strict";
    this.theUtilModule = require("./util_module.js");
    this.theQueueModule = require("./queue_module.js");
    this.theGoContainerModule = require("./go_game/go_container_module.js")

    this.theSessionObject = session_val;

    this.objectName = function () {
        return "topicObject";
    };

    this.utilModule = function () {
        return this.theUtilModule;
    };

    this.queueModule = function () {
        return this.theQueueModule;
    };

    this.goContainerModule = function () {
        return this.theGoContainerModule;
    };

    this.sessionObject = function () {
        return this.theSessionObject;
    };

    this.goContainerObject = function () {
        return this.theGoContainerObject;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.transmitQueue = function () {
        return this.theTransmitQueue;
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.abend = function (str1_val, str2_val) {
        this.utilModule().abend(this.objectName() + "." + str1_val, str2_val);
    };

    this.logit = function (str1_val, str2_val) {
        this.utilModule().logit(this.objectName() + "." + str1_val, str2_val);
    };

    this.enqueueTransmitData = function (data_val) {
        this.transmitQueue().enQueue(data_val);
    };

    this.processTransmitData = function () {
        while (true) {
            var data = this.transmitQueue().deQueue();
            if (!data) {
                return;
            }
            this.sessionObject().transmitQueue().enQueue(data);
        }
    };

    this.processSetupLinkData = function (json_data_val) {
        this.debug(true, "processSetupLinkData", "data=" + json_data_val);
        var json = JSON.parse(json_data_val);
        if (json.command === "config") {
            this.goContainerObject().configObject().createConfig(json.data);
        }
    };

    this.processReceiveData = function () {
        while (true) {
            var data = this.receiveQueue().deQueue();
            if (!data) {
                return;
            }
            this.receiveStringData(data);
        }
    };

    this.enqueAndPocessReceiveData = function (data_val) {
        this.debug(true, "processReceiveData", data_val);
        this.receiveQueue().enQueue(data_val);
        this.processReceiveData();
    };

    this.receiveStringData = function (str_val) {
        this.goContainerObject().portObject().receiveStringData(str_val);
    };

    this.logit(this.objectName(), "aaa");

    this.theGoContainerObject = this.goContainerModule().malloc(this);
    this.theReceiveQueue = this.queueModule().malloc();
    this.theTransmitQueue = this.queueModule().malloc();
}
<commit_msg>session array<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_topic_module.js
 */

module.exports = {
    malloc: function (session_val) {
        return new topicObject(session_val);
    },
};

function topicObject (session_val) {
    "use strict";
    this.theUtilModule = require("./util_module.js");
    this.theQueueModule = require("./queue_module.js");
    this.theGoContainerModule = require("./go_game/go_container_module.js")

    this.theSessionArray = [2];
    this.theSessionArray[0] = session_val;
    this.theSessionArrayLength = 1;
    this.theSessionObject =  this.theSessionArray[0];

    this.objectName = function () {
        return "topicObject";
    };

    this.utilModule = function () {
        return this.theUtilModule;
    };

    this.queueModule = function () {
        return this.theQueueModule;
    };

    this.goContainerModule = function () {
        return this.theGoContainerModule;
    };

    this.sessionObject = function () {
        return this.theSessionObject;
    };

    this.goContainerObject = function () {
        return this.theGoContainerObject;
    };

    this.sessionArray = function (index_val) {
        return this.theSessionArray[index_val];
    };

    this.sessionArrayLength = function () {
        return this.theSessionArrayLength;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.transmitQueue = function () {
        return this.theTransmitQueue;
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.abend = function (str1_val, str2_val) {
        this.utilModule().abend(this.objectName() + "." + str1_val, str2_val);
    };

    this.logit = function (str1_val, str2_val) {
        this.utilModule().logit(this.objectName() + "." + str1_val, str2_val);
    };

    this.enqueueTransmitData = function (data_val) {
        this.transmitQueue().enQueue(data_val);
    };

    this.processTransmitData = function () {
        while (true) {
            var data = this.transmitQueue().deQueue();
            if (!data) {
                return;
            }

            var i = 0;
            while (i < this.sessionArrayLength()) {
                this.sessionArray(i).transmitQueue().enQueue(data);
                i += 1;
            }
        }
    };

    this.processSetupLinkData = function (json_data_val) {
        this.debug(true, "processSetupLinkData", "data=" + json_data_val);
        var json = JSON.parse(json_data_val);
        if (json.command === "config") {
            this.goContainerObject().configObject().createConfig(json.data);
        }
    };

    this.processReceiveData = function () {
        while (true) {
            var data = this.receiveQueue().deQueue();
            if (!data) {
                return;
            }
            this.receiveStringData(data);
        }
    };

    this.enqueAndPocessReceiveData = function (data_val) {
        this.debug(true, "processReceiveData", data_val);
        this.receiveQueue().enQueue(data_val);
        this.processReceiveData();
    };

    this.receiveStringData = function (str_val) {
        this.goContainerObject().portObject().receiveStringData(str_val);
    };

    this.logit(this.objectName(), "aaa");

    this.theGoContainerObject = this.goContainerModule().malloc(this);
    this.theReceiveQueue = this.queueModule().malloc();
    this.theTransmitQueue = this.queueModule().malloc();
}
<|endoftext|>


<commit_before>var operators = {
  'eq': '=',
  'ne': '!=',
  'lt': '<',
  'lte': '<=',
  'gt': '>',
  'gte': '>='
};

var enclose = function(val) {
  return typeof val === 'string' ? '\'' + val + '\'' : val;
};

module.exports = [
  {
    odata: '$top',
    esri: 'resultRecordCount',
    translate: function(val) {
      return val;
    }
  },
  {
    odata: '$skip',
    esri: 'resultOffset',
    translate: function(val) {
      return val;
    }
  },
  {
    odata: '$select',
    esri: 'outFields',
    translate: function(val) {
      return val.join(', ');
    }
  },
  {
    odata: '$filter',
    esri: 'where',
    translate: function(val) {
      if(val.type === 'and' || val.type === 'or') {
        return [
          this.translate(val.left),
          val.type,
          this.translate(val.right)
        ].join(' ');
      }
      else {
        return [
          val.left.name,
          operators[val.type],
          enclose(val.right.value)
        ].join(' ')
      };
    }
  }
]
<commit_msg>Added le & ge operators<commit_after>var operators = {
  'eq': '=',
  'ne': '!=',
  'lt': '<',
  'le': '<=',
  'gt': '>',
  'ge': '>='
};

var enclose = function(val) {
  return typeof val === 'string' ? '\'' + val + '\'' : val;
};

module.exports = [
  {
    odata: '$top',
    esri: 'resultRecordCount',
    translate: function(val) {
      return val;
    }
  },
  {
    odata: '$skip',
    esri: 'resultOffset',
    translate: function(val) {
      return val;
    }
  },
  {
    odata: '$select',
    esri: 'outFields',
    translate: function(val) {
      return val.join(', ');
    }
  },
  {
    odata: '$filter',
    esri: 'where',
    translate: function(val) {
      if(val.type === 'and' || val.type === 'or') {
        return [
          this.translate(val.left),
          val.type,
          this.translate(val.right)
        ].join(' ');
      }
      else {
        return [
          val.left.name,
          operators[val.type],
          enclose(val.right.value)
        ].join(' ')
      };
    }
  }
]
<|endoftext|>


<commit_before>"use strict";
/*eslint-disable*/
module.exports = () => {

    const vars = {};

    vars.http                   = require('http');
    vars.ipAddress              = require('ip').address();
    vars.path                   = require('path');

    vars.webpack                = require('webpack');
    vars.chalk                  = require('chalk');
    vars._                      = require('lodash');
    vars.Q                      = require('q');
    vars.qfs                    = require('q-io/fs');
    vars.fs                     = require('fs-extra');
    vars.exec                   = require('child_process').exec;
    vars.spawn                  = require('child_process').spawn;
    vars.spawnSync              = require('child_process').spawnSync;
    vars.chokidar               = require('chokidar');

    try {
        vars.GIT_VERSION        = require('child_process').execSync('git rev-parse HEAD').toString().trim();
        vars.GIT_VERSION_SHORT  = require('child_process').execSync('git rev-parse --short HEAD').toString().trim();
    } catch (err) {
        console.log("git is not initialized...", vars.chalk.red(err.cmd) + " FAILED!");
        vars.GIT_VERSION        = 'buildDetails';
        vars.GIT_VERSION_SHORT  = 'UNKNOWN_GIT_VERSION_SHORT';
    }
    vars.BUILD_DATE             = new Date();

    vars.ProgressBarPlugin      = require('progress-bar-webpack-plugin');
    vars.HtmlWebpackPlugin      = require('html-webpack-plugin');
    vars.BrowserSyncPlugin      = require('browser-sync-webpack-plugin');
    vars.StyleLintPlugin        = require('stylelint-webpack-plugin');
    vars.ExtractTextPlugin      = require("extract-text-webpack-plugin");
    vars.Visualizer             = require('webpack-visualizer-plugin');
    vars.WebpackDevServer       = require('webpack-dev-server');
    vars.WebpackDevMiddleware   = require("webpack-dev-middleware");
    vars.WebpackHotMiddleware   = require("webpack-hot-middleware");
    vars.fallback               = require('express-history-api-fallback');
    vars.historyApiFallback     = require('connect-history-api-fallback');
    vars.ImageminPlugin         = require('imagemin-webpack-plugin').default;
    vars.WebpackShellPlugin     = require('webpack-shell-plugin');
    vars.CleanWebpackPlugin     = require('clean-webpack-plugin');
    vars.WebpackNotifierPlugin  = require('webpack-notifier');
    vars.CopyWebpackPlugin      = require('copy-webpack-plugin');

    vars.autoprefixer           = require('autoprefixer');

    vars.express                = require('express');
    vars.app                    = require('express')();
    vars.morgan                 = require('morgan');
    vars.NODE_ENV               = process.env.NODE_ENV;

    return vars;
};<commit_msg>adjust GIT_VERSION variable<commit_after>"use strict";
/*eslint-disable*/
module.exports = () => {

    const vars = {};

    vars.http                   = require('http');
    vars.ipAddress              = require('ip').address();
    vars.path                   = require('path');

    vars.webpack                = require('webpack');
    vars.chalk                  = require('chalk');
    vars._                      = require('lodash');
    vars.Q                      = require('q');
    vars.qfs                    = require('q-io/fs');
    vars.fs                     = require('fs-extra');
    vars.exec                   = require('child_process').exec;
    vars.spawn                  = require('child_process').spawn;
    vars.spawnSync              = require('child_process').spawnSync;
    vars.chokidar               = require('chokidar');

    try {
        vars.GIT_VERSION        = require('child_process').execSync('git rev-parse HEAD').toString().trim();
        vars.GIT_VERSION_SHORT  = require('child_process').execSync('git rev-parse --short HEAD').toString().trim();
    } catch (err) {
        console.log("git is not initialized...", vars.chalk.red(err.cmd) + " FAILED!");
        vars.GIT_VERSION        = 'GIT_VERSION';
        vars.GIT_VERSION_SHORT  = 'UNKNOWN_GIT_VERSION_SHORT';
    }
    vars.BUILD_DATE             = new Date();

    vars.ProgressBarPlugin      = require('progress-bar-webpack-plugin');
    vars.HtmlWebpackPlugin      = require('html-webpack-plugin');
    vars.BrowserSyncPlugin      = require('browser-sync-webpack-plugin');
    vars.StyleLintPlugin        = require('stylelint-webpack-plugin');
    vars.ExtractTextPlugin      = require("extract-text-webpack-plugin");
    vars.Visualizer             = require('webpack-visualizer-plugin');
    vars.WebpackDevServer       = require('webpack-dev-server');
    vars.WebpackDevMiddleware   = require("webpack-dev-middleware");
    vars.WebpackHotMiddleware   = require("webpack-hot-middleware");
    vars.fallback               = require('express-history-api-fallback');
    vars.historyApiFallback     = require('connect-history-api-fallback');
    vars.ImageminPlugin         = require('imagemin-webpack-plugin').default;
    vars.WebpackShellPlugin     = require('webpack-shell-plugin');
    vars.CleanWebpackPlugin     = require('clean-webpack-plugin');
    vars.WebpackNotifierPlugin  = require('webpack-notifier');
    vars.CopyWebpackPlugin      = require('copy-webpack-plugin');

    vars.autoprefixer           = require('autoprefixer');

    vars.express                = require('express');
    vars.app                    = require('express')();
    vars.morgan                 = require('morgan');
    vars.NODE_ENV               = process.env.NODE_ENV;

    return vars;
};<|endoftext|>


<commit_before>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("0.6.1",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 6; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Virtual Boy",11); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<commit_msg>language.majorVersionBinary<commit_after>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("0.6.1",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 6; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Virtual Boy",11); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 5; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<|endoftext|>


<commit_before>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message) {
    if (message.channel.type != 'text') return;
    var guild = message.guild;
    var embed = utils.generateDekuDiv(message);
    var regions = {
      'brazil': ':flag_br: Brazil',
      'eu-central': ':flag_eu: EU Central',
      'hongkong': ':flag_hk: Hongkong',
      'us-central': ':flag_us: US Central',
      'us-east': ':flag_us: US East',
      'us-south': ':flag_us: US South',
      'us-west': ':flag_us: US West',
      'russia': ':flag_ru: Russia',
      'sydney': ':flag_au: Sydney',
      'eu-west': ':flag_eu: Western Europe'
    };
    var region = regions[guild.region] || guild.region;
    var offline = guild.members.filter(m=>m.presence.status=="offline").size;
    var online = guild.members.size - offline;
    embed.addField('Name', guild.name, true);
    embed.addField('Members', online + '/' + guild.members.size + ' online', true);
    embed.addField('Owner', guild.owner.user.tag, true);
    embed.addField('Region', region, true);
    embed.addField('Emojis', guild.emojis.size, true);
    embed.addField('Roles', guild.roles.size, true);
    embed.addField('ID', guild.id, true);
    embed.setThumbnail(guild.iconURL);

    message.channel.send({embed});
  }
}
<commit_msg>Don't run command in DMs<commit_after>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message) {
    var guild = message.guild;
    var embed = utils.generateDekuDiv(message);
    var regions = {
      'brazil': ':flag_br: Brazil',
      'eu-central': ':flag_eu: EU Central',
      'hongkong': ':flag_hk: Hongkong',
      'us-central': ':flag_us: US Central',
      'us-east': ':flag_us: US East',
      'us-south': ':flag_us: US South',
      'us-west': ':flag_us: US West',
      'russia': ':flag_ru: Russia',
      'sydney': ':flag_au: Sydney',
      'eu-west': ':flag_eu: Western Europe'
    };
    var region = regions[guild.region] || guild.region;
    var offline = guild.members.filter(m=>m.presence.status=="offline").size;
    var online = guild.members.size - offline;
    embed.addField('Name', guild.name, true);
    embed.addField('Members', online + '/' + guild.members.size + ' online', true);
    embed.addField('Owner', guild.owner.user.tag, true);
    embed.addField('Region', region, true);
    embed.addField('Emojis', guild.emojis.size, true);
    embed.addField('Roles', guild.roles.size, true);
    embed.addField('ID', guild.id, true);
    embed.setThumbnail(guild.iconURL);

    message.channel.send({embed});
  }
}
<|endoftext|>