<commit_before>'use strict';

const Hs100Api = require('hs100-api');
var Accessory, Service, Characteristic, UUIDGen;

module.exports = function (homebridge) {
  Accessory = homebridge.platformAccessory;
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  homebridge.registerPlatform('homebridge-hs100', 'Hs100', Hs100Platform, true);
};

class Hs100Platform {
  constructor (log, config, api) {
    this.log = log;
    this.config = config || {};
    this.api = api;
    this.plugs = config['plugs'] || [];
    this.accessories = new Map();

    this.client = new Hs100Api.Client();

    this.client.on('plug-offline', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory !== undefined) {
        if (accessory instanceof Hs100Accessory) {
          this.log('Offline: %s [%s]', accessory.accessory.displayName, accessory.deviceId);
          accessory.accessory.updateReachability(false);
        }
      }
    });

    this.client.on('plug-online', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory === undefined) {
        this.addAccessory(plug);
      } else {
        if (accessory instanceof Hs100Accessory) {
          this.log('Online: %s [%s]', accessory.accessory.displayName, plug.deviceId);
          accessory.accessory.updateReachability(true);
        }
      }
    });

    this.client.on('plug-new', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory === undefined) {
        this.addAccessory(plug);
      } else {
        this.log('New Plug Online: %s [%s]', accessory.displayName, plug.deviceId);
        var hs100Acc = new Hs100Accessory(this.log, accessory, this.client);
        this.accessories.set(plug.deviceId, hs100Acc);
        hs100Acc.configure(plug);
      }
    });

    this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this));
  }

  configureAccessory (accessory) {
    this.accessories.set(accessory.context.deviceId, accessory);
  }

  didFinishLaunching () {
    this.client.startDiscovery();
  }

  addAccessory (plug) {
    const name = plug.name;
    this.log('Adding: %s', name);

    const platformAccessory = new Accessory(name, UUIDGen.generate(plug.deviceId), 7 /* Accessory.Categories.OUTLET */);
    platformAccessory.addService(Service.Outlet, name);

    const infoService = platformAccessory.getService(Service.AccessoryInformation);
    infoService.addCharacteristic(Characteristic.FirmwareRevision);
    infoService.addCharacteristic(Characteristic.HardwareRevision);

    platformAccessory.context.deviceId = plug.deviceId;
    platformAccessory.context.host = plug.host;
    platformAccessory.context.port = plug.port || 9999;

    const accessory = new Hs100Accessory(this.log, platformAccessory, this.client);

    return accessory.configure(plug).then(() => {
      this.accessories.set(plug.deviceId, accessory);
      this.api.registerPlatformAccessories('homebridge-hs100', 'Hs100', [platformAccessory]);
      return accessory;
    }).catch((reason) => {
      this.log(reason);
    });
  }

  removeAccessory (accessory) {
    this.log('Removing: %s', accessory.accessory.displayName);

    this.accessories.delete(accessory.accessory.deviceId);
    this.api.unregisterPlatformAccessories('homebridge-hs100', 'Hs100', [accessory.accessory]);
  }

}

class Hs100Accessory {
  constructor (log, accessory, client) {
    this.log = log;

    this.accessory = accessory;
    this.client = client;
    this.plug = client.getPlug({host: accessory.context.host, port: accessory.context.port});
    this.deviceId = accessory.context.deviceId;
  // this.hs100api = hs100api ; // || new Hs100Api({host: accessory.context.host, port: accessory.context.port})
  }

  identify (callback) {
    // TODO
    callback();
  }

  configure (plug) {
    this.log('Configuring: %s', this.accessory.displayName);

    let plugInfo = plug ? Promise.resolve(plug.getInfo) : this.plug.getInfo();

    return plugInfo.then((info) => {
      const pa = this.accessory;

      this.refresh(info.sysInfo);

      const outletService = pa.getService(Service.Outlet);
      outletService.getCharacteristic(Characteristic.On)
        .on('get', (callback) => {
          this.plug.getSysInfo().then((si) => {
            this.refresh(si);
            callback(null, si.relay_state === 1);
          }).catch((reason) => {
            this.log(reason);
          });
        })
        .on('set', (value, callback) => {
          this.plug.setPowerState(value).then(() => {
            callback();
          }, (reason) => {
            this.log(reason);
          });
        });

      outletService.getCharacteristic(Characteristic.OutletInUse)
        .on('get', (callback) => {
          this.plug.getSysInfo().then((si) => {
            this.refresh(si);
            callback(null, si.relay_state === 1);
          }).catch((reason) => {
            this.log(reason);
          });
        });
    }).catch((reason) => {
      this.log(reason);
    });
  }

  refresh (sysInfo) {
    sysInfo = sysInfo ? Promise.resolve(sysInfo) : this.plug.getSysInfo();

    return sysInfo.then((si) => {
      this.accessory.updateReachability(true);

      const name = si.alias || this.accessory.context.host;
      this.accessory.displayName = name;

      const outletService = this.accessory.getService(Service.Outlet);
      outletService.setCharacteristic(Characteristic.Name, name);

      const infoService = this.accessory.getService(Service.AccessoryInformation);
      infoService
        .setCharacteristic(Characteristic.Name, name)
        .setCharacteristic(Characteristic.Manufacturer, 'TP-Link')
        .setCharacteristic(Characteristic.Model, si.model)
        .setCharacteristic(Characteristic.SerialNumber, si.deviceId)
        .setCharacteristic(Characteristic.FirmwareRevision, si.sw_ver)
        .setCharacteristic(Characteristic.HardwareRevision, si.hw_ver);

      this.accessory.context.lastRefreshed = new Date();
      return this;
    }).catch((reason) => {
      this.log(reason);
    });
  }
}
<commit_msg>Modified OutletInUse characteristic checking the power consumption<commit_after>'use strict';

const Hs100Api = require('hs100-api');
var Accessory, Service, Characteristic, UUIDGen;

module.exports = function (homebridge) {
  Accessory = homebridge.platformAccessory;
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  UUIDGen = homebridge.hap.uuid;

  homebridge.registerPlatform('homebridge-hs100', 'Hs100', Hs100Platform, true);
};

class Hs100Platform {
  constructor (log, config, api) {
    this.log = log;
    this.config = config || {};
    this.api = api;
    this.plugs = config['plugs'] || [];
    this.accessories = new Map();

    this.client = new Hs100Api.Client();

    this.client.on('plug-offline', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory !== undefined) {
        if (accessory instanceof Hs100Accessory) {
          this.log('Offline: %s [%s]', accessory.accessory.displayName, accessory.deviceId);
          accessory.accessory.updateReachability(false);
        }
      }
    });

    this.client.on('plug-online', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory === undefined) {
        this.addAccessory(plug);
      } else {
        if (accessory instanceof Hs100Accessory) {
          this.log('Online: %s [%s]', accessory.accessory.displayName, plug.deviceId);
          accessory.accessory.updateReachability(true);
        }
      }
    });

    this.client.on('plug-new', (plug) => {
      var accessory = this.accessories.get(plug.deviceId);
      if (accessory === undefined) {
        this.addAccessory(plug);
      } else {
        this.log('New Plug Online: %s [%s]', accessory.displayName, plug.deviceId);
        var hs100Acc = new Hs100Accessory(this.log, accessory, this.client);
        this.accessories.set(plug.deviceId, hs100Acc);
        hs100Acc.configure(plug);
      }
    });

    this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this));
  }

  configureAccessory (accessory) {
    this.accessories.set(accessory.context.deviceId, accessory);
  }

  didFinishLaunching () {
    this.client.startDiscovery();
  }

  addAccessory (plug) {
    const name = plug.name;
    this.log('Adding: %s', name);

    const platformAccessory = new Accessory(name, UUIDGen.generate(plug.deviceId), 7 /* Accessory.Categories.OUTLET */);
    platformAccessory.addService(Service.Outlet, name);

    const infoService = platformAccessory.getService(Service.AccessoryInformation);
    infoService.addCharacteristic(Characteristic.FirmwareRevision);
    infoService.addCharacteristic(Characteristic.HardwareRevision);

    platformAccessory.context.deviceId = plug.deviceId;
    platformAccessory.context.host = plug.host;
    platformAccessory.context.port = plug.port || 9999;

    const accessory = new Hs100Accessory(this.log, platformAccessory, this.client);

    return accessory.configure(plug).then(() => {
      this.accessories.set(plug.deviceId, accessory);
      this.api.registerPlatformAccessories('homebridge-hs100', 'Hs100', [platformAccessory]);
      return accessory;
    }).catch((reason) => {
      this.log(reason);
    });
  }

  removeAccessory (accessory) {
    this.log('Removing: %s', accessory.accessory.displayName);

    this.accessories.delete(accessory.accessory.deviceId);
    this.api.unregisterPlatformAccessories('homebridge-hs100', 'Hs100', [accessory.accessory]);
  }

}

class Hs100Accessory {
  constructor (log, accessory, client) {
    this.log = log;

    this.accessory = accessory;
    this.client = client;
    this.plug = client.getPlug({host: accessory.context.host, port: accessory.context.port});
    this.deviceId = accessory.context.deviceId;
  // this.hs100api = hs100api ; // || new Hs100Api({host: accessory.context.host, port: accessory.context.port})
  }

  identify (callback) {
    // TODO
    callback();
  }

  configure (plug) {
    this.log('Configuring: %s', this.accessory.displayName);

    let plugInfo = plug ? Promise.resolve(plug.getInfo) : this.plug.getInfo();

    return plugInfo.then((info) => {
      const pa = this.accessory;

      this.refresh(info.sysInfo);

      const outletService = pa.getService(Service.Outlet);
      outletService.getCharacteristic(Characteristic.On)
        .on('get', (callback) => {
          this.plug.getSysInfo().then((si) => {
            this.refresh(si);
            callback(null, si.relay_state === 1);
          }).catch((reason) => {
            this.log(reason);
          });
        })
        .on('set', (value, callback) => {
          this.plug.setPowerState(value).then(() => {
            callback();
          }, (reason) => {
            this.log(reason);
          });
        });

      outletService.getCharacteristic(Characteristic.OutletInUse)
        .on('get', (callback) => {
          this.plug.getSysInfo().then((si) => {
            this.refresh(si);
            // On HS110 model we'll check the current power consumption to determinate the state
            if(si.model.toLowerCase().indexOf("hs110")) {
              this.plug.getConsumption().then((consumption) => {
                callback(null, consumption.get_realtime.power > 0);
              });
            // On HS100 we can just use relay state
            } else {
              callback(null, si.relay_state === 1);
            }
          }).catch((reason) => {
            this.log(reason);
          });
        });
    }).catch((reason) => {
      this.log(reason);
    });
  }

  refresh (sysInfo) {
    sysInfo = sysInfo ? Promise.resolve(sysInfo) : this.plug.getSysInfo();

    return sysInfo.then((si) => {
      this.accessory.updateReachability(true);

      const name = si.alias || this.accessory.context.host;
      this.accessory.displayName = name;

      const outletService = this.accessory.getService(Service.Outlet);
      outletService.setCharacteristic(Characteristic.Name, name);

      const infoService = this.accessory.getService(Service.AccessoryInformation);
      infoService
        .setCharacteristic(Characteristic.Name, name)
        .setCharacteristic(Characteristic.Manufacturer, 'TP-Link')
        .setCharacteristic(Characteristic.Model, si.model)
        .setCharacteristic(Characteristic.SerialNumber, si.deviceId)
        .setCharacteristic(Characteristic.FirmwareRevision, si.sw_ver)
        .setCharacteristic(Characteristic.HardwareRevision, si.hw_ver);

      this.accessory.context.lastRefreshed = new Date();
      return this;
    }).catch((reason) => {
      this.log(reason);
    });
  }
}
<|endoftext|>


<commit_before>module.exports = utils;
module.exports['default'] = utils;

var isTouch = require('./is-touch').default;

function utils(base, props, statuses) {
  return {
    isTouch: isTouch
  };
};
<commit_msg>there is no excuse, I am an idiot<commit_after>var isTouch = require('./is-touch');
var utils = {
  isTouch: isTouch.default
};

module.exports = utils;
module.exports['default'] = utils;<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()

app.set('port', (process.env.PORT || 5000))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))

// parse application/json
app.use(bodyParser.json())

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot')
})

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge'])
	}
	res.send('Error, wrong token')
})

// to post data
app.post('/webhook/', function (req, res) {
	let messaging_events = req.body.entry[0].messaging
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i]
		let sender = event.sender.id
		if (event.message && event.message.text) {
			let text = event.message.text
			if (text === 'Generic') {
				sendGenericMessage(sender)
				continue
			}
			sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
		}
		if (event.postback) {
			let text = JSON.stringify(event.postback)
			sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
			continue
		}
	}
	res.sendStatus(200)
})

// recommended to inject access tokens as environmental variables, e.g.
// const token = process.env.PAGE_ACCESS_TOKEN
const token = process.env.FB_PAGE_ACCESS_TOKEN

function sendTextMessage(sender, text) {
	let messageData = { text:text }

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error)
		} else if (response.body.error) {
			console.log('Error: ', response.body.error)
		}
	})
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	}
	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error)
		} else if (response.body.error) {
			console.log('Error: ', response.body.error)
		}
	})
}

// spin spin sugar
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'))
})
<commit_msg>added funky<commit_after>'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()

app.set('port', (process.env.PORT || 5000))

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))

// parse application/json
app.use(bodyParser.json())

// index
app.get('/', function (req, res) {
	res.send('hello world i am a secret bot')
})

// for facebook verification
app.get('/webhook/', function (req, res) {
	if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
		res.send(req.query['hub.challenge'])
	}
	res.send('Error, wrong token')
})

// to post data
app.post('/webhook/', function (req, res) {
	let messaging_events = req.body.entry[0].messaging
	for (let i = 0; i < messaging_events.length; i++) {
		let event = req.body.entry[0].messaging[i]
		let sender = event.sender.id
		if (event.message && event.message.text) {
			let text = event.message.text
			if (text === 'Generic') {
				sendGenericMessage(sender)
				continue
			} else if (text === 'Funky') {
                sendFunkyMessage(sender)
			}
			sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
		}
		if (event.postback) {
			let text = JSON.stringify(event.postback)
			sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
			continue
		}
	}
	res.sendStatus(200)
})

// recommended to inject access tokens as environmental variables, e.g.
// const token = process.env.PAGE_ACCESS_TOKEN
const token = process.env.FB_PAGE_ACCESS_TOKEN

function sendTextMessage(sender, text) {
	let messageData = { text:text }

	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error)
		} else if (response.body.error) {
			console.log('Error: ', response.body.error)
		}
	})
}

function sendFunkyMessage(sender) {
    let messageData = {
        "attachement": {
            "type": "template",
            "payload": {
                "template_type": "button",
                "text": "The POWER of node.js in Messenger",
                "buttons": [
                    {
                        "type": "postback",
                        "title": "Show OneBlade",
                        "payload": "Payload content"
                    },
                    {
                        "type": "web_url",
                        "title": "Show OneBlade Product Page",
                        "url": "http://www.philips.co.uk/c-m-pe/oneblade-face-style-and-shave",
                        "webview_height_ratio": "compact"
                    }
                ]
            }
        }
    }
}

function sendGenericMessage(sender) {
	let messageData = {
		"attachment": {
			"type": "template",
			"payload": {
				"template_type": "generic",
				"elements": [{
					"title": "First card",
					"subtitle": "Element #1 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/rift.png",
					"buttons": [{
						"type": "web_url",
						"url": "https://www.messenger.com",
						"title": "web url"
					}, {
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for first element in a generic bubble",
					}],
				}, {
					"title": "Second card",
					"subtitle": "Element #2 of an hscroll",
					"image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
					"buttons": [{
						"type": "postback",
						"title": "Postback",
						"payload": "Payload for second element in a generic bubble",
					}],
				}]
			}
		}
	}
	request({
		url: 'https://graph.facebook.com/v2.6/me/messages',
		qs: {access_token:token},
		method: 'POST',
		json: {
			recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
			console.log('Error sending messages: ', error)
		} else if (response.body.error) {
			console.log('Error: ', response.body.error)
		}
	})
}

// spin spin sugar
app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'))
})
<|endoftext|>


<commit_before>var extractor = require('unfluff');
var request = require('request');
var google = require('google');

exports.synopsis = function(mediaTitle, mediaType, callback) {
    if (mediaType === null || mediaType === undefined) {
        mediaType = '';
    }
    google(mediaTitle + ' ' + mediaType + ' site:wikipedia.org',
        function(err, next, links){
            if (err) {
                callback(err);
                return;
            }
            if (!links[0]) {
                callback("No Wikipedia Results found for that mediaTitle and mediaType");
                return;
            }
            // Sometimes this will be 'List of x Episodes' for TV shows. Example: 're hamatora'
            var title = getMediaTitle(links[0].title);
            request(links[0].link, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                data = extractor(body);
                var releventParagraphs = getParagraphsUntilMediaMention(data.text, mediaType);
                callback(undefined,
                {
                    title: title,
                    content: releventParagraphs.replace(/(\[.+\])/g,'') // Remove annotations
                });
        } else {
            callback(error);
        }
    });
    });
};

function getMediaTitle(fullLinkText) {
    var title = fullLinkText.split('- Wikipedia')[0];
    var listOfEpsRegex = /.*List of (.*) episodes/.exec(title);
    if(listOfEpsRegex) {
        return listOfEpsRegex[1];
    }
    var filmRegex = /(.*) \(film\)/.exec(title);
    if(filmRegex) {
        return filmRegex[1];
    }
    return title;
}

function getParagraphsUntilMediaMention(text, mediaType) {
    paragraphs = text.split('\n');
    var re = new RegExp('\\b' + mediaType + '\\b', 'i');
    var output = [];
    var index = 0;
    while(index <= paragraphs.length) {
        if(re.test(paragraphs[index]) || mediaType === ''){
            // If there's already stuff in there make a new line,
            // otherwise just return the current paragraph
            return output.length > 0 ?
            output.join('\n') + paragraphs[index] :
            paragraphs[index];
        }
        output.push(paragraphs[index]); // Add whatever was found to output buffer
        index += 1;
    }
    // Word anime wasn't found, return falsey value
    return '';
}<commit_msg>Updated doc for getParagraphs but not code yet<commit_after>var extractor = require('unfluff');
var request = require('request');
var google = require('google');

exports.synopsis = function(mediaTitle, mediaType, callback) {
    if (mediaType === null || mediaType === undefined) {
        mediaType = '';
    }
    google(mediaTitle + ' ' + mediaType + ' site:wikipedia.org',
        function(err, next, links){
            if (err) {
                callback(err);
                return;
            }
            if (!links[0]) {
                callback("No Wikipedia Results found for that mediaTitle and mediaType");
                return;
            }
            // Sometimes this will be 'List of x Episodes' for TV shows. Example: 're hamatora'
            var title = getMediaTitle(links[0].title);
            request(links[0].link, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                data = extractor(body);
                var releventParagraphs = getParagraphsUntilMediaMention(data.text, mediaType);
                callback(undefined,
                {
                    title: title,
                    content: releventParagraphs.replace(/(\[.+\])/g,'') // Remove annotations
                });
        } else {
            callback(error);
        }
    });
    });
};

function getMediaTitle(fullLinkText) {
    var title = fullLinkText.split('- Wikipedia')[0];
    var listOfEpsRegex = /.*List of (.*) episodes/.exec(title);
    if(listOfEpsRegex) {
        return listOfEpsRegex[1];
    }
    var filmRegex = /(.*) \(film\)/.exec(title);
    if(filmRegex) {
        return filmRegex[1];
    }
    return title;
}

/**
Three possible return scenarios:

1. First paragraph contains the mediaType, return it
2. First paragraph does not contain the mediaType but the forth down
or less does, return 0 - paragraph containing media term
3. First 4 paragraphs do not contain mediaType, return first paragraph
*/
function getParagraphsUntilMediaMention(text, mediaType) {
    paragraphs = text.split('\n');
    var re = new RegExp('\\b' + mediaType + '\\b', 'i');
    var output = [];
    var index = 0;
    while(index <= paragraphs.length) {
        if(re.test(paragraphs[index]) || mediaType === ''){
            // If there's already stuff in there make a new line,
            // otherwise just return the current paragraph
            return output.length > 0 ?
            output.join('\n') + paragraphs[index] :
            paragraphs[index];
        }
        output.push(paragraphs[index]); // Add whatever was found to output buffer
        index += 1;
    }
    // Word anime wasn't found, return falsey value
    return '';
}<|endoftext|>


<commit_before>/*
 =================================================
 nodejs-static-noangularjs
 Copyright (c) 2014 Luis Enrique Arriojas Catalini
 http://opensource.org/licenses/MIT
 =================================================
 */

var http = require("http");
var url = require("url");
var fs = require("fs");
var server;

server = http.createServer(function (req, res) {
    var path = url.parse(req.url).pathname;
    switch (path) {
        case "/":
            res.writeHead(200, {"Content-Type": "text/html"});
            res.write("jojoy hola !!");
            res.end();
            break;
    }
});

server.listen(1337);<commit_msg>Error 404 added<commit_after>/*
 =================================================
 nodejs-static-noangularjs
 Copyright (c) 2014 Luis Enrique Arriojas Catalini
 http://opensource.org/licenses/MIT
 =================================================
 */

var http = require("http");
var url = require("url");
var fs = require("fs");
var server;

server = http.createServer(function (req, res) {
    var path = url.parse(req.url).pathname;
    switch (path) {
        case "/":
            res.writeHead(200, {"Content-Type": "text/html"});
            res.write("jojoy hola !!");
            res.end();
            break;
        default:
            send404(res);
            break;
    }
});

send404 = function (res) {
    res.writeHead(404, {"Content-Type": "text/html"});
    res.write("Error 404 - Pagina no encontrada");
    res.end();
};

server.listen(1337);<|endoftext|>


<commit_before>module.exports = {
  env: {
    browser: true,
    es6: true,
  },

  extends: 'eslint:recommended',

  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },

  rules: {
    'no-console':  ['warn', {allow: ['info', 'warn', 'error']}],
    'no-debugger': ['warn'],

    'arrow-parens':                ['error', 'as-needed'],
    'camelcase':                   ['error', {'properties': 'always'}],
    'comma-dangle':                ['error', 'always-multiline'],
    'comma-spacing':               ['error', {'before': false, 'after': true}],
    'eol-last':                    ['error'],
    'eqeqeq':                      ['error'],
    'indent':                      ['error', 2, {SwitchCase: 1}],
    'linebreak-style':             ['error', 'unix'],
    'multiline-ternary':           ['error', 'never'],
    'no-unused-expressions':       ['error'],
    'no-use-before-define':        ['error', {classes: false}],
    'object-curly-spacing':        ['error', 'never'],
    'object-shorthand':            ['error', 'always'],
    'quotes':                      ['error', 'backtick'],
    'semi':                        ['error', 'always'],
    'space-before-blocks':         ['error', 'always'],
    'space-before-function-paren': ['error', 'never'],
  },
};
<commit_msg>use backticks for eslint config<commit_after>module.exports = {
  env: {
    browser: true,
    es6: true,
  },

  extends: `eslint:recommended`,

  parserOptions: {
    ecmaVersion: 2017,
    sourceType: `module`,
  },

  rules: {
    'no-console':  [`warn`, {allow: [`info`, `warn`, `error`]}],
    'no-debugger': [`warn`],

    'arrow-parens':                [`error`, `as-needed`],
    'camelcase':                   [`error`, {'properties': `always`}],
    'comma-dangle':                [`error`, `always-multiline`],
    'comma-spacing':               [`error`, {'before': false, 'after': true}],
    'eol-last':                    [`error`],
    'eqeqeq':                      [`error`],
    'indent':                      [`error`, 2, {SwitchCase: 1}],
    'linebreak-style':             [`error`, `unix`],
    'multiline-ternary':           [`error`, `never`],
    'no-unused-expressions':       [`error`],
    'no-use-before-define':        [`error`, {classes: false}],
    'object-curly-spacing':        [`error`, `never`],
    'object-shorthand':            [`error`, `always`],
    'quotes':                      [`error`, `backtick`],
    'semi':                        [`error`, `always`],
    'space-before-blocks':         [`error`, `always`],
    'space-before-function-paren': [`error`, `never`],
  },
};
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var extend = require('util')._extend;

module.exports = {
  name: 'ember-offline',
  included: function(app) {
    this._super.included(app);

    var defaultThemes = {
      theme: 'default',
      indicator: false,
      language: 'english'
    };

    var config = this.project.config(app.env);
    var emberOffline = config.emberOffline || {};
    var configThemes = emberOffline.themes || {};

    var themes = extend(defaultThemes, configThemes);
    var themesDir = app.bowerDirectory + '/offline/themes';

    if (themes.theme) {
      app.import(themesDir + '/offline-theme-' + themes.theme + '.css');
      app.import(themesDir + '/offline-language-' + themes.language + '.css');
    }

    if (themes.indicator) {
      app.import(themesDir + '/offline-theme-' + themes.indicator + '-indicator.css');
      app.import(themesDir + '/offline-language-' + themes.language + '-indicator.css');
    }

    app.import(app.bowerDirectory + '/offline/offline.min.js');
  }
};
<commit_msg>Import the non-minified offline<commit_after>/* jshint node: true */
'use strict';

var extend = require('util')._extend;

module.exports = {
  name: 'ember-offline',
  included: function(app) {
    this._super.included(app);

    var defaultThemes = {
      theme: 'default',
      indicator: false,
      language: 'english'
    };

    var config = this.project.config(app.env);
    var emberOffline = config.emberOffline || {};
    var configThemes = emberOffline.themes || {};

    var themes = extend(defaultThemes, configThemes);
    var themesDir = app.bowerDirectory + '/offline/themes';

    if (themes.theme) {
      app.import(themesDir + '/offline-theme-' + themes.theme + '.css');
      app.import(themesDir + '/offline-language-' + themes.language + '.css');
    }

    if (themes.indicator) {
      app.import(themesDir + '/offline-theme-' + themes.indicator + '-indicator.css');
      app.import(themesDir + '/offline-language-' + themes.language + '-indicator.css');
    }

    app.import(app.bowerDirectory + '/offline/offline.js');
  }
};
<|endoftext|>


<commit_before>import merge from 'deepmerge';
import shvl from 'shvl';

export default function(options, storage, key) {
  options = options || {};
  storage = options.storage || (window && window.localStorage);
  key = options.key || 'vuex';

  function canWriteStorage(storage) {
    try {
      storage.setItem('@@', 1);
      storage.removeItem('@@');
      return true;
    } catch (e) {}

    return false;
  }

  function getState(key, storage, value) {
    try {
      return (value = storage.getItem(key)) && value !== 'undefined'
        ? JSON.parse(value)
        : undefined;
    } catch (err) {}

    return undefined;
  }

  function filter() {
    return true;
  }

  function setState(key, state, storage) {
    return storage.setItem(key, JSON.stringify(state));
  }

  function reducer(state, paths) {
    return paths.length === 0
      ? state
      : paths.reduce(function(substate, path) {
          return shvl.set(substate, path, shvl.get(state, path));
        }, {});
  }

  function subscriber(store) {
    return function(handler) {
      return store.subscribe(handler);
    };
  }

  if (!canWriteStorage(storage)) {
    throw new Error('Invalid storage instance given');
  }

  return function(store) {
    const savedState = shvl.get(options, 'getState', getState)(key, storage);

    if (typeof savedState === 'object' && savedState !== null) {
      store.replaceState(merge(store.state, savedState, {
        arrayMerge: options.arrayMerger || function (store, saved) { return saved },
        clone: false,
      }));
    }

    (options.subscriber || subscriber)(store)(function(mutation, state) {
      if ((options.filter || filter)(mutation)) {
        (options.setState || setState)(
          key,
          (options.reducer || reducer)(state, options.paths || []),
          storage
        );
      }
    });
  };
};
<commit_msg>Fix checking on undefined (#128)<commit_after>import merge from 'deepmerge';
import shvl from 'shvl';

export default function(options, storage, key) {
  options = options || {};
  storage = options.storage || (window && window.localStorage);
  key = options.key || 'vuex';

  function canWriteStorage(storage) {
    try {
      storage.setItem('@@', 1);
      storage.removeItem('@@');
      return true;
    } catch (e) {}

    return false;
  }

  function getState(key, storage, value) {
    try {
      return (value = storage.getItem(key)) && typeof value !== 'undefined'
        ? JSON.parse(value)
        : undefined;
    } catch (err) {}

    return undefined;
  }

  function filter() {
    return true;
  }

  function setState(key, state, storage) {
    return storage.setItem(key, JSON.stringify(state));
  }

  function reducer(state, paths) {
    return paths.length === 0
      ? state
      : paths.reduce(function(substate, path) {
          return shvl.set(substate, path, shvl.get(state, path));
        }, {});
  }

  function subscriber(store) {
    return function(handler) {
      return store.subscribe(handler);
    };
  }

  if (!canWriteStorage(storage)) {
    throw new Error('Invalid storage instance given');
  }

  return function(store) {
    const savedState = shvl.get(options, 'getState', getState)(key, storage);

    if (typeof savedState === 'object' && savedState !== null) {
      store.replaceState(merge(store.state, savedState, {
        arrayMerge: options.arrayMerger || function (store, saved) { return saved },
        clone: false,
      }));
    }

    (options.subscriber || subscriber)(store)(function(mutation, state) {
      if ((options.filter || filter)(mutation)) {
        (options.setState || setState)(
          key,
          (options.reducer || reducer)(state, options.paths || []),
          storage
        );
      }
    });
  };
};
<|endoftext|>


<commit_before>module.exports = {
  parseCategories     : parseCategories,
  fixPluginName       : fixPluginName,
  camelize            : camelize,
  fixPluginCategories : fixPluginCategories
}

/**
* @param {String} user's input
*/
function parseCategories(input) {
  this.options.categories = input.split(',');
}

/** Function that validate the Spinner name
* @returns {String}
*/
function fixPluginName(name, ReplaceSymbol) {
  name = name.toLowerCase().trim();
  return name.replace(/ /g, ReplaceSymbol);
}

/** Function that validate the Categories
* @returns {String}
*/
function fixPluginCategories(list) {
  list = list.replace(/ /g, '').toLowerCase().trim();
  var arrayCategories = list.split(',');
  return JSON.stringify(arrayCategories);
}

/** Function that converts a string into camel case using javascript regex
 * @author Christian C. Salvadó
 * @see http://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case
 * @param {string} user's input
 * @returns {string} camelCase
*/
function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter, index) {
    return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
  }).replace(/\s+/g, '');
}
<commit_msg>Direct copy method<commit_after>module.exports = {
  parseCategories     : parseCategories,
  fixPluginName       : fixPluginName,
  camelize            : camelize,
  fixPluginCategories : fixPluginCategories
}

/**
* @param {String} user's input
*/
function parseCategories(input) {
  this.options.categories = input.split(',');
}

/** Function that validate the Spinner name
* @returns {String}
*/
function fixPluginName(name, ReplaceSymbol) {
  name = name.toLowerCase().trim();
  return name.replace(/ /g, ReplaceSymbol);
}

/** Function that validate the Categories
* @returns {String}
*/
function fixPluginCategories(list) {
  list = list.replace(/ /g, '').toLowerCase().trim();
  var arrayCategories = list.split(',');
  return JSON.stringify(arrayCategories);
}

/** Function that converts a string into camel case using javascript regex
 * @author Christian C. Salvadó
 * @see http://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case
 * @param {string} user's input
 * @returns {string} camelCase
*/
function camelize(str) {
  return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter, index) {
    return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
  }).replace(/\s+/g, '');
}

/** Function direct copy files
* @param {object} this
* @param {object} input
* @param {array} relative location - files to copy
* @param {boolean} [false] internally it uses copy or copyTpl
*/
function directCopy(self, input, files, templated) {
  templated = templated || false;

  for (var i = files.length; i--;) {
    if (templated) {
      self.fs.copyTpl(
        self.templatePath(files[i]),
        self.destinationPath(files[i]),
        input
      );
    } else {
      self.fs.copy(
        self.templatePath(files[i]),
        self.destinationPath(files[i]),
        input
      );
    }
  }
}
<|endoftext|>


<commit_before>const chalk = require('chalk');

var NicerReporter = function (baseReporterDecorator, config, logger, helper, formatError) {
  baseReporterDecorator(this);
  function print(msg, color) {
    console.log(chalk[color](msg));
  };

  this.adapters = [function(msg) {
      process.stdout.write.bind(process.stdout)(msg + "\r\n");
  }];

  this.onRunStart = function (browsers) {
    this.write("IT'S ALIVE!");
  }

  this.onBrowserStart = function (browser) {
    //
    this.write("Running......");
  }

  this.specSuccess = function(browser, result) {
    //this.write(reporterConfig.successMsg)
  }

  this.specFailure = function(browser, result) {
    //this.write(reporterConfig.failureMsg)
  }

  this.onSpecComplete = function(browser, result) {
    print(result.description, 'green');
  }

  this.onRunComplete = function () {
    //Done
  }

}

NicerReporter.$inject = ['baseReporterDecorator', 'config', 'logger', 'helper', 'formatError']
module.exports = {
  'reporter:nicer': ['type', NicerReporter]
}

<commit_msg>Built the guts of it<commit_after>const chalk = require('chalk');

var NicerReporter = function (baseReporterDecorator, config, logger, helper, formatError) {
var log = logger.create('reporter.logical');

  var startPath = 'at ' + config.protocol + '//' + config.hostname + ':' + config.port + '/';
  var startPathLength = startPath.length;

  //Allow us to take parts from karma.conf.js logicalReporter section
  var reporterConfig = config.logicalReporter || {};
  var successColor = reporterConfig.successColor || 'green';
  var failColor = reporterConfig.failColor || 'red';
  var skipColor = reporterConfig.skipColor || 'yellow';
  var defaulColor = reporterConfig.defaulColor || 'cyan';
  var errorColor = reporterConfig.errorColor || 'white';
  /*
  black
  red
  green
  yellow
  blue (on Windows the bright version is used as normal blue is illegible)
  magenta
  cyan
  white
  gray
  */
  var groupedResults = {};
  var firstLinePrinted = false;

  baseReporterDecorator(this);

  this.adapters = [function(msg) {
    process.stdout.write.bind(process.stdout)(msg + "\r\n");
  }];

  function print(msg, color) {
    var color = color || defaulColor;
    console.log(chalk[color](msg));
  }

  function write(msg, color) {
    var color = color || defaulColor;
    process.stdout.write(chalk[color](msg));
  }

  this.onRunStart = function (browsers) {
  }

  this.onBrowserStart = function (browser) {
    //
    print('.');
    print('..');
    print('... running KARMA (with karma-logical-reporter)');
  }

  function printErrorLog(log) {
    for (var i=0, len=log.length; i<len; i++) {
      var logLines = log[i].split('\n');
      for (var i=0, len=logLines.length; i<len; i++) {
        var msg = logLines[i].trim() ;

        if (msg.startsWith(startPath)) {
          msg = msg.substr(startPathLength);
          var break1 = msg.indexOf('?');
          var filePart = msg.slice(0, break1);
          var break2 = msg.indexOf(':');
          var lineNumber = msg.substr(break2);
          msg = 'at ' + filePart +  ' line: ' + lineNumber;
        }
        print(msg, errorColor);
      }
    }
  }

  this.onSpecComplete = function(browser, result) {
    var suite = result.suite;
    if (groupedResults[suite] === undefined) {
      groupedResults[suite] = [];
    }
    groupedResults[suite].push(result);
    if (!result.success) {
      print('  ');
      if (!firstLinePrinted) {
        print('-----------------------------------------------', failColor);
        print('  ');
        firstLinePrinted = true;
      }
      print('Failure at:', failColor);
      print('  SUITE: ' + result.suite, failColor);
      print('  TEST:  ' + result.description, failColor);
      print('  ');
      printErrorLog(result.log);
      print('  ');
      print('-----------------------------------------------', failColor);
    }

  };

  this.onBrowserComplete = function (browser) {
    print('');
    suiteNames = Object.keys(groupedResults);
    suiteNames.sort();
    for (var i=0, len=suiteNames.length; i<len; i++) {
      var suiteName = suiteNames[i];
      printSuite(suiteName, groupedResults[suiteName]);
    }
    printSummary(browser);
  };

  function printSuite(suiteName, results) {
    var failed = 0;
    var skipped = 0;
    var success = 0;
    var printList = [];
    for (var i=0, len=results.length; i<len; i++) {
      var result = results[i];
      var text = '   ' + result.description;
      if (result.skipped) {
        skipped += 1;
      } else if (result.success) {
        success += 1;
      } else {
        failed += 1;
      }
    }

    function z(value) {
      if (value == 0) {
        return ' .'
      } else {
        return String("  " + value).slice(-2)
      }
    };

    function printHeader(outcome, color) {
      write(' ');
      write(z(success), successColor);
      write(' ');
      write(z(failed), failColor);
      write(' ');
      write(z(skipped), skipColor);
      write('  ');
      write(z(len));
      write('  ');
      write(outcome, color);
      write(' suite > ', color);
      write(suiteName , color);
      write('\r\n');
    }
    if (failed == 0) {
      if (skipped == 0) {
        printHeader('PASSED', successColor);
      } else {
        printHeader('UNSURE', skipColor);
      }
    } else {
      printHeader('FAILED', failColor);
    }
  };

  function printSummary(browser) {
    var scores = browser.lastResult;
    print(' ');
    print(browser.name);
    print(' ');
    //print('-------------------------------------');
    print('--------   Completed '  + scores.total + ' tests in ' + scores.totalTime + ' seconds   --------');
    //print('-------------'  + browser.name + '-------------');
    //print('Summary for ' + scores.total + ' tests in ' + scores.totalTime + ' seconds:');
    print('  ');
    write('          PASS: ' + scores.success, successColor);
    write('    FAIL: ' + scores.failed, failColor);
    write('    SKIP: ' + scores.skipped, skipColor);
    print('  ');
  }

  this.onRunComplete = function () {
    //
  }

}

NicerReporter.$inject = ['baseReporterDecorator', 'config', 'logger', 'helper', 'formatError']
module.exports = {
  'reporter:nicer': ['type', NicerReporter]
}

<|endoftext|>


<commit_before>'use strict';

var cssauron = require('cssauron');
var code = require('yields-keycode');

var PD = '//';

function identity(thing) {
  return thing;
}

function isString(thing) {
  return typeof thing === 'string';
}

function isNumber(thing) {
  return typeof thing === 'number';
}

function isArray(thing) {
  return Object.prototype.toString.call(thing) === '[object Array]';
}

function isModule(thing) {
  return  thing && typeof thing === 'object' && thing.controller && thing.view;
}

function isFuction(thing) {
  return typeof thing === 'function';
}

function call(thing) {
  return thing();
}

var language = cssauron({
  tag: 'tag',
  contents: function(node) {
    if (isString(node.children)) {
      return node.children;
    }
    return isArray(node.children) ? node.children.filter(isString).concat('') : '';
  },
  id: function(node) {
    if (node.attrs) {
      return node.attrs.id;
    }
    return '';
  },
  class: function(node) {
    if (node.attrs) {
      return node.attrs.className;
    }
    return '';
  },
  parent: 'parent',
  children: function(node) {
    return node.children.filter(identity);
  },
  attr: function(node, attr) {
    if (node.attrs) {
      return node.attrs[attr];
    }
  }
});

function join(arrays) {
  return arrays.reduce(function(result, array) {
    return result.concat(array);
  }, []);
}

function scan(render) {
  var api = {
    rootEl: render(),
    onunloaders: []
  };

  var scopes = {};

  function find(selectorString, el) {
    return select(language(selectorString))(el);
  }

  function select(matchesSelector) {
    return function matches(el, treePath) {
      treePath = treePath || '';
      if (isArray(el)) {
        return join(el.filter(identity).map(function(childEl, index) {
          return matches(childEl, treePath + PD + (childEl.key || index));
        }));
      }
      var foundEls = [];
      if (!el) {
        return foundEls;
      }
      if (isModule(el)) {
        scopes[treePath] = scopes[treePath] || el.controller();
        if (scopes[treePath]) {
          api.onunloaders.push(scopes[treePath].onunload);
        }
        el = el.view(scopes[treePath]);
      }
      if (matchesSelector(el)) {
        foundEls.push(el);
      }
      if (!el.children || isString(el.children)) {
        return foundEls;
      }
      el.children.filter(identity).forEach(function(child) {
        child.parent = el;
      });
      return foundEls.concat(matches(el.children, treePath));
    };
  }

  function first(selector) {
    var el = find(selector, api.rootEl)[0];
    if (!el) {
      throw new Error('No element matches ' + selector);
    }
    return el;
  }

  function has(selector) {
    return find(selector, api.rootEl).length > 0;
  }

  function contains(value, el) {
    if (isModule(el)) {
      var scope;
      if (el.controller) {
        scope = el.controller();
        if (scope && scope.onunload) {
          api.onunloaders.push(scope.onunload);
        }
      }
      el = el.view(scope);
    }
    if (!el) {
      return false;
    }
    if (isString(el)) {
      return el.indexOf(value) >= 0;
    }
    if (isString(el.children)) {
      return el.children.indexOf(value) >= 0;
    }
    if (isNumber(el)) {
      return el === value;
    }
    if (isNumber(el.children)) {
      return el.children === value;
    }
    if (isArray(el)) {
      return el.some(function(child) {
        return contains(value, child);
      });
    }
    if (el.children && el.children.length) {
      return el.children.some(function(child) {
        return contains(value, child);
      });
    }
    return false;
  }

  function shouldHaveAtLeast(minCount, selector) {
    var actualCount = find(selector, api.rootEl).length;
    if (actualCount < minCount) {
      throw new Error('Wrong count of elements that matches "' + selector +
            '"\n  expected: >=' + minCount + '\n  actual: ' + actualCount);
    }
  }

  function shouldHave(expectedCount, selector) {
    if (!selector) {
      return shouldHaveAtLeast(1, expectedCount);
    }
    var actualCount = find(selector, api.rootEl).length;
    if (actualCount !== expectedCount) {
      throw new Error('Wrong count of elements that matches "' + selector +
            '"\n  expected: ' + expectedCount + '\n  actual: ' + actualCount);
    }
  }

  function shouldNotHave(selector) {
    shouldHave(0, selector);
  }

  function shouldContain(string) {
    if (!contains(string, api.rootEl)) {
      throw new Error('Expected "' + string + '" not found!');
    }
  }

  function shouldNotContain(string) {
    if (contains(string, api.rootEl)) {
      throw new Error('Unexpected "' + string + '" found!');
    }
  }

  function setValue(selector, string, silent) {
    var attrs = first(selector).attrs;
    var event = {
      currentTarget: {value: string},
      target: {value: string}
    };
    attrs.oninput && attrs.oninput(event);
    attrs.onchange && attrs.onchange(event);
    attrs.onkeyup && attrs.onkeyup(event);
    silent || api.redraw();
  }

  function trigger(eventName) {
    return function (selector, event, silent) {
      var attrs = first(selector).attrs;
      attrs['on' + eventName](event);
      silent || api.redraw();
    };
  }

  function triggerKey(eventName) {
    var fire = trigger(eventName);
    return function keydown(selector, key, silent) {
      fire(selector, {
        keyCode: isString(key) ? code(key) : key
      }, silent);
    };
  }

  shouldHave.at = {
    least: shouldHaveAtLeast
  };

  api.redraw = function() {
    api.rootEl = render();
    return api;
  };
  api.first = first;
  api.has = has;
  api.contains = function(value) {
    return contains(value, api.rootEl);
  };
  api.find = function(selector) {
    return find(selector, api.rootEl);
  };
  api.setValue = setValue;
  ['focus', 'click', 'blur', 'mousedown', 'mouseup', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'].map(function(eventName) {
    api[eventName] = trigger(eventName);
  });
  api.keydown = triggerKey('keydown');
  api.keypress = triggerKey('keypress');
  api.keyup = triggerKey('keyup');
  api.should = {
    not: {
      have: shouldNotHave,
      contain: shouldNotContain,
    },
    have: shouldHave,
    contain: shouldContain
  };
  return api;
}

function init(viewOrModuleOrRootEl, scope, b, c, d, e, f, noWay) {
  if (noWay) {
    throw new Error('More than 6 args of a component? Seriously? Such bad style is not supported.');
  }
  var api = {};
  var isViewFunction = typeof viewOrModuleOrRootEl === 'function';
  if (isViewFunction) {
    api = scan(function() {
      return viewOrModuleOrRootEl(scope);
    });
    if (scope) {
      api.onunloaders.push(scope.onunload);
    }
  } else if (isModule(viewOrModuleOrRootEl)) {
    var a = scope;
    scope = new viewOrModuleOrRootEl.controller(a, b, c, d, e, f);
    api = scan(function() {
      return viewOrModuleOrRootEl.view(scope, a, b, c, d, e, f);
    });
    if (scope) {
      api.onunloaders.push(scope.onunload);
    }
  } else {
    // assume that first argument is rendered view
    api = scan(function() {
      return viewOrModuleOrRootEl;
    });
  }
  api.onunload = function() {
    api.onunloaders.filter(isFuction).map(call);
  };
  return api;
}

module.exports = init;
<commit_msg>fix #9<commit_after>'use strict';

var cssauron = require('cssauron');
var code = require('yields-keycode');

var PD = '//';

function identity(thing) {
  return thing;
}

function isString(thing) {
  return typeof thing === 'string';
}

function isNumber(thing) {
  return typeof thing === 'number';
}

function isArray(thing) {
  return Object.prototype.toString.call(thing) === '[object Array]';
}

function isModule(thing) {
  return  thing && typeof thing === 'object' && thing.controller && thing.view;
}

function isFuction(thing) {
  return typeof thing === 'function';
}

function call(thing) {
  return thing();
}

var language = cssauron({
  tag: 'tag',
  contents: function(node) {
    if (isString(node.children)) {
      return node.children;
    }
    return isArray(node.children) ? node.children.filter(isString).concat('') : '';
  },
  id: function(node) {
    if (node.attrs) {
      return node.attrs.id;
    }
    return '';
  },
  class: function(node) {
    if (node.attrs) {
      return node.attrs.className;
    }
    return '';
  },
  parent: 'parent',
  children: function(node) {
    return node.children.filter(identity);
  },
  attr: function(node, attr) {
    if (node.attrs) {
      return node.attrs[attr];
    }
  }
});

function join(arrays) {
  return arrays.reduce(function(result, array) {
    return result.concat(array);
  }, []);
}

function scan(render) {
  var api = {
    rootEl: render(),
    onunloaders: []
  };

  var scopes = {};

  function find(selectorString, el) {
    return select(language(selectorString))(el);
  }

  function select(matchesSelector) {
    return function matches(el, treePath) {
      treePath = treePath || '';
      if (isArray(el)) {
        return join(el.filter(identity).map(function(childEl, index) {
          return matches(childEl, treePath + PD + (childEl.key || index));
        }));
      }
      var foundEls = [];
      if (!el) {
        return foundEls;
      }
      if (isModule(el)) {
        scopes[treePath] = scopes[treePath] || el.controller();
        if (scopes[treePath]) {
          api.onunloaders.push(scopes[treePath].onunload);
        }
        el = el.view(scopes[treePath]);
      }
      if (matchesSelector(el)) {
        foundEls.push(el);
      }
      if (!el.children || isString(el.children)) {
        return foundEls;
      }
      var children = el.children.filter(identity).map(function(child) {
        if (typeof(child) === 'object') {
          child.parent = el;
        }
        return child
      });
      return foundEls.concat(matches(children, treePath));
    };
  }

  function first(selector) {
    var el = find(selector, api.rootEl)[0];
    if (!el) {
      throw new Error('No element matches ' + selector);
    }
    return el;
  }

  function has(selector) {
    return find(selector, api.rootEl).length > 0;
  }

  function contains(value, el) {
    if (isModule(el)) {
      var scope;
      if (el.controller) {
        scope = el.controller();
        if (scope && scope.onunload) {
          api.onunloaders.push(scope.onunload);
        }
      }
      el = el.view(scope);
    }
    if (!el) {
      return false;
    }
    if (isString(el)) {
      return el.indexOf(value) >= 0;
    }
    if (isString(el.children)) {
      return el.children.indexOf(value) >= 0;
    }
    if (isNumber(el)) {
      return el === value;
    }
    if (isNumber(el.children)) {
      return el.children === value;
    }
    if (isArray(el)) {
      return el.some(function(child) {
        return contains(value, child);
      });
    }
    if (el.children && el.children.length) {
      return el.children.some(function(child) {
        return contains(value, child);
      });
    }
    return false;
  }

  function shouldHaveAtLeast(minCount, selector) {
    var actualCount = find(selector, api.rootEl).length;
    if (actualCount < minCount) {
      throw new Error('Wrong count of elements that matches "' + selector +
            '"\n  expected: >=' + minCount + '\n  actual: ' + actualCount);
    }
  }

  function shouldHave(expectedCount, selector) {
    if (!selector) {
      return shouldHaveAtLeast(1, expectedCount);
    }
    var actualCount = find(selector, api.rootEl).length;
    if (actualCount !== expectedCount) {
      throw new Error('Wrong count of elements that matches "' + selector +
            '"\n  expected: ' + expectedCount + '\n  actual: ' + actualCount);
    }
  }

  function shouldNotHave(selector) {
    shouldHave(0, selector);
  }

  function shouldContain(string) {
    if (!contains(string, api.rootEl)) {
      throw new Error('Expected "' + string + '" not found!');
    }
  }

  function shouldNotContain(string) {
    if (contains(string, api.rootEl)) {
      throw new Error('Unexpected "' + string + '" found!');
    }
  }

  function setValue(selector, string, silent) {
    var attrs = first(selector).attrs;
    var event = {
      currentTarget: {value: string},
      target: {value: string}
    };
    attrs.oninput && attrs.oninput(event);
    attrs.onchange && attrs.onchange(event);
    attrs.onkeyup && attrs.onkeyup(event);
    silent || api.redraw();
  }

  function trigger(eventName) {
    return function (selector, event, silent) {
      var attrs = first(selector).attrs;
      attrs['on' + eventName](event);
      silent || api.redraw();
    };
  }

  function triggerKey(eventName) {
    var fire = trigger(eventName);
    return function keydown(selector, key, silent) {
      fire(selector, {
        keyCode: isString(key) ? code(key) : key
      }, silent);
    };
  }

  shouldHave.at = {
    least: shouldHaveAtLeast
  };

  api.redraw = function() {
    api.rootEl = render();
    return api;
  };
  api.first = first;
  api.has = has;
  api.contains = function(value) {
    return contains(value, api.rootEl);
  };
  api.find = function(selector) {
    return find(selector, api.rootEl);
  };
  api.setValue = setValue;
  ['focus', 'click', 'blur', 'mousedown', 'mouseup', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'].map(function(eventName) {
    api[eventName] = trigger(eventName);
  });
  api.keydown = triggerKey('keydown');
  api.keypress = triggerKey('keypress');
  api.keyup = triggerKey('keyup');
  api.should = {
    not: {
      have: shouldNotHave,
      contain: shouldNotContain,
    },
    have: shouldHave,
    contain: shouldContain
  };
  return api;
}

function init(viewOrModuleOrRootEl, scope, b, c, d, e, f, noWay) {
  if (noWay) {
    throw new Error('More than 6 args of a component? Seriously? Such bad style is not supported.');
  }
  var api = {};
  var isViewFunction = typeof viewOrModuleOrRootEl === 'function';
  if (isViewFunction) {
    api = scan(function() {
      return viewOrModuleOrRootEl(scope);
    });
    if (scope) {
      api.onunloaders.push(scope.onunload);
    }
  } else if (isModule(viewOrModuleOrRootEl)) {
    var a = scope;
    scope = new viewOrModuleOrRootEl.controller(a, b, c, d, e, f);
    api = scan(function() {
      return viewOrModuleOrRootEl.view(scope, a, b, c, d, e, f);
    });
    if (scope) {
      api.onunloaders.push(scope.onunload);
    }
  } else {
    // assume that first argument is rendered view
    api = scan(function() {
      return viewOrModuleOrRootEl;
    });
  }
  api.onunload = function() {
    api.onunloaders.filter(isFuction).map(call);
  };
  return api;
}

module.exports = init;
<|endoftext|>


<commit_before>var walkSync = require('walk-sync');
var Plugin = require('broccoli-plugin');
var UglifyJS = require('uglify-js');
var path = require('path');
var fs = require('fs');
var merge = require('lodash.merge');
var symlinkOrCopy = require('symlink-or-copy');
var mkdirp = require('mkdirp');
var srcURL = require('source-map-url');
var MatcherCollection = require('matcher-collection');
var debug = require('debug')('broccoli-uglify-sourcemap');

module.exports = UglifyWriter;

UglifyWriter.prototype = Object.create(Plugin.prototype);
UglifyWriter.prototype.constructor = UglifyWriter;

function UglifyWriter (inputNodes, options) {
  if (!(this instanceof UglifyWriter)) {
    return new UglifyWriter(inputNodes, options);
  }

  inputNodes = Array.isArray(inputNodes) ? inputNodes : [inputNodes];

  Plugin.call(this, inputNodes, options);
  this.options = merge({
    mangle: true,
    compress: true,
    sourceMapIncludeSources: true
  }, options);

  this.sourceMapConfig = merge({
    enabled: true,
    extensions: ['js']
  }, this.options.sourceMapConfig);

  this.inputNodes = inputNodes;

  var exclude = this.options.exclude;
  if (Array.isArray(exclude)) {
    this.excludes = new MatcherCollection(exclude);
  } else {
    this.excludes = MatchNothing;
  }
}

var MatchNothing = {
  match: function () {
    return false;
  }
};

UglifyWriter.prototype.build = function () {
  var writer = this;

  this.inputPaths.forEach(function(inputPath) {
    walkSync(inputPath).forEach(function(relativePath) {
      if (relativePath.slice(-1) === '/') {
        return;
      }
      var inFile = path.join(inputPath, relativePath);
      var outFile = path.join(writer.outputPath, relativePath);

      mkdirp.sync(path.dirname(outFile));

      if (relativePath.slice(-3) === '.js' && !writer.excludes.match(relativePath)) {
        writer.processFile(inFile, outFile, relativePath, writer.outputPath);
      } else if (relativePath.slice(-4) === '.map') {
        if (writer.excludes.match(relativePath.slice(0, -4) + '.js')) {
          // ensure .map files for excldue JS paths are also copied forward
          symlinkOrCopy.sync(inFile, outFile);
        }
        // skip, because it will get handled when its corresponding JS does
      } else {
        symlinkOrCopy.sync(inFile, outFile);
      }
    });
  });

  return this.outputPath;
};

UglifyWriter.prototype.enableSourcemaps = function() {
  return this.sourceMapConfig.enabled &&
    this.sourceMapConfig.extensions.indexOf('js') > -1;
};

UglifyWriter.prototype.mapURL = function(mapName) {
  if (this.enableSourcemaps()) {
    if (this.sourceMapConfig.mapDir) {
      return '/' + path.join(this.sourceMapConfig.mapDir, mapName);
    } else {
      return mapName;
    }
  }
};

UglifyWriter.prototype.processFile = function(inFile, outFile, relativePath, outDir) {
  var src = fs.readFileSync(inFile, 'utf-8');
  var mapName = path.basename(outFile).replace(/\.js$/,'') + '.map';
  var mapDir;
  var origSourcesContent;

  if (this.sourceMapConfig.mapDir) {
    mapDir = path.join(outDir, this.sourceMapConfig.mapDir);
  } else {
    mapDir = path.dirname(path.join(outDir, relativePath));
  }

  var opts = {
    fromString: true,
    outSourceMap: this.mapURL(mapName),
    enableSourcemaps: this.enableSourcemaps()
  };

  if (opts.enableSourcemaps && srcURL.existsIn(src)) {
    var url = srcURL.getFrom(src);
    opts.inSourceMap = path.join(path.dirname(inFile), url);
    origSourcesContent = JSON.parse(fs.readFileSync(opts.inSourceMap)).sourcesContent;
  }

  try {
    var start = new Date();
    debug('[starting]: %s %dKB', relativePath, (src.length / 1000));
    var result = UglifyJS.minify(src, merge(opts, this.options));
    var end = new Date();
    var total = end - start;
    debug('[finsihed]: %s %dKB in %dms', relativePath, (result.code.length / 1000), total);

    if (total > 20000) {
      console.warn('[WARN] `' + relativePath + '` took: ' + total + 'ms (more than 20,000ms)');
    }

  } catch(e) {
    e.filename = relativePath;
    throw e;
  }

  if (opts.enableSourcemaps) {
    var newSourceMap = JSON.parse(result.map);

    if (origSourcesContent) {
      // This is a workaround for https://github.com/mishoo/UglifyJS2/pull/566
      newSourceMap.sourcesContent = origSourcesContent;
    } else {
      newSourceMap.sources = [ relativePath ];
      newSourceMap.sourcesContent = [ src ];
    }

    // uglify is wrong about this and always puts the maps own name
    // here.
    newSourceMap.file = path.basename(inFile);

    newSourceMap.sources = newSourceMap.sources.map(function(path){
      // If out output file has the same name as one of our original
      // sources, they will shadow eachother in Dev Tools. So instead we
      // alter the reference to the upstream file.
      if (path === relativePath) {
        path = path.replace(/\.js$/, '-orig.js');
      }
      return path;
    });
    mkdirp.sync(mapDir);
    fs.writeFileSync(path.join(mapDir, mapName), JSON.stringify(newSourceMap));
  }
  fs.writeFileSync(outFile, result.code);
};
<commit_msg>fix minor typo<commit_after>var walkSync = require('walk-sync');
var Plugin = require('broccoli-plugin');
var UglifyJS = require('uglify-js');
var path = require('path');
var fs = require('fs');
var merge = require('lodash.merge');
var symlinkOrCopy = require('symlink-or-copy');
var mkdirp = require('mkdirp');
var srcURL = require('source-map-url');
var MatcherCollection = require('matcher-collection');
var debug = require('debug')('broccoli-uglify-sourcemap');

module.exports = UglifyWriter;

UglifyWriter.prototype = Object.create(Plugin.prototype);
UglifyWriter.prototype.constructor = UglifyWriter;

function UglifyWriter (inputNodes, options) {
  if (!(this instanceof UglifyWriter)) {
    return new UglifyWriter(inputNodes, options);
  }

  inputNodes = Array.isArray(inputNodes) ? inputNodes : [inputNodes];

  Plugin.call(this, inputNodes, options);
  this.options = merge({
    mangle: true,
    compress: true,
    sourceMapIncludeSources: true
  }, options);

  this.sourceMapConfig = merge({
    enabled: true,
    extensions: ['js']
  }, this.options.sourceMapConfig);

  this.inputNodes = inputNodes;

  var exclude = this.options.exclude;
  if (Array.isArray(exclude)) {
    this.excludes = new MatcherCollection(exclude);
  } else {
    this.excludes = MatchNothing;
  }
}

var MatchNothing = {
  match: function () {
    return false;
  }
};

UglifyWriter.prototype.build = function () {
  var writer = this;

  this.inputPaths.forEach(function(inputPath) {
    walkSync(inputPath).forEach(function(relativePath) {
      if (relativePath.slice(-1) === '/') {
        return;
      }
      var inFile = path.join(inputPath, relativePath);
      var outFile = path.join(writer.outputPath, relativePath);

      mkdirp.sync(path.dirname(outFile));

      if (relativePath.slice(-3) === '.js' && !writer.excludes.match(relativePath)) {
        writer.processFile(inFile, outFile, relativePath, writer.outputPath);
      } else if (relativePath.slice(-4) === '.map') {
        if (writer.excludes.match(relativePath.slice(0, -4) + '.js')) {
          // ensure .map files for excldue JS paths are also copied forward
          symlinkOrCopy.sync(inFile, outFile);
        }
        // skip, because it will get handled when its corresponding JS does
      } else {
        symlinkOrCopy.sync(inFile, outFile);
      }
    });
  });

  return this.outputPath;
};

UglifyWriter.prototype.enableSourcemaps = function() {
  return this.sourceMapConfig.enabled &&
    this.sourceMapConfig.extensions.indexOf('js') > -1;
};

UglifyWriter.prototype.mapURL = function(mapName) {
  if (this.enableSourcemaps()) {
    if (this.sourceMapConfig.mapDir) {
      return '/' + path.join(this.sourceMapConfig.mapDir, mapName);
    } else {
      return mapName;
    }
  }
};

UglifyWriter.prototype.processFile = function(inFile, outFile, relativePath, outDir) {
  var src = fs.readFileSync(inFile, 'utf-8');
  var mapName = path.basename(outFile).replace(/\.js$/,'') + '.map';
  var mapDir;
  var origSourcesContent;

  if (this.sourceMapConfig.mapDir) {
    mapDir = path.join(outDir, this.sourceMapConfig.mapDir);
  } else {
    mapDir = path.dirname(path.join(outDir, relativePath));
  }

  var opts = {
    fromString: true,
    outSourceMap: this.mapURL(mapName),
    enableSourcemaps: this.enableSourcemaps()
  };

  if (opts.enableSourcemaps && srcURL.existsIn(src)) {
    var url = srcURL.getFrom(src);
    opts.inSourceMap = path.join(path.dirname(inFile), url);
    origSourcesContent = JSON.parse(fs.readFileSync(opts.inSourceMap)).sourcesContent;
  }

  try {
    var start = new Date();
    debug('[starting]: %s %dKB', relativePath, (src.length / 1000));
    var result = UglifyJS.minify(src, merge(opts, this.options));
    var end = new Date();
    var total = end - start;
    debug('[finished]: %s %dKB in %dms', relativePath, (result.code.length / 1000), total);

    if (total > 20000) {
      console.warn('[WARN] `' + relativePath + '` took: ' + total + 'ms (more than 20,000ms)');
    }

  } catch(e) {
    e.filename = relativePath;
    throw e;
  }

  if (opts.enableSourcemaps) {
    var newSourceMap = JSON.parse(result.map);

    if (origSourcesContent) {
      // This is a workaround for https://github.com/mishoo/UglifyJS2/pull/566
      newSourceMap.sourcesContent = origSourcesContent;
    } else {
      newSourceMap.sources = [ relativePath ];
      newSourceMap.sourcesContent = [ src ];
    }

    // uglify is wrong about this and always puts the maps own name
    // here.
    newSourceMap.file = path.basename(inFile);

    newSourceMap.sources = newSourceMap.sources.map(function(path){
      // If out output file has the same name as one of our original
      // sources, they will shadow eachother in Dev Tools. So instead we
      // alter the reference to the upstream file.
      if (path === relativePath) {
        path = path.replace(/\.js$/, '-orig.js');
      }
      return path;
    });
    mkdirp.sync(mapDir);
    fs.writeFileSync(path.join(mapDir, mapName), JSON.stringify(newSourceMap));
  }
  fs.writeFileSync(outFile, result.code);
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Odometer from 'odometer';

class ReactOdometer extends React.Component {
  static propTypes = {
    value: PropTypes.number.isRequired,
    options: PropTypes.object,
  };

  componentDidMount() {
    this.odometer = new Odometer({
      el: ReactDOM.findDOMNode(this),
      value: this.props.value,
      ...this.props.options,
    });
  }

  componentDidUpdate() {
    this.odometer.update(this.props.value);
  }

  render() {
    return React.createElement('div');
  }
}

export default ReactOdometer;
<commit_msg>Just export default class<commit_after>import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import Odometer from 'odometer';

export default class ReactOdometer extends React.Component {
  static propTypes = {
    value: PropTypes.number.isRequired,
    options: PropTypes.object,
  };

  componentDidMount() {
    this.odometer = new Odometer({
      el: ReactDOM.findDOMNode(this),
      value: this.props.value,
      ...this.props.options,
    });
  }

  componentDidUpdate() {
    this.odometer.update(this.props.value);
  }

  render() {
    return React.createElement('div');
  }
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var now = require('mout/time/now');
var gm = require('googlemaps');
var util = require('util');

var ACValidater = require('./js/acvalidater.js');
var validator = new ACValidater();

var ACViper = require('./js/acviper.js');
var viper = new ACViper();

app.use(express.static(__dirname + '/public'));

function transact(data){
    console.log("trans: [" + data.request + "]");
    console.log("plate number: [" + data.price + "]");
    viper.logRequest(data);
    if ( "buy" == data.request){
        viper.findMatch(data, "sell", buyerSearchCB);
    }
    if ( "sell" == data.request){
        viper.findMatch(data, "buy", sellerSearchCB);
    }
} // END transact()

function validate(data){
    var result = {
        success: true,
	address: "valid",
	phone_number: "valid",
	plate_number: "valid",
	price: "valid"
    };
    if (!validator.phoneNumber(data.phone_number)){
        result.success=false;
        result.phone_number="invalid";
    }
    if (!validator.isNumber(data.price)){
        result.success=false;
        result.price="invalid";
    }

    /*
    if (!validator.isAddress("Hillcrest", data.address)){
        result.success=false;
        result.address="invalid";
    }
    */

    if (!validator.isAlphaNumber(data.plate_number)){
        result.success=false;
        result.plate_number="invalid";
    }

    return result;
} // END validate()

function startProcessing(data){
    gm.geocode(data.address, function(err, addy){
	valid=validate(data);
        util.puts(JSON.stringify(data));
	if ( ! valid.success ){
    	    console.log("Validation FAIL.");
            io.sockets.emit('fail',  valid );
	    return;
        }
	transact(data);
    });
} // END startProcessing()
	// TODO: ADD lat and lng here...
/*
	if (validate.inNeighborhood("Hillcrest", addy)) {
	    console.log("in neighborhood");
	    transact(data);
	}
        else{
	    console.log("NOT in neighborhood");
            io.sockets.emit('fail',  valid );
	}
*/

io.on('connection', function (socket) {
    console.log("Connection!!");

    socket.on('transaction', function (data) {
	startProcessing(data);

	valid=validate(data);
        if ( ! valid.success ){
    	    console.log("Validation FAIL.");
            io.sockets.emit('fail',  valid );
	    return;
        }
	transact(data);

        return;
    }); // END socket.on('transaction');
}); // END io.on()

/* Searcher is seller
 * which means they searched for a "buy" match. */
function sellerSearchCB(err, result){
    if ( null != result ){
	console.log("Success: [" + result.address + "]");
        result.lat=32.749393;
        result.lng=-117.162453;
        console.log("lat: " + result.lat + " lng: " + result.lng);
        io.sockets.emit('success',  result );
    }
    else{
	console.log("Fail.");
        io.sockets.emit('failed',  result );
        return;
    }

} // END sellerSearchCB()

function buyerSearchCB(err, result){
     if ( null != result ){
	console.log("Success: [" + result.address + "]");
        result.lat=32.749393;
        result.lng=-117.162453;
        console.log("lat: " + result.lat + " lng: " + result.lng);
        io.sockets.emit('success',  result );
    }
    else{
	console.log("Fail.");
        io.sockets.emit('failed',  result );
        return;
    }
} // END buyerSerachCB()

console.log("Autocrest Started");

server.listen(process.env.PORT || 3000);
<commit_msg>Minor bug fixes.<commit_after>var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var now = require('mout/time/now');
var gm = require('googlemaps');
var util = require('util');

var ACValidater = require('./js/acvalidater.js');
var validator = new ACValidater();

var ACViper = require('./js/acviper.js');
var viper = new ACViper();

app.use(express.static(__dirname + '/public'));

function transact(data){
    console.log("trans: [" + data.request + "]");
    console.log("plate number: [" + data.price + "]");
    viper.logRequest(data);
    if ( "buy" == data.request){
        viper.findMatch(data, "sell", buyerSearchCB);
    }
    if ( "sell" == data.request){
        viper.findMatch(data, "buy", sellerSearchCB);
    }
} // END transact()

function validate(data){
    var result = {
        success: true,
	address: "valid",
	phone_number: "valid",
	plate_number: "valid",
	price: "valid"
    };
    if (!validator.phoneNumber(data.phone_number)){
        result.success=false;
        result.phone_number="invalid";
    }
    if (!validator.isNumber(data.price)){
        result.success=false;
        result.price="invalid";
    }

    /*
    if (!validator.isAddress("Hillcrest", data.address)){
        result.success=false;
        result.address="invalid";
    }
    */

    if (!validator.isAlphaNumber(data.plate_number)){
        result.success=false;
        result.plate_number="invalid";
    }

    return result;
} // END validate()

function startProcessing(data){
    gm.geocode(data.address, function(err, addy){
	console.log("error: [%s]", err);
	if (! null == err){
    	    console.log("addy lookup fail");
            io.sockets.emit('fail',  valid );
	    return;
	}
	console.log("data: [%s]", addy);
        util.puts(JSON.stringify(addy));
	data.neighborhood=JSON.stringify(addy.results[0].address_components[2].long_name).replace(/"/g, "");
	console.log("neighborhood: [%s]", data.neighborhood);
	valid=validate(data);
	if ( ! valid.success ){
    	    console.log("Validation FAIL.");
            io.sockets.emit('fail',  valid );
	    return;
        }
	transact(data);
    });
} // END startProcessing()
	// TODO: ADD lat and lng here...
/*
	if (validate.inNeighborhood("Hillcrest", addy)) {
	    console.log("in neighborhood");
	    transact(data);
	}
        else{
	    console.log("NOT in neighborhood");
            io.sockets.emit('fail',  valid );
	}
*/

io.on('connection', function (socket) {
    console.log("Connection!!");

    socket.on('transaction', function (data) {
	startProcessing(data);
        return;
    }); // END socket.on('transaction');
}); // END io.on()

/* Searcher is seller
 * which means they searched for a "buy" match. */
function sellerSearchCB(err, result){
    if ( null != result ){
	console.log("Success: [" + result.address + "]");
        result.lat=32.749393;
        result.lng=-117.162453;
        console.log("lat: " + result.lat + " lng: " + result.lng);
        io.sockets.emit('success',  result );
    }
    else{
	console.log("Fail.");
        io.sockets.emit('failed',  result );
        return;
    }

} // END sellerSearchCB()

function buyerSearchCB(err, result){
     if ( null != result ){
	console.log("Success: [" + result.address + "]");
        result.lat=32.749393;
        result.lng=-117.162453;
        console.log("lat: " + result.lat + " lng: " + result.lng);
        io.sockets.emit('success',  result );
    }
    else{
	console.log("Fail.");
        io.sockets.emit('failed',  result );
        return;
    }
} // END buyerSerachCB()

console.log("Autocrest Started");

server.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>var path = require('path');
var fs   = require('fs');

function EmberCLISimpleAuth(project) {
  this.project = project;
  this.name    = 'Ember CLI Simple Auth';
}

function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
}

EmberCLISimpleAuth.prototype.treeFor = function included(name) {
  var treePath = path.join('node_modules/ember-cli-simple-auth', name + '-addon');

  if (fs.existsSync(treePath)) {
    return unwatchedTree(treePath);
  }
};

EmberCLISimpleAuth.prototype.included = function included(app) {
  this.app = app;

  this.app.import('vendor/ember-simple-auth/simple-auth.amd.js', {
    'simple-auth/authenticators/base':                    ['default'],
    'simple-auth/authorizers/base':                       ['default'],
    'simple-auth/mixins/application-route-mixin':         ['default'],
    'simple-auth/mixins/authenticated-route-mixin':       ['default'],
    'simple-auth/mixins/authentication-controller-mixin': ['default'],
    'simple-auth/mixins/login-controller-mixin':          ['default'],
    'simple-auth/stores/base':                            ['default'],
    'simple-auth/stores/ephemeral':                       ['default'],
    'simple-auth/stores/local-storage':                   ['default'],
    'simple-auth/configuration':                          ['default'],
    'simple-auth/initializer':                            ['default']
  });
};

module.exports = EmberCLISimpleAuth;
<commit_msg>add simple-auth/session to app import<commit_after>var path = require('path');
var fs   = require('fs');

function EmberCLISimpleAuth(project) {
  this.project = project;
  this.name    = 'Ember CLI Simple Auth';
}

function unwatchedTree(dir) {
  return {
    read:    function() { return dir; },
    cleanup: function() { }
  };
}

EmberCLISimpleAuth.prototype.treeFor = function included(name) {
  var treePath = path.join('node_modules/ember-cli-simple-auth', name + '-addon');

  if (fs.existsSync(treePath)) {
    return unwatchedTree(treePath);
  }
};

EmberCLISimpleAuth.prototype.included = function included(app) {
  this.app = app;

  this.app.import('vendor/ember-simple-auth/simple-auth.amd.js', {
    'simple-auth/authenticators/base':                    ['default'],
    'simple-auth/authorizers/base':                       ['default'],
    'simple-auth/mixins/application-route-mixin':         ['default'],
    'simple-auth/mixins/authenticated-route-mixin':       ['default'],
    'simple-auth/mixins/authentication-controller-mixin': ['default'],
    'simple-auth/mixins/login-controller-mixin':          ['default'],
    'simple-auth/stores/base':                            ['default'],
    'simple-auth/stores/ephemeral':                       ['default'],
    'simple-auth/stores/local-storage':                   ['default'],
    'simple-auth/session':                                ['default'],
    'simple-auth/configuration':                          ['default'],
    'simple-auth/initializer':                            ['default']
  });
};

module.exports = EmberCLISimpleAuth;
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* Copyright (c) 2018 Looker Data Sciences, Inc. See https://github.com/looker-open-source/look-at-me-sideways/blob/master/LICENSE.txt */
const defaultConsole = console
const defaultProcess = process
/**
 * LAMS main function
 *
 * @param {object}	options - options
 * @param {object}	options.cwd - Override the current working directory
 * @param {string=}	options.reporting - One of yes, no, save-yes, or save-no. Program terminates with a warning if omitted. See PRIVACY.md for details
 * @param {string=}	options.reportLicenseKey - Optional Looker License Key. See PRIVACY.md for details
 * @param {string=}	options.reportUser - Optional user email address. See PRIVACY.md for details
 * @param {string=}	options.source - An optional glob specifying which files to read
 * @param {string=}	options.projectName - An optional name for the project, used to generate links back to the project in mardown output
 * @param {*=}		options.allowCustomRules - Experimental option. DO NOT USE TO RUN UNTRUSTED CODE. Pass a value to allow running of externally defined JS for custom rules
 * @param {*=}		options.jenkins - Set to indicate that LAMS is being run by Jenkins and to include the build URL from ENV variables in the markdown output
 * @param {object=} io - IO overrides, primarily for testing
 * @param {object=} io.console
 * @param {object=} io.console.log
 * @param {object=} io.console.warn
 * @param {object=} io.console.error
 * @param {object=} io.fs
 * @param {object=} io.tracker Object compatible with ./lib/tracking.js
 * @param {object=} io.process Object with cwd() and exit()
 * @param {function=} io.get function that takes a URL and returns the contents
 * @return Returns undefined or calls process.exit
 */

module.exports = async function(
	options,
	{
		console = defaultConsole,
		process = defaultProcess,
		fs,
		get,
		tracker
	}={}
	){
	let messages = [];		// These are for the LookML developer who has attempted to lint a project
	let lamsMessages = [];	// These are for the administrator who has invoked LAMS
	try {
		fs = fs || require('fs');
		get = get || require('./lib/https-get.js');
		tracker = tracker || require('./lib/tracking')({
			cliArgs:{
				reporting: options.reporting,
				reportLicenseKey: options.reportLicenseKey,
				reportUser: options.reportUser
			},
			gaPropertyId: 'UA-96247573-2',
		});
		const path = require('path');
		const parser = require('lookml-parser');
		const templates = require('./lib/templates.js');

		console.log('Parsing project...');
		const project = await parser.parseFiles({
			source: options.source,
			conditionalCommentString: 'LAMS',
			fileOutput:"array",
			cwd:options.cwd||process.cwd(),
			console: {
				log: (msg) => {},
				warn: (msg) => lamsMessages.push({message: msg&&msg.message||msg, level: 'lams-warning'}), // LAMS warnings should not abort the deploy
				error: (msg) => lamsMessages.push({message: msg&&msg.message||msg, level: 'lams-error'}), // LAMS errors should abort the deploy
			},
		});
		if (project.errors) {
			console.log(project.errors);
			lamsMessages = lamsMessages.concat(project.errors.map((e) =>
				({message: e&&e.message||e, level: 'lams-error'})
			));
			console.error('> Issues occurred during parsing (containing files will not be considered):');
			project.errorReport();
		}
		if (project.error) {
			throw (project.error);
		}
		project.name = false
			|| project.file && project.file.manifest && project.file.manifest.project_name
			|| options.projectName
			|| (options.cwd||process.cwd()||'').split(path.sep).filter(Boolean).slice(-1)[0]	// The current directory. May not actually be the project name...
			|| 'unknown_project';
		if (project.name === 'look-at-me-sideways') {
			lamsMessages.push({level: 'lams-warning', message: 'Consider adding a manifest.lkml file to your project to identify the project_name'});
		}
		console.log('> Parsing done!');

		console.log('Checking rules... ');
		let rules = fs.readdirSync(path.join(__dirname, 'rules')).map((fileName) => fileName.match(/^(.*)\.js$/)).filter(Boolean).map((match) => match[1]);
		for (let r of rules) {
			console.log('> '+r.toUpperCase());
			let rule = require('./rules/'+r+'.js');
			let result = rule(project);
			messages = messages.concat(result.messages.map((msg)=>({rule: r, ...msg})));
		}
		console.log('> Rules done!');
		if (project.file && project.file.manifest && project.file.manifest.custom_rules) {
			console.log('Checking custom rules...');
			let requireFromString = require('require-from-string');
			let get = require('./lib/https-get.js');
			let rules =  coerceArray(project.file && project.file.manifest && project.file.manifest.custom_rules)
			for (let rule of rules){

			}
			if (options.allowCustomRules !== undefined) {
				let requireFromString = require('require-from-string');
				let customRuleRequests = [];
				project.file.manifest.custom_rules.forEach(async (url, u) => {

					try {
						let request = get(url);
						customRuleRequests.push(request);
						let ruleSrc = await request;
						console.log('> #'+u);
						let rule = requireFromString(ruleSrc, {
							prependPaths: path.resolve(__dirname, './rules'),
						});
						let result = rule(project);
						messages = messages.concat(result.messages.map((msg)=>({rule: `Custom Rule ${u}`, ...msg})));
					} catch (e) {
						let msg = `URL #${u}: ${e&&e.message||e}`;
						console.error('> '+msg);
						lamsMessages.push({
							level: 'lams-error',
							message: `An error occurred while checking custom rule in ${msg}`,
						});
					}
				});
				await Promise.all(customRuleRequests).catch(() => {});
				console.log('> Custom rules done!');
			} else {
				console.warn([
					'> Your project specifies custom rules. Run LAMS with `--allow-custom-rules`',
					'if you want to allow local execution of this remotely-defined Javascript code:',
				].concat(project.file.manifest.custom_rules).join('\n  '));
			}
		}

		let errors = messages.filter((msg) => {
			return msg.level==='error' && !msg.exempt;
		});
		let warnings = messages.filter((msg) => {
			return msg.level==='warning' && !msg.exempt;
		});
		let lamsErrors = messages.filter((msg) => {
			return msg.level==='lams-errors' && !msg.exempt;
		});

		const buildStatus = (errors.length || warnings.length || lamsErrors.length) ? 'FAILED' : 'PASSED';
		console.log(`BUILD ${buildStatus}: ${errors.length} errors and ${warnings.length} warnings found. Check .md files for details.`);

		let jobURL;
		if (options.jenkins) {
			try {
				jobURL = process.env.BUILD_URL;
			} catch (e) {
				// silent
			}
			let json = JSON.stringify({
				buildStatus: buildStatus,
				errors: errors.length,
				warnings: warnings.length,
				lamsErrors: lamsErrors.length,
			});
			fs.writeFileSync('results.json', json, 'utf8');
		}

		console.log('Writing summary files...');
		fs.writeFileSync('developer.md', templates.developer({messages}).replace(/\n\t+/g, '\n'));
		console.log('> Developer index done');
		fs.writeFileSync('issues.md', templates.issues({messages, jobURL}).replace(/\n\t+/g, '\n'));
		console.log('> Issue summary done');

		console.log('> Summary files done!');

		if (tracker.enabled) {
			await Promise.race([
				tracker.track({messages, errors: lamsMessages}),
				new Promise((res) => setTimeout(res, 2000)),
			]);
		}

		if (errors.length) {
			process.exit(1);
		}

		return messages;
	} catch (e) {
		try {
			console.error(e);
			if (!tracker.valid) {
				throw new Error('Unknown error');
			}
			if (tracker.enabled) {
				e.isFatalError = true;
				tracker.track({messages, errors: lamsMessages.concat(e)});
			} else {
				console.warn(`Error reporting is disabled. Run with --reporting=yes to report, or see PRIVACY.md for more info`);
			}
		} catch (e) {
			console.error(e);
			console.error(`Error reporting is not available	. Please submit an issue to https://github.com/looker-open-source/look-at-me-sideways/issues`);
		}
		process.exit(1);
	}
};

function coerceArray(maybeArray){
	if(maybeArray === undefined){return [];}
	if(Array.isArray(maybeArray)){return maybeArray;}
	return [maybeArray];
}
<commit_msg>Custom rules next WIP<commit_after>#! /usr/bin/env node
/* Copyright (c) 2018 Looker Data Sciences, Inc. See https://github.com/looker-open-source/look-at-me-sideways/blob/master/LICENSE.txt */
const defaultConsole = console
const defaultProcess = process
/**
 * LAMS main function
 *
 * @param {object}	options - options
 * @param {object}	options.cwd - Override the current working directory
 * @param {string=}	options.reporting - One of yes, no, save-yes, or save-no. Program terminates with a warning if omitted. See PRIVACY.md for details
 * @param {string=}	options.reportLicenseKey - Optional Looker License Key. See PRIVACY.md for details
 * @param {string=}	options.reportUser - Optional user email address. See PRIVACY.md for details
 * @param {string=}	options.source - An optional glob specifying which files to read
 * @param {string=}	options.projectName - An optional name for the project, used to generate links back to the project in mardown output
 * @param {*=}		options.allowCustomRules - Experimental option. DO NOT USE TO RUN UNTRUSTED CODE. Pass a value to allow running of externally defined JS for custom rules
 * @param {*=}		options.jenkins - Set to indicate that LAMS is being run by Jenkins and to include the build URL from ENV variables in the markdown output
 * @param {object=} io - IO overrides, primarily for testing
 * @param {object=} io.console
 * @param {object=} io.console.log
 * @param {object=} io.console.warn
 * @param {object=} io.console.error
 * @param {object=} io.fs
 * @param {object=} io.tracker Object compatible with ./lib/tracking.js
 * @param {object=} io.process Object with cwd() and exit()
 * @param {function=} io.get function that takes a URL and returns the contents
 * @return Returns undefined or calls process.exit
 */

module.exports = async function(
	options,
	{
		console = defaultConsole,
		process = defaultProcess,
		fs,
		get,
		tracker
	}={}
	){
	let messages = [];		// These are for the LookML developer who has attempted to lint a project
	let lamsMessages = [];	// These are for the administrator who has invoked LAMS
	try {
		fs = fs || require('fs');
		get = get || require('./lib/https-get.js');
		tracker = tracker || require('./lib/tracking')({
			cliArgs:{
				reporting: options.reporting,
				reportLicenseKey: options.reportLicenseKey,
				reportUser: options.reportUser
			},
			gaPropertyId: 'UA-96247573-2',
		});
		const path = require('path');
		const parser = require('lookml-parser');
		const templates = require('./lib/templates.js');

		console.log('Parsing project...');
		const project = await parser.parseFiles({
			source: options.source,
			conditionalCommentString: 'LAMS',
			fileOutput:"array",
			cwd:options.cwd||process.cwd(),
			console: {
				log: (msg) => {},
				warn: (msg) => lamsMessages.push({message: msg&&msg.message||msg, level: 'lams-warning'}), // LAMS warnings should not abort the deploy
				error: (msg) => lamsMessages.push({message: msg&&msg.message||msg, level: 'lams-error'}), // LAMS errors should abort the deploy
			},
		});
		if (project.errors) {
			console.log(project.errors);
			lamsMessages = lamsMessages.concat(project.errors.map((e) =>
				({message: e&&e.message||e, level: 'lams-error'})
			));
			console.error('> Issues occurred during parsing (containing files will not be considered):');
			project.errorReport();
		}
		if (project.error) {
			throw (project.error);
		}
		project.name = false
			|| project.file && project.file.manifest && project.file.manifest.project_name
			|| options.projectName
			|| (options.cwd||process.cwd()||'').split(path.sep).filter(Boolean).slice(-1)[0]	// The current directory. May not actually be the project name...
			|| 'unknown_project';
		if (project.name === 'look-at-me-sideways') {
			lamsMessages.push({level: 'lams-warning', message: 'Consider adding a manifest.lkml file to your project to identify the project_name'});
		}
		console.log('> Parsing done!');

		console.log('Checking rules... ');
		let rules = fs.readdirSync(path.join(__dirname, 'rules')).map((fileName) => fileName.match(/^(.*)\.js$/)).filter(Boolean).map((match) => match[1]);
		for (let r of rules) {
			console.log('> '+r.toUpperCase());
			let rule = require('./rules/'+r+'.js');
			let result = rule(project);
			messages = messages.concat(result.messages.map((msg)=>({rule: r, ...msg})));
		}
		console.log('> Rules done!');

		if (project.manifest && project.manifest.custom_rules) {
			console.warn('\x1b[33m%s\x1b[0m', 'Legacy custom rules will be removed in the next major version!');
			console.log('Checking legacy custom rules...');
			let requireFromString = require('require-from-string');
			let get = options.get || require('./lib/https-get.js');
			let rules =  coerceArray(project.file && project.file.manifest && project.file.manifest.custom_rules)
			if (options.allowCustomRules !== undefined) {
				let requireFromString = require('require-from-string');
				let customRuleRequests = [];
				project.file.manifest.custom_rules.forEach(async (url, u) => {
					try {
						let request = get(url);
						customRuleRequests.push(request);
						let ruleSrc = await request;
						console.log('> #'+u);
						let rule = requireFromString(ruleSrc, {
							prependPaths: path.resolve(__dirname, './rules'),
						});
						let result = rule(project);
						messages = messages.concat(result.messages.map((msg)=>({rule: `Custom Rule ${u}`, ...msg})));
					} catch (e) {
						let msg = `URL #${u}: ${e&&e.message||e}`;
						console.error('> '+msg);
						lamsMessages.push({
							level: 'lams-error',
							message: `An error occurred while checking custom rule in ${msg}`,
						});
					}
				});
				await Promise.all(customRuleRequests).catch(() => {});
				console.log('> Legacy custom rules done!');
			} else {
				console.warn([
					'> Your project specifies custom rules. Run LAMS with `--allow-custom-rules`',
					'if you want to allow local execution of this remotely-defined Javascript code:',
				].concat(project.file.manifest.custom_rules).join('\n  '));
			}
		}

		if(project.manifest && project.manifest.rules){

		}

		let errors = messages.filter((msg) => {
			return msg.level==='error' && !msg.exempt;
		});
		let warnings = messages.filter((msg) => {
			return msg.level==='warning' && !msg.exempt;
		});
		let lamsErrors = messages.filter((msg) => {
			return msg.level==='lams-errors' && !msg.exempt;
		});

		const buildStatus = (errors.length || warnings.length || lamsErrors.length) ? 'FAILED' : 'PASSED';
		console.log(`BUILD ${buildStatus}: ${errors.length} errors and ${warnings.length} warnings found. Check .md files for details.`);

		let jobURL;
		if (options.jenkins) {
			try {
				jobURL = process.env.BUILD_URL;
			} catch (e) {
				// silent
			}
			let json = JSON.stringify({
				buildStatus: buildStatus,
				errors: errors.length,
				warnings: warnings.length,
				lamsErrors: lamsErrors.length,
			});
			fs.writeFileSync('results.json', json, 'utf8');
		}

		console.log('Writing summary files...');
		fs.writeFileSync('developer.md', templates.developer({messages}).replace(/\n\t+/g, '\n'));
		console.log('> Developer index done');
		fs.writeFileSync('issues.md', templates.issues({messages, jobURL}).replace(/\n\t+/g, '\n'));
		console.log('> Issue summary done');

		console.log('> Summary files done!');

		if (tracker.enabled) {
			await Promise.race([
				tracker.track({messages, errors: lamsMessages}),
				new Promise((res) => setTimeout(res, 2000)),
			]);
		}

		if (errors.length) {
			process.exit(1);
		}

		return messages;
	} catch (e) {
		try {
			console.error(e);
			if (!tracker.valid) {
				throw new Error('Unknown error');
			}
			if (tracker.enabled) {
				e.isFatalError = true;
				tracker.track({messages, errors: lamsMessages.concat(e)});
			} else {
				console.warn(`Error reporting is disabled. Run with --reporting=yes to report, or see PRIVACY.md for more info`);
			}
		} catch (e) {
			console.error(e);
			console.error(`Error reporting is not available	. Please submit an issue to https://github.com/looker-open-source/look-at-me-sideways/issues`);
		}
		process.exit(1);
	}
};

function coerceArray(maybeArray){
	if(maybeArray === undefined){return [];}
	if(Array.isArray(maybeArray)){return maybeArray;}
	return [maybeArray];
}
<|endoftext|>