<commit_before>
/**
 * Module dependencies.
 */

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js'),
mongojs = require('mongojs'),
deriver = require('./lib/deriver.js');
var path = require("path");

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback",
    profileFields: ['id', 'name', 'location','gender','birthday']
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return generateUserFB(profile,done);
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.facebookId);
});

passport.deserializeUser(function(id, done) {
  data.findOne({ facebookId: id }, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

app.get('/account', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('account', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

app.post('/account',function (req, res) {
  req.body.facebookId = req.user.facebookId;
  req.body.name = {familyName:req.body.familyName,givenName:req.body.givenName};
  req.body.familyName,req.body.givenName = null;
  //data.updatePerson(req.body);
  console.log(JSON.stringify(req.user));

  deriver.annotate(data, req.body, function(error, user) {
  data.updatePerson(user.facebookId,user);
  //console.log(JSON.stringify(req.body));
  res.statusCode = 200;
  return res.redirect('/account');
  });
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook', { scope: ['user_about_me','user_birthday','user_education_history',
  'user_hometown','user_interests','user_location'] }));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/account');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.get('/about', function (req, res) {
res.render('about', {
    page : 'About',
        theme : 'yeti',
  });
});
// API stuff
app.get('/people', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

app.get('/people/id/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  data.listByThing('_id', objectId, function(e, results){
      res.send(results);
    });
  });

app.get('/people/:thing/:id', function (req, res) {
  var id = req.params.id;
  var thing = req.params.thing;

  data.listByThing(thing, id, function(e, results){
      res.send(results);
    });
  });

app.get('/search', function (req, res) {
  data.listByQueryObject(req.query, function(e, results){
      res.send(results);
    });
  });

app.post('/people', function (req, res) {
  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.people.insert(req.body.person);
  res.statusCode = 200;
  return res.send('Inserted');
  });

app.put('/people/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Put syntax incorrect.');
  }

  data.people.replaceWithObject(objectId, req.body.person);
  res.statusCode = 200;
  return res.send('Updated');

  });

app.get('/map', function (req, res) {
res.render('countrydash', {
    page : 'Map',
    mapelement : 'map',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

app.get('/bargraph', function (req, res) {
res.render('dashboards/bargraph', {
    page : 'Map',
    bar_element_name : 'graph',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

app.get('/piechart', function (req, res) {
res.render('dashboards/piechart', {
    page : 'Map',
    pie_element_name : 'graph',
    datapoints: [
        {label:"Things1", value:100, comma: true},
        {label:"Things2", value:200, comma: true},
        {label:"Things3", value:300, comma: true},
        {label:"Things4", value:400}
      ]

  });
});

app.get('/broadband', function (req, res) {
 data.listByQueryObject(req.query, function(e, results){
  var availability = {};
  for (var i = results.length - 1; i >= 0; i--) {
    if (results[i].broadband){
      availability['Yes'] += 1;
    } else {
      availability['No'] += 1;
    }
  }
  console.log(availability);
    res.render('dashboards/piechart', {
        page : 'Map',
        pie_element_name : 'graph',
        datapoints: [
            {label:"Yes", value:availability['Yes'], comma: true},
            {label:"No", value:availability['No']}
          ]
      });
    });
});

app.get('/persons', function (req, res) {
  data.listByQueryObject({},function(e, people){
    console.log(people);
    for (var i=0;i<people.length;i++)
{
var person = people[i];
if(person.gender == 0){
              person.gender = "Male";
            }else if(person.gender == 1){
              person.gender = "Female";
            }else if(person.gender == 2){
              person.gender = "other";
            }
            people[i] = person;
}
    res.render('dashboards/people', {
        page : 'People',
        persons: people
      });
    });
});

function generateUserFB(profile,done){

var g = 2;
if(profile.gender == "male"){
g = 0;
}else if (profile.gender == "female"){
g = 1
}
var user = { facebookId: profile.id , name: profile.name,gender: g,location: profile.location,birthday: profile.birthday}
data.addPerson(user);
data.findOne(user, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null,false);
      return done(err, user);
      }
    );
}

http.createServer(app).listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Hopeful fix<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
http = require('http'),
passport = require('passport'),
util = require('util'),
path = require('path'),
FacebookStrategy = require('passport-facebook').Strategy,
config = require('./config.js'),
data = require('./lib/data.js'),
mongojs = require('mongojs'),
deriver = require('./lib/deriver.js');
var path = require("path");

var app = express();

app.configure(function () {
	app.set('port', process.env.PORT || 3000);
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'mustache');
    app.engine('mustache', require('hogan-middleware').__express);
	app.use(express.favicon(path.join(__dirname, 'public/favicon.png')));
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.session({
			secret : config.sessionsecret
		}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}
// passport
passport.use(new FacebookStrategy({
    clientID: config.facebookid,
    clientSecret: config.facebooksecret,
    callbackURL: "http://delta.dev.geeksoc.org/auth/facebook/callback",
    profileFields: ['id', 'name', 'location','gender','birthday']
  },
  function(accessToken, refreshToken, profile, done) {
    data.findOne({ facebookId: profile.id }, function (err, user) {
    if (err) return done(err);
      if (!user) return generateUserFB(profile,done);
      return done(err, user);
      }
    );
  }

));

passport.serializeUser(function(user, done) {
  done(null, user.facebookId);
});

passport.deserializeUser(function(id, done) {
  data.findOne({ facebookId: id }, function(err, user) {
    done(err, user);
  });
});

app.get('/', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('index', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

app.get('/account', function (req, res) {
console.log(JSON.stringify(req.user));
res.render('account', {
		page : 'Main Page',
        theme : 'yeti',
		user : req.user
	});
});

app.post('/account',function (req, res) {
  req.body.facebookId = req.user.facebookId;
  req.body.name = {familyName:req.body.familyName,givenName:req.body.givenName};
  req.body.familyName,req.body.givenName = null;
  //data.updatePerson(req.body);
  console.log(JSON.stringify(req.user));

  deriver.annotate(data, req.body, function(error, user) {
  data.updatePerson(user.facebookId,user);
  //console.log(JSON.stringify(req.body));
  res.statusCode = 200;
  return res.redirect('/account');
  });
});

// auth routes
app.get('/auth/facebook',
  passport.authenticate('facebook', { scope: ['user_about_me','user_birthday','user_education_history',
  'user_hometown','user_interests','user_location'] }));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/account');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.get('/about', function (req, res) {
res.render('about', {
    page : 'About',
        theme : 'yeti',
  });
});
// API stuff
app.get('/people', function (req, res) {
  data.listAllPeople(function(e, results){
      res.send(results);
    });
  });

app.get('/people/id/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  data.listByThing('_id', objectId, function(e, results){
      res.send(results);
    });
  });

app.get('/people/:thing/:id', function (req, res) {
  var id = req.params.id;
  var thing = req.params.thing;

  data.listByThing(thing, id, function(e, results){
      res.send(results);
    });
  });

app.get('/search', function (req, res) {
  data.listByQueryObject(req.query, function(e, results){
      res.send(results);
    });
  });

app.post('/people', function (req, res) {
  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
  }
  data.people.insert(req.body.person);
  res.statusCode = 200;
  return res.send('Inserted');
  });

app.put('/people/:id', function (req, res) {
  var id = req.params.id;
  var objectId = mongojs.ObjectId(id);

  if(!req.body.hasOwnProperty('person')) {
    res.statusCode = 400;
    return res.send('Error 400: Put syntax incorrect.');
  }

  data.people.replaceWithObject(objectId, req.body.person);
  res.statusCode = 200;
  return res.send('Updated');

  });

app.get('/map', function (req, res) {
res.render('countrydash', {
    page : 'Map',
    mapelement : 'map',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

app.get('/bargraph', function (req, res) {
res.render('dashboards/bargraph', {
    page : 'Map',
    bar_element_name : 'graph',
    datapoints: [
      {latitude: 55.8506080519, longitude: -4.26492576329, weight: 100},
        {latitude: 55.8613701277, longitude: -4.24460130892, weight: 100},
        {latitude: 55.4906916873, longitude: -4.60522901822, weight: 100},
        {latitude: 55.8651840586, longitude: -4.2216469545 , weight: 100}
      ]

  });
});

app.get('/piechart', function (req, res) {
res.render('dashboards/piechart', {
    page : 'Map',
    pie_element_name : 'graph',
    datapoints: [
        {label:"Things1", value:100, comma: true},
        {label:"Things2", value:200, comma: true},
        {label:"Things3", value:300, comma: true},
        {label:"Things4", value:400}
      ]

  });
});

app.get('/broadband', function (req, res) {
 data.listByQueryObject(req.query, function(e, results){
  var availability = {};
  availability['Yes'] = 0;
  availability['No']  = 0;
  for (var i = results.length - 1; i >= 0; i--) {
    if (results[i].broadband){

      availability['Yes'] += 1;
    } else {
      availability['No'] += 1;
    }
  }
  console.log(availability);
    res.render('dashboards/piechart', {
        page : 'Map',
        pie_element_name : 'graph',
        datapoints: [
            {label:"Yes", value:availability['Yes'], comma: true},
            {label:"No", value:availability['No']}
          ]
      });
    });
});

app.get('/persons', function (req, res) {
  data.listByQueryObject({},function(e, people){
    console.log(people);
    for (var i=0;i<people.length;i++)
{
var person = people[i];
if(person.gender == 0){
              person.gender = "Male";
            }else if(person.gender == 1){
              person.gender = "Female";
            }else if(person.gender == 2){
              person.gender = "other";
            }
            people[i] = person;
}
    res.render('dashboards/people', {
        page : 'People',
        persons: people
      });
    });
});

function generateUserFB(profile,done){

var g = 2;
if(profile.gender == "male"){
g = 0;
}else if (profile.gender == "female"){
g = 1
}
var user = { facebookId: profile.id , name: profile.name,gender: g,location: profile.location,birthday: profile.birthday}
data.addPerson(user);
data.findOne(user, function (err, user) {
    if (err) return done(err);
      if (!user) return done(null,false);
      return done(err, user);
      }
    );
}

http.createServer(app).listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>/**
 * Provides buttons to share a page through multiple social community sites.
 *
 * @author	Marcel Werk
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @module	WoltLabSuite/Core/Ui/Message/Share
 */
define(['EventHandler'], function(EventHandler) {
	"use strict";

	/**
	 * @exports	WoltLabSuite/Core/Ui/Message/Share
	 */
	return {
		_pageDescription: '',
		_pageUrl: '',

		init: function() {
			var title = elBySel('meta[property="og:title"]');
			if (title !== null) this._pageDescription = encodeURIComponent(title.content);
			var url = elBySel('meta[property="og:url"]');
			if (url !== null) this._pageUrl = encodeURIComponent(url.content);

			elBySelAll('.jsMessageShareButtons', null, (function(container) {
				container.classList.remove('jsMessageShareButtons');

				var providers = {
					facebook: {
						link: elBySel('.jsShareFacebook', container),
						share: (function() { this._share('facebook', 'https://www.facebook.com/sharer.php?u={pageURL}&t={text}', true); }).bind(this)
					},
					google: {
						link: elBySel('.jsShareGoogle', container),
						share: (function() { this._share('google', 'https://plus.google.com/share?url={pageURL}', false); }).bind(this)
					},
					reddit: {
						link: elBySel('.jsShareReddit', container),
						share: (function() { this._share('reddit', 'https://ssl.reddit.com/submit?url={pageURL}', false); }).bind(this)
					},
					twitter: {
						link: elBySel('.jsShareTwitter', container),
						share: (function() { this._share('twitter', 'https://twitter.com/share?url={pageURL}&text={text}', false); }).bind(this)
					},
					linkedIn: {
						link: elBySel('.jsShareLinkedIn', container),
						share: (function() { this._share('linkedIn', 'https://www.linkedin.com/cws/share?url={pageURL}', false); }).bind(this)
					},
					pinterest: {
						link: elBySel('.jsSharePinterest', container),
						share: (function() { this._share('pinterest', 'https://www.pinterest.com/pin/create/link/?url={pageURL}&description={text}', false); }).bind(this)
					},
					xing: {
						link: elBySel('.jsShareXing', container),
						share: (function() { this._share('xing', 'https://www.xing.com/social_plugins/share?url={pageURL}', false); }).bind(this)
					},
					whatsApp: {
						link: elBySel('.jsShareWhatsApp', container),
						share: (function() {
							window.location.href = 'whatsapp://send?text=' + this._pageDescription + '%20' + this._pageUrl;
						}).bind(this)
					}
				};

				EventHandler.fire('com.woltlab.wcf.message.share', 'shareProvider', {
					container: container,
					providers: providers,
					pageDescription: this._pageDescription,
					pageUrl: this._pageUrl
				});

				for (var provider in providers) {
					if (providers.hasOwnProperty(provider)) {
						if (providers[provider].link !== null) {
							providers[provider].link.addEventListener(WCF_CLICK_EVENT, providers[provider].share);
						}
					}
				}
			}).bind(this));
		},

		_share: function(objectName, url, appendURL) {
			window.open(url.replace(/\{pageURL}/, this._pageUrl).replace(/\{text}/, this._pageDescription + (appendURL ? "%20" + this._pageUrl : "")), objectName, 'height=600,width=600');
		}
	};
});
<commit_msg>Improved WhatsApp Message Sharing<commit_after>/**
 * Provides buttons to share a page through multiple social community sites.
 *
 * @author	Marcel Werk
 * @copyright	2001-2017 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @module	WoltLabSuite/Core/Ui/Message/Share
 */
define(['EventHandler'], function(EventHandler) {
	"use strict";

	/**
	 * @exports	WoltLabSuite/Core/Ui/Message/Share
	 */
	return {
		_pageDescription: '',
		_pageUrl: '',

		init: function() {
			var title = elBySel('meta[property="og:title"]');
			if (title !== null) this._pageDescription = encodeURIComponent(title.content);
			var url = elBySel('meta[property="og:url"]');
			if (url !== null) this._pageUrl = encodeURIComponent(url.content);

			elBySelAll('.jsMessageShareButtons', null, (function(container) {
				container.classList.remove('jsMessageShareButtons');

				var providers = {
					facebook: {
						link: elBySel('.jsShareFacebook', container),
						share: (function() { this._share('facebook', 'https://www.facebook.com/sharer.php?u={pageURL}&t={text}', true); }).bind(this)
					},
					google: {
						link: elBySel('.jsShareGoogle', container),
						share: (function() { this._share('google', 'https://plus.google.com/share?url={pageURL}', false); }).bind(this)
					},
					reddit: {
						link: elBySel('.jsShareReddit', container),
						share: (function() { this._share('reddit', 'https://ssl.reddit.com/submit?url={pageURL}', false); }).bind(this)
					},
					twitter: {
						link: elBySel('.jsShareTwitter', container),
						share: (function() { this._share('twitter', 'https://twitter.com/share?url={pageURL}&text={text}', false); }).bind(this)
					},
					linkedIn: {
						link: elBySel('.jsShareLinkedIn', container),
						share: (function() { this._share('linkedIn', 'https://www.linkedin.com/cws/share?url={pageURL}', false); }).bind(this)
					},
					pinterest: {
						link: elBySel('.jsSharePinterest', container),
						share: (function() { this._share('pinterest', 'https://www.pinterest.com/pin/create/link/?url={pageURL}&description={text}', false); }).bind(this)
					},
					xing: {
						link: elBySel('.jsShareXing', container),
						share: (function() { this._share('xing', 'https://www.xing.com/social_plugins/share?url={pageURL}', false); }).bind(this)
					},
					whatsApp: {
						link: elBySel('.jsShareWhatsApp', container),
						share: (function() {
							window.location.href = 'https://api.whatsapp.com/send?text=' + this._pageDescription + '%20' + this._pageUrl;
						}).bind(this)
					}
				};

				EventHandler.fire('com.woltlab.wcf.message.share', 'shareProvider', {
					container: container,
					providers: providers,
					pageDescription: this._pageDescription,
					pageUrl: this._pageUrl
				});

				for (var provider in providers) {
					if (providers.hasOwnProperty(provider)) {
						if (providers[provider].link !== null) {
							providers[provider].link.addEventListener(WCF_CLICK_EVENT, providers[provider].share);
						}
					}
				}
			}).bind(this));
		},

		_share: function(objectName, url, appendURL) {
			window.open(url.replace(/\{pageURL}/, this._pageUrl).replace(/\{text}/, this._pageDescription + (appendURL ? "%20" + this._pageUrl : "")), objectName, 'height=600,width=600');
		}
	};
});
<|endoftext|>


<commit_before>const Donation = require('../models/Donation');
const Bot = require('../models/Bot');
const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');
const moment = require('moment');

exports.createDonation = asyncFn((donationData) => {
	const createdAt = donationData.createdAt;
	const earlierDonation = awaitFn(
		Donation.find({
			fromTwitterID: donationData.fromTwitterID,
			createdAt: {
				$gte: moment(createdAt)
					.startOf('day')
					.toDate(),
				$lt: moment(createdAt)
					.endOf('day')
					.toDate(),
			},
		})
	);
	if (earlierDonation.length) {
		throw new Error('Donation not allowed. Already donated today!');
	}
	const donation = new Donation(donationData);
	const bot = awaitFn(Bot.findOne());
	bot.money += donation.money;
	awaitFn(donation.save());
	return awaitFn(bot.save());
});

exports.index = asyncFn((req, res) => {
	const terence = awaitFn(Bot.findOne());
	const donations = awaitFn(Donation.find()
		.sort({
			createdAt: 'desc',
		})
		.limit(10));
	const count = awaitFn(Donation.count());
	const top = awaitFn(Donation.getTopDonaters());
	const totalDonaters = top.length;
	const topDonaters = top.sort((a, b) => b.value - a.value).slice(0, 9);
	res.render('', {
		title: 'Donations',
		totalDonaters,
		topDonaters,
		donations,
		count,
		terence,
	});
});
<commit_msg>cleanup<commit_after>const Donation = require('../models/Donation');
const Bot = require('../models/Bot');
const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');
const moment = require('moment');

exports.createDonation = asyncFn((donationData) => {
	const createdAt = donationData.createdAt;
	const earlierDonation = awaitFn(
		Donation.find({
			fromTwitterID: donationData.fromTwitterID,
			createdAt: {
				$gte: moment(createdAt)
					.startOf('day')
					.toDate(),
				$lt: moment(createdAt)
					.endOf('day')
					.toDate(),
			},
		})
	);
	if (earlierDonation.length) {
		throw new Error('Donation not allowed. Already donated today!');
	}
	const donation = new Donation(donationData);
	const bot = awaitFn(Bot.findOne());
	bot.money += donation.money;
	awaitFn(donation.save());
	return awaitFn(bot.save());
});

exports.index = asyncFn((req, res) => {
	const terence = awaitFn(Bot.findOne());
	const donations = awaitFn(Donation.find()
		.sort({
			createdAt: 'desc',
		})
		.limit(10));
	const count = awaitFn(Donation.count());
	const top = awaitFn(Donation.getTopDonaters());
	const totalDonaters = top.length;
	const topDonaters = top.slice(0, 10); // use only top 10
	res.render('', {
		title: 'Donations',
		totalDonaters,
		topDonaters,
		donations,
		count,
		terence,
	});
});
<|endoftext|>


<commit_before>//test
var watch = require('watch');
var xml2js = require('xml2js');
var fs = require('fs');
var through = require('through2');
var path = require('path');

var read = process.argv[2];
var write = process.argv[3];

watch.createMonitor(read, function (monitor) {

	monitor.on("created", function (f, stat) {
		if(stat.isFile())
			convertToJson(f);
		console.log("created " + f)// Handle new files
	})
	monitor.on("changed", function (f, curr, prev) {
	  // Handle file changes
	})
	monitor.on("removed", function (f, stat) {
	  // Handle removed files
	})
	//monitor.stop(); // Stop watching
})

function convertToJson(f){

	console.log(f);
	var pathInfo = path.parse(f)
	var parser = new xml2js.Parser()

	if(pathInfo.ext !== '.xml') return;

	var toXML = fs.readFile(f, function(err, data){
		parser.parseString(data, function(err, result){
			fs.writeFile(pathInfo.dir + "/" + pathInfo.name + ".json", result, function(err){
				if(err){
					console.log("Couldn't write JSON: " + e)
					return
				}
			})
		})
	})
}
<commit_msg>adding some changes<commit_after>//test
var watch = require('watch');
var xml2js = require('xml2js');
var fs = require('fs');
var through = require('through2');
var path = require('path');

//var buffer = through(start, end);

var read = process.argv[2];
var write = process.argv[3];

watch.createMonitor(read, function (monitor) {

	monitor.on("created", function (f, stat) {
		if(stat.isFile())
			convertToJson(f);
	})
	monitor.on("changed", function (f, curr, prev) {
	  if(curr.isFile())
			convertToJson(f);
	})
	monitor.on("removed", function (f, stat) {
	  // Handle removed files
	})
	//monitor.stop(); // Stop watching
})

function convertToJson(f){

	console.log(f);
	var pathInfo = path.parse(f)
	var parser = new xml2js.Parser()
	var jsonString;

	if(pathInfo.ext !== '.xml') return console.log("Not XML, no changes");

	fs.createReadStream(f).pipe(through(write, end)).pipe(fs.createWriteStream(pathInfo.dir + "/" + pathInfo.name + ".json"));
		//parser.parseString(data, function(err, result){
		//	console.log(result);
		//	var jsonString = result;
		//	console.log(jsonString);
		//	//fs.writeFile(pathInfo.dir + "/" + pathInfo.name + ".json", jsonString, function(err, data2){
			//	console.log("inside " + jsonString);
			//	if(err){
			//		console.log("Couldn't write JSON: " + err)
			//		return
			//	}
			//})

	function write(buff, enc, next){

		console.log("Incoming XML \n" + buff.toString());
		this.push(parser.parseString(buff.toString(), function(err, result){
			if(err) return console.log("there was an error");

			return result;
		}))
	}

	function end(done){
		//this.push(jsonString);
		done();
	}
}

<|endoftext|>


<commit_before>define(['Language', 'Ui/Dialog'], function(Language, UiDialog) {
	"use strict";

	var _boundListener = false;
	var _callback = null;

	return {
		showDialog: function(options) {
			UiDialog.open(this);

			UiDialog.setTitle(this, Language.get('wcf.editor.link.' + (options.insert ? 'add' : 'edit')));

			var submitButton = elById('redactor-modal-button-action');
			submitButton.textContent = Language.get('wcf.global.button.' + (options.insert ? 'insert' : 'save'));

			_callback = options.submitCallback;

			if (!_boundListener) {
				_boundListener = true;

				submitButton.addEventListener(WCF_CLICK_EVENT, this._submit.bind(this));
			}
		},

		_submit: function() {
			if (_callback()) {
				UiDialog.close(this);
			}
			else {
				var url = elById('redactor-link-url');
				var small = (url.nextElementSibling && url.nextElementSibling.nodeName === 'SMALL') ? url.nextElementSibling : null;

				if (small === null) {
					small = elCreate('small');
					small.className = 'innerError';
					url.parentNode.appendChild(small);
				}

				small.textContent = Language.get((url.value.trim() === '' ? 'wcf.global.form.error.empty' : 'wcf.editor.link.error.invalid'));
			}
		},

		_dialogSetup: function() {
			return {
				id: 'redactorDialogLink',
				options: {
					onClose: function() {
						var url = elById('redactor-link-url');
						var small = (url.nextElementSibling && url.nextElementSibling.nodeName === 'SMALL') ? url.nextElementSibling : null;
						if (small !== null) {
							elRemove(small);
						}
					}
				},
				source: '
'
						+ '
' + Language.get('wcf.editor.link.url') + '
'
						+ '
<input type="url" id="redactor-link-url" class="long">
'
					+ '
'
					+ '
'
						+ '
' + Language.get('wcf.editor.link.text') + '
'
						+ '
<input type="text" id="redactor-link-url-text" class="long">
'
					+ '
'
					+ '
'
						+ '<button id="redactor-modal-button-action" class="buttonPrimary"></button>'
					+ '
'
			};
		}
	};
});
<commit_msg>Force focus on url input, added enter-key submit support<commit_after>define(['Core', 'EventKey', 'Language', 'Ui/Dialog'], function(Core, EventKey, Language, UiDialog) {
	"use strict";

	var _boundListener = false;
	var _callback = null;

	return {
		showDialog: function(options) {
			UiDialog.open(this);

			UiDialog.setTitle(this, Language.get('wcf.editor.link.' + (options.insert ? 'add' : 'edit')));

			var submitButton = elById('redactor-modal-button-action');
			submitButton.textContent = Language.get('wcf.global.button.' + (options.insert ? 'insert' : 'save'));

			_callback = options.submitCallback;

			if (!_boundListener) {
				_boundListener = true;

				submitButton.addEventListener(WCF_CLICK_EVENT, this._submit.bind(this));
			}
		},

		_submit: function() {
			if (_callback()) {
				UiDialog.close(this);
			}
			else {
				var url = elById('redactor-link-url');
				var small = (url.nextElementSibling && url.nextElementSibling.nodeName === 'SMALL') ? url.nextElementSibling : null;

				if (small === null) {
					small = elCreate('small');
					small.className = 'innerError';
					url.parentNode.appendChild(small);
				}

				small.textContent = Language.get((url.value.trim() === '' ? 'wcf.global.form.error.empty' : 'wcf.editor.link.error.invalid'));
			}
		},

		_dialogSetup: function() {
			return {
				id: 'redactorDialogLink',
				options: {
					onClose: function() {
						var url = elById('redactor-link-url');
						var small = (url.nextElementSibling && url.nextElementSibling.nodeName === 'SMALL') ? url.nextElementSibling : null;
						if (small !== null) {
							elRemove(small);
						}
					},
					onSetup: function (content) {
						var submitButton = elBySel('.formSubmit > .buttonPrimary', content);

						if (submitButton !== null) {
							elBySelAll('input[type="url"], input[type="text"]', content, function (input) {
								input.addEventListener('keyup', function (event) {
									if (EventKey.Enter(event)) {
										Core.triggerEvent(submitButton, 'click');
									}
								});
							});
						}
					},
					onShow: function () {
						elById('redactor-link-url').focus();
					}
				},
				source: '
'
						+ '
' + Language.get('wcf.editor.link.url') + '
'
						+ '
<input type="url" id="redactor-link-url" class="long">
'
					+ '
'
					+ '
'
						+ '
' + Language.get('wcf.editor.link.text') + '
'
						+ '
<input type="text" id="redactor-link-url-text" class="long">
'
					+ '
'
					+ '
'
						+ '<button id="redactor-modal-button-action" class="buttonPrimary"></button>'
					+ '
'
			};
		}
	};
});
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, { useCallback, useMemo, useState } from "react";
import styled from "styled-components";

import Button from "@agir/front/genericComponents/Button";
import Modal from "@agir/front/genericComponents/Modal";
import Spacer from "@agir/front/genericComponents/Spacer";

import { routeConfig } from "@agir/front/app/routes.config";

const ANONYMOUS_TO_SOFT_LOGIN_CONNECTION = "ANONYMOUS_TO_SOFT_LOGIN_CONNECTION";
const LOGGED_IN_TO_SOFT_LOGIN_CONNECTION = "LOGGED_IN_TO_SOFT_LOGIN_CONNECTION";
export const SOFT_LOGIN_MODAL_TAGS = [
  ANONYMOUS_TO_SOFT_LOGIN_CONNECTION,
  LOGGED_IN_TO_SOFT_LOGIN_CONNECTION,
];

const StyledModalContent = styled.div`
  max-width: 415px;
  padding: 1rem;
  margin: 40px auto 0;
  border-radius: ${(props) => props.theme.borderRadius};
  box-shadow: ${(props) => props.theme.elaborateShadow};
  background-color: ${(props) => props.theme.white};

  @media (max-width: ${(props) => props.theme.collapse}px) {
    margin-top: 1rem;
    min-height: 0;
    max-width: calc(100% - 2rem);
  }

  h3,
  h6 {
    text-align: center;
    line-height: 1.5;
    margin: 0;
  }

  h3 {
    font-weight: 600;
    font-size: 1.25rem;
  }

  h6 {
    color: ${(props) => props.theme.primary500};
    font-weight: 400;
    font-size: 0.875rem;
  }
  p {
    line-height: 1.5;

    strong {
      font-weight: 600;
    }

    em {
      color: ${(props) => props.theme.black500};
    }
  }

  footer {
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    gap: 0.5rem;

    ${Button} {
      flex: 1 1 auto;
    }
  }
`;

const SoftLoginModalContent = (props) => {
  const { user, data, onClose } = props;

  if (!user || !data) {
    return null;
  }

  const username =
    user?.displayName.length > 2
      ? user?.displayName
      : user?.firstName || user?.displayName;

  const [type, softLoginUserName, softLoginUserEmail, softLoginURL] =
    data.tags.split(",");

  if (type === ANONYMOUS_TO_SOFT_LOGIN_CONNECTION) {
    return (

    );
  }

  if (type === LOGGED_IN_TO_SOFT_LOGIN_CONNECTION) {
    return (

    );
  }

  return null;
};

export const SoftLoginModal = (props) => (
  <Modal shouldShow={props.shouldShow} noScroll>
    {props.shouldShow && <SoftLoginModalContent {...props} />}
  </Modal>
);

SoftLoginModalContent.propTypes = SoftLoginModal.propTypes = {
  data: {
    tags: PropTypes.string.isRequired,
  },
  user: PropTypes.shape({
    displayName: PropTypes.string.isRequired,
    firstName: PropTypes.string,
    email: PropTypes.string.isRequired,
  }).isRequired,
  shouldShow: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
};

export default SoftLoginModal;
<commit_msg>fix: sentry length of undefined<commit_after>import PropTypes from "prop-types";
import React, { useCallback, useMemo, useState } from "react";
import styled from "styled-components";

import Button from "@agir/front/genericComponents/Button";
import Modal from "@agir/front/genericComponents/Modal";
import Spacer from "@agir/front/genericComponents/Spacer";

import { routeConfig } from "@agir/front/app/routes.config";

const ANONYMOUS_TO_SOFT_LOGIN_CONNECTION = "ANONYMOUS_TO_SOFT_LOGIN_CONNECTION";
const LOGGED_IN_TO_SOFT_LOGIN_CONNECTION = "LOGGED_IN_TO_SOFT_LOGIN_CONNECTION";
export const SOFT_LOGIN_MODAL_TAGS = [
  ANONYMOUS_TO_SOFT_LOGIN_CONNECTION,
  LOGGED_IN_TO_SOFT_LOGIN_CONNECTION,
];

const StyledModalContent = styled.div`
  max-width: 415px;
  padding: 1rem;
  margin: 40px auto 0;
  border-radius: ${(props) => props.theme.borderRadius};
  box-shadow: ${(props) => props.theme.elaborateShadow};
  background-color: ${(props) => props.theme.white};

  @media (max-width: ${(props) => props.theme.collapse}px) {
    margin-top: 1rem;
    min-height: 0;
    max-width: calc(100% - 2rem);
  }

  h3,
  h6 {
    text-align: center;
    line-height: 1.5;
    margin: 0;
  }

  h3 {
    font-weight: 600;
    font-size: 1.25rem;
  }

  h6 {
    color: ${(props) => props.theme.primary500};
    font-weight: 400;
    font-size: 0.875rem;
  }
  p {
    line-height: 1.5;

    strong {
      font-weight: 600;
    }

    em {
      color: ${(props) => props.theme.black500};
    }
  }

  footer {
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    gap: 0.5rem;

    ${Button} {
      flex: 1 1 auto;
    }
  }
`;

const SoftLoginModalContent = (props) => {
  const { user, data, onClose } = props;

  if (!user || !data) {
    return null;
  }

  const username =
    user.displayName?.length > 2
      ? user.displayName
      : user.firstName || user.displayName;

  const [type, softLoginUserName, softLoginUserEmail, softLoginURL] =
    data.tags.split(",");

  if (type === ANONYMOUS_TO_SOFT_LOGIN_CONNECTION) {
    return (

    );
  }

  if (type === LOGGED_IN_TO_SOFT_LOGIN_CONNECTION) {
    return (

    );
  }

  return null;
};

export const SoftLoginModal = (props) => (
  <Modal shouldShow={props.shouldShow} noScroll>
    {props.shouldShow && <SoftLoginModalContent {...props} />}
  </Modal>
);

SoftLoginModalContent.propTypes = SoftLoginModal.propTypes = {
  data: {
    tags: PropTypes.string.isRequired,
  },
  user: PropTypes.shape({
    displayName: PropTypes.string.isRequired,
    firstName: PropTypes.string,
    email: PropTypes.string.isRequired,
  }).isRequired,
  shouldShow: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
};

export default SoftLoginModal;
<|endoftext|>


<commit_before>import { h, Component } from 'preact/preact';
import SVGIcon 			from 'com/svg-icon/icon';

export default class SidebarUpcoming extends Component {
	constructor() {
	}

	render( props, state ) {
		return (

<SVGIcon baseline>calendar-wide</SVGIcon> Coming Up

Nov. 29th - Theme Slaughter

Dec. 9th - Ludum Dare 37 <SVGIcon baseline small>trophy</SVGIcon>

 { console.log('full-schedlue'); window.location.hash = "#cal"; }}>Full Schedule

		);
	}
}

//
Dec. 30th - Results

<commit_msg>updated the upcoming events<commit_after>import { h, Component } from 'preact/preact';
import SVGIcon 			from 'com/svg-icon/icon';

export default class SidebarUpcoming extends Component {
	constructor() {
	}

	render( props, state ) {
		return (

<SVGIcon baseline>calendar-wide</SVGIcon> Coming Up

Dec. 4th - Theme Voting

Dec. 7th - Final Theme Voting

Dec. 9th - Ludum Dare 37 <SVGIcon baseline small>trophy</SVGIcon>

 { console.log('full-schedlue'); window.location.hash = "#cal"; }}>Full Schedule

		);
	}
}

//
Dec. 30th - Results

<|endoftext|>


<commit_before>import { combineReducers } from 'redux';

import {
  WEAVE_ON, WEAVE_OFF,
  THREADING_ON, THREADING_OFF,
  TREADLING_ON, TREADLING_OFF,
  TIE_UP_ON, TIE_UP_OFF} from '../constants';

const initialState = {
  weaves: [],
  numberOfWeaves: 0,
  threadings: [],
  treadlings: [],
  tieUp: []
};

function initNewState(state) {
  return Object.assign({}, state,
    {
      weaves: [...state.weaves],
      numberOfWeaves: state.numberOfWeaves,
      threadings: [...state.threadings],
      treadlings: [...state.treadlings],
      tieUp: [...state.tieUp]
    }
  );
}

function switcherWeaveOn(newState, action) {
  newState.numberOfWeaves++;

  if (newState.weaves[action.row] === undefined)
    newState.weaves[action.row] = [];

  newState.weaves[action.row][action.col] = true;
  return newState;
}

function switcherWeaveOff(newState, action) {
  newState.numberOfWeaves--;

  if (newState.weaves[action.row] === undefined)
    newState.weaves[action.row] = [];

  newState.weaves[action.row][action.col] = false;
  return newState;
}

function checkThreading(newState, row) {
  const ret = [];

  for (let i = 0; i < newState.threadings.length; i++) {
    if (newState.threadings[i] === row) ret.push(i);
  }

  return ret;
}

function checkTreadling(newState, col) {
  const ret = [];

  for (let i = 0; i < newState.treadlings.length; i++) {
    if (newState.treadlings[i] === col) ret.push(i);
  }

  return ret;
}

function checkTieUpRow(newState, row) {
  const ret = [];

  if (newState.tieUp[row]) {
    for (let i = 0; i < newState.tieUp[row].length; i++) {
      if (newState.tieUp[row][i] === true) ret.push(i);
    }
  }

  return ret;
}

function checkTieUpCol(newState, col) {
  const ret = [];

  for (let i = 0; i < newState.tieUp.length; i++) {
    const tieUpRow = newState.tieUp[i];

    if (tieUpRow && tieUpRow[col] === true) ret.push(i);
  }

  return ret;
}

function switcherTieUpOn(newState, action) {
  if (newState.tieUp[action.row] === undefined)
    newState.tieUp[action.row] = [];

  newState.tieUp[action.row][action.col] = true;

  const weaveCols = checkThreading(newState, action.row);
  const weaveRows = checkTreadling(newState, action.col);

  for (let r = 0; r < weaveRows.length; r++) {
    const weaveRow = weaveRows[r];

    if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];

    for (let c = 0; c < weaveCols.length; c++) {
      const weaveCol = weaveCols[c];
      newState.weaves[weaveRow][weaveCol] = true;
    }
  }

  return newState;
}

function switcherTieUpOff(newState, action) {
  if (newState.tieUp[action.row] === undefined)
    newState.tieUp[action.row] = [];

  newState.tieUp[action.row][action.col] = false;

  const weaveCols = checkThreading(newState, action.row);
  const weaveRows = checkTreadling(newState, action.col);

  for (let r = 0; r < weaveRows.length; r++) {
    const weaveRow = weaveRows[r];

    if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];

    for (let c = 0; c < weaveCols.length; c++) {
      const weaveCol = weaveCols[c];
      newState.weaves[weaveRow][weaveCol] = false;
    }
  }

  return newState;
}

function switcherThreadingOn(newState, action) {
  newState.threadings[action.col] = action.row;

  const tieUpRows = checkTieUpRow(newState, action.row);

  if (tieUpRows.length) {
    for (let r = 0; r < tieUpRows.length; r++) {
      const treadlingCols = checkTreadling(newState, tieUpRows[r]);

      for (let c = 0; c < treadlingCols.length; c++) {
        const weaveRow = treadlingCols[c];
        if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];
        newState.weaves[weaveRow][action.col] = true;
      }
    }
  } else {
    for (let i = 0; i < newState.weaves.length; i++) {
      if (newState.weaves[i]) newState.weaves[i][action.col] = false;
    }
  }

  return newState;
}

function switcherThreadingOff(newState, action) {
  newState.threadings[action.col] = undefined;

  const tieUpRows = checkTieUpRow(newState, action.row);

  for (let r = 0; r < tieUpRows.length; r++) {
    const treadlingCols = checkTreadling(newState, tieUpRows[r]);

    for (let c = 0; c < treadlingCols.length; c++) {
      const weaveRow = treadlingCols[c];
      if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];
      newState.weaves[weaveRow][action.col] = false;
    }
  }

  return newState;
}

function switcherTreadlingOn(newState, action) {
  newState.treadlings[action.col] = action.row;

  const tieUpCols = checkTieUpCol(newState, action.row/*????*/);

  if (tieUpCols.length) {
    newState.weaves[action.col] = [];

    for (let i = 0; i < tieUpCols.length; i++) {
      const threadingRows = checkThreading(newState, tieUpCols[i]);

      for (let ii = 0; ii < threadingRows.length; ii++) {
        const weaveCol = threadingRows[ii];
        if (newState.weaves[action.col] === undefined) newState.weaves[action.col] = [];
        newState.weaves[action.col][weaveCol] = true;
      }
    }
  } else {
    newState.weaves[action.col] = [];
  }

  return newState;
}

function switcherTreadlingOff(newState, action) {
  newState.treadlings[action.col] = undefined;

  const tieUpCols = checkTieUpCol(newState, action.row/*????*/);

  for (let i = 0; i < tieUpCols.length; i++) {
    const threadingRows = checkThreading(newState, tieUpCols[i]);

    for (let ii = 0; ii < threadingRows.length; ii++) {
      const weaveCol = threadingRows[ii];
      if (newState.weaves[action.col] === undefined) newState.weaves[action.col] = [];
      newState.weaves[action.col][weaveCol] = false;
    }
  }

  return newState;
}

function switcher4(state, action) {
  switch (action.type) {
    case WEAVE_ON: return switcherWeaveOn(initNewState(state), action);
    case WEAVE_OFF: return switcherWeaveOff(initNewState(state), action);
    case TIE_UP_ON: return switcherTieUpOn(initNewState(state), action);
    case TIE_UP_OFF: return switcherTieUpOff(initNewState(state), action);
    case THREADING_ON: return switcherThreadingOn(initNewState(state), action);
    case THREADING_OFF: return switcherThreadingOff(initNewState(state), action);
    case TREADLING_ON: return switcherTreadlingOn(initNewState(state), action);
    case TREADLING_OFF: return switcherTreadlingOff(initNewState(state), action);
    default: return initialState;
  }
}

const reducer4 = combineReducers({switcher4});

export default reducer4;
<commit_msg>Refactoring<commit_after>import { combineReducers } from 'redux';

import {
  WEAVE_ON, WEAVE_OFF,
  THREADING_ON, THREADING_OFF,
  TREADLING_ON, TREADLING_OFF,
  TIE_UP_ON, TIE_UP_OFF} from '../constants';

const initialState = {
  weaves: [],
  numberOfWeaves: 0,
  threadings: [],
  treadlings: [],
  tieUp: []
};

function initNewState(state) {
  return Object.assign({}, state,
    {
      weaves: [...state.weaves],
      numberOfWeaves: state.numberOfWeaves,
      threadings: [...state.threadings],
      treadlings: [...state.treadlings],
      tieUp: [...state.tieUp]
    }
  );
}

function switcherWeaveOn(newState, action) {
  newState.numberOfWeaves++;

  if (newState.weaves[action.row] === undefined)
    newState.weaves[action.row] = [];

  newState.weaves[action.row][action.col] = true;
  return newState;
}

function switcherWeaveOff(newState, action) {
  newState.numberOfWeaves--;

  if (newState.weaves[action.row] === undefined)
    newState.weaves[action.row] = [];

  newState.weaves[action.row][action.col] = false;
  return newState;
}

function checkThreading(newState, row) {
  return newState
    .threadings
    .map((e, i) => {return (e === row) ? i : false})
    .filter((e) => {return (e) ? e : undefined});
}

function checkTreadling(newState, col) {
  return newState
    .treadlings
    .map((e, i) => {return (e === col) ? i : false})
    .filter((e) => {return (e) ? e : undefined});
}

function checkTieUpRow(newState, row) {
  const ret = [];

  if (newState.tieUp[row]) {
    for (let i = 0; i < newState.tieUp[row].length; i++) {
      if (newState.tieUp[row][i] === true) ret.push(i);
    }
  }

  return ret;
}

function checkTieUpCol(newState, col) {
  const ret = [];

  for (let i = 0; i < newState.tieUp.length; i++) {
    const tieUpRow = newState.tieUp[i];

    if (tieUpRow && tieUpRow[col] === true) ret.push(i);
  }

  return ret;
}

function switcherTieUpOn(newState, action) {
  if (newState.tieUp[action.row] === undefined)
    newState.tieUp[action.row] = [];

  newState.tieUp[action.row][action.col] = true;

  const weaveCols = checkThreading(newState, action.row);
  const weaveRows = checkTreadling(newState, action.col);

  for (let r = 0; r < weaveRows.length; r++) {
    const weaveRow = weaveRows[r];

    if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];

    for (let c = 0; c < weaveCols.length; c++) {
      const weaveCol = weaveCols[c];
      newState.weaves[weaveRow][weaveCol] = true;
    }
  }

  return newState;
}

function switcherTieUpOff(newState, action) {
  if (newState.tieUp[action.row] === undefined)
    newState.tieUp[action.row] = [];

  newState.tieUp[action.row][action.col] = false;

  const weaveCols = checkThreading(newState, action.row);
  const weaveRows = checkTreadling(newState, action.col);

  for (let r = 0; r < weaveRows.length; r++) {
    const weaveRow = weaveRows[r];

    if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];

    for (let c = 0; c < weaveCols.length; c++) {
      const weaveCol = weaveCols[c];
      newState.weaves[weaveRow][weaveCol] = false;
    }
  }

  return newState;
}

function switcherThreadingOn(newState, action) {
  newState.threadings[action.col] = action.row;

  const tieUpRows = checkTieUpRow(newState, action.row);

  if (tieUpRows.length) {
    for (let r = 0; r < tieUpRows.length; r++) {
      const treadlingCols = checkTreadling(newState, tieUpRows[r]);

      for (let c = 0; c < treadlingCols.length; c++) {
        const weaveRow = treadlingCols[c];
        if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];
        newState.weaves[weaveRow][action.col] = true;
      }
    }
  } else {
    for (let i = 0; i < newState.weaves.length; i++) {
      if (newState.weaves[i]) newState.weaves[i][action.col] = false;
    }
  }

  return newState;
}

function switcherThreadingOff(newState, action) {
  newState.threadings[action.col] = undefined;

  const tieUpRows = checkTieUpRow(newState, action.row);

  for (let r = 0; r < tieUpRows.length; r++) {
    const treadlingCols = checkTreadling(newState, tieUpRows[r]);

    for (let c = 0; c < treadlingCols.length; c++) {
      const weaveRow = treadlingCols[c];
      if (newState.weaves[weaveRow] === undefined) newState.weaves[weaveRow] = [];
      newState.weaves[weaveRow][action.col] = false;
    }
  }

  return newState;
}

function switcherTreadlingOn(newState, action) {
  newState.treadlings[action.col] = action.row;

  const tieUpCols = checkTieUpCol(newState, action.row/*????*/);

  if (tieUpCols.length) {
    newState.weaves[action.col] = [];

    for (let i = 0; i < tieUpCols.length; i++) {
      const threadingRows = checkThreading(newState, tieUpCols[i]);

      for (let ii = 0; ii < threadingRows.length; ii++) {
        const weaveCol = threadingRows[ii];
        if (newState.weaves[action.col] === undefined) newState.weaves[action.col] = [];
        newState.weaves[action.col][weaveCol] = true;
      }
    }
  } else {
    newState.weaves[action.col] = [];
  }

  return newState;
}

function switcherTreadlingOff(newState, action) {
  newState.treadlings[action.col] = undefined;

  const tieUpCols = checkTieUpCol(newState, action.row/*????*/);

  for (let i = 0; i < tieUpCols.length; i++) {
    const threadingRows = checkThreading(newState, tieUpCols[i]);

    for (let ii = 0; ii < threadingRows.length; ii++) {
      const weaveCol = threadingRows[ii];
      if (newState.weaves[action.col] === undefined) newState.weaves[action.col] = [];
      newState.weaves[action.col][weaveCol] = false;
    }
  }

  return newState;
}

function switcher4(state, action) {
  switch (action.type) {
    case WEAVE_ON: return switcherWeaveOn(initNewState(state), action);
    case WEAVE_OFF: return switcherWeaveOff(initNewState(state), action);
    case TIE_UP_ON: return switcherTieUpOn(initNewState(state), action);
    case TIE_UP_OFF: return switcherTieUpOff(initNewState(state), action);
    case THREADING_ON: return switcherThreadingOn(initNewState(state), action);
    case THREADING_OFF: return switcherThreadingOff(initNewState(state), action);
    case TREADLING_ON: return switcherTreadlingOn(initNewState(state), action);
    case TREADLING_OFF: return switcherTreadlingOff(initNewState(state), action);
    default: return initialState;
  }
}

const reducer4 = combineReducers({switcher4});

export default reducer4;
<|endoftext|>


<commit_before>/**
 * Location Controller
 *
 */
module.exports = {

  ip_lookup: function (req, res) {

    // var geoip = require('geoip-lite');
    var request = require('request');
    var ip = req.headers['x-forwarded-for'] ||
     req.connection.remoteAddress ||
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;

    // var geo = geoip.lookup(ip);

    // if (!geo) return res.notFound();

    // res.ok(geo);
    url = 'http://freegeoip.net/json/' + ip

    request.get(url, function(error, response, body) {
      if (error) return res.notFound();
      res.ok(body);
    })
  },
  address_lookup: function (req, res) {
    var geocoder = require('geocoder');
    var address = req.param('address');

    // Geocoding
    geocoder.geocode(address, function ( err, data ) {
      if (err) return res.notFound();
      res.ok(data.results.geometry.location);
    });
  },
  latlng_lookup: function (req, res) {
    var geocoder = require('geocoder');
    var lat = req.param('lat');
    var lng = req.param('lng');

    geocoder.reverseGeocode(lat, lng, function ( err, data ) {
      if (err) return res.notFound();
      res.ok(data);
    });
  }
}<commit_msg>Ip lookup<commit_after>/**
 * Location Controller
 *
 */
module.exports = {

  ip_lookup: function (req, res) {

    // var geoip = require('geoip-lite');
    var request = require('request');
    var ip = req.headers['x-forwarded-for'] ||
     req.connection.remoteAddress ||
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress;

    // var geo = geoip.lookup(ip);

    // if (!geo) return res.notFound();

    // res.ok(geo);
    url = 'http://freegeoip.net/json/' + ip

    request.get(url, function(error, response, body) {
      if (error) return res.notFound();
      res.ok(body);
    })
  },
  address_lookup: function (req, res) {
    var geocoder = require('geocoder');
    var address = req.param('address');

    // Geocoding
    geocoder.geocode(address, function ( err, data ) {
      if (err) return res.notFound();
      res.ok(data.results.geometry);
    });
  },
  latlng_lookup: function (req, res) {
    var geocoder = require('geocoder');
    var lat = req.param('lat');
    var lng = req.param('lng');

    geocoder.reverseGeocode(lat, lng, function ( err, data ) {
      if (err) return res.notFound();
      res.ok(data);
    });
  }
}<|endoftext|>


<commit_before>import express from 'express';
import nunjucks from 'nunjucks';
import sass from 'node-sass';
import sassMiddleware from 'node-sass-middleware';
import mongoose from 'mongoose';
import Tour from './models/tourSchema';
import Trailer from './models/trailerSchema';
import Press from './models/pressSchema';
import submitBlocks from './submitBlocks';
import specialBlocks from './specialBlocks';
import homeBlocks from './homeBlocks';

const app = express();
require('./models/models');

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

app.use((req, res, next) => {

  const env = nunjucks.configure('views', {
    autoescape: true,
    express: app,
  });

  // Sets Nunjucks as the Express template engine
  app.set('engine', env);

  const randomHash = () => Math.random() * 0xffffffff | 0;
  const counter = () => {
    let count = 0;
    return {
      increment: () => { count++; },
      print: () => { return count; },
      reset: () => { count = 0; },
    };
  };

  const storage = () => {
    let store = {};
    return {
      getItem: (key) => store[key],
      setItem: (key, value) => { store[key] = value; },
      removeItem: (key) => { delete store[key]; },
      clear: () => { store = {}; },
    };
  };
  env.addGlobal('counter', counter());
  env.addGlobal('randomHash', randomHash);
  env.addGlobal('storage', storage());

  next();
});

app.use(sassMiddleware({
  src: './views',
  dest: './public',
  debug: true,
  outputStyle: 'compressed'
}),
express.static('./public'));

app.get('/', (req, res) => {
    res.redirect('/home');
})

// Home page
app.get('/home', (req, res) => {
    Press.find( (err, presses) => {
        if(err) {
            console.log(err);
        }

        res.render('Home/home.html', {
            page: 'home',
            port: app.get('port'),
            presses: presses,
            blocks: homeBlocks,
        });
    });
});

// specials
app.get('/specials', (req, res) => {
  res.render('Specials/specials.html', {
    page: 'specials',
    port: app.get('port'),
    blocks: specialBlocks
  });
});

// submit videos
app.get('/submit', (req, res) => {
    res.render('Submit/submit.html', {
        page: 'submit',
        port: app.get('port'),
        blocks: submitBlocks
    });
});

// tour
app.get('/tour', (req, res) => {
    Tour.find( (err, tours) => {
        if(err) {
            console.log(err);
        }

        res.render('Tour/tour.html', {
            page: 'tour',
            port: app.get('port'),
            tours: tours
        });
    });
});

// watch trailers
app.get('/watch', (req, res) => {
    Trailer.find( (err, trailers) => {
        if(err) {
            console.log(err);
        }

        res.render('Watch/watch.html', {
            page: 'watch',
            port: app.get('port'),
            trailers: [{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            },{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            },{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            }]
        });
    });
});

// shop
app.get('/shop', (req, res) => {
    res.render('Shop/shop.html', {
        page: 'shop',
        port: app.get('port'),
    });
});

// Admin tools
app.get('/admin', (req, res) => {
    res.render('Admin/admin.html', {
        page: 'admin',
        port: app.get('port'),
    });
});

// Kick start our server
app.listen(app.get('port'), () => {
  console.log('Server started on port', app.get('port'));
});
<commit_msg>rebuild<commit_after>import express from 'express';
import nunjucks from 'nunjucks';
import sass from 'node-sass';
import sassMiddleware from 'node-sass-middleware';
import mongoose from 'mongoose';
import Tour from './models/tourSchema';
import Trailer from './models/trailerSchema';
import Press from './models/pressSchema';
import submitBlocks from './submitBlocks';
import specialBlocks from './specialBlocks';
import homeBlocks from './homeBlocks';

const app = express();
require('./models/models');

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

app.use((req, res, next) => {

  const env = nunjucks.configure('views', {
    autoescape: true,
    express: app,
  });

  // Sets Nunjucks as the Express template engine
  app.set('engine', env);

  const randomHash = () => Math.random() * 0xffffffff | 0;
  const counter = () => {
    let count = 0;
    return {
      increment: () => { count++; },
      print: () => { return count; },
      reset: () => { count = 0; },
    };
  };

  const storage = () => {
    let store = {};
    return {
      getItem: (key) => store[key],
      setItem: (key, value) => { store[key] = value; },
      removeItem: (key) => { delete store[key]; },
      clear: () => { store = {}; },
    };
  };
  env.addGlobal('counter', counter());
  env.addGlobal('randomHash', randomHash);
  env.addGlobal('storage', storage());

  next();
});

app.use(sassMiddleware({
  src: './views',
  dest: './public',
  debug: true,
  outputStyle: 'compressed'
}),
express.static('./public'));

app.get('/', (req, res) => {
    res.redirect('/home');
});

// Home page
app.get('/home', (req, res) => {
    Press.find( (err, presses) => {
        if(err) {
            console.log(err);
        }

        res.render('Home/home.html', {
            page: 'home',
            port: app.get('port'),
            presses: presses,
            blocks: homeBlocks,
        });
    });
});

// specials
app.get('/specials', (req, res) => {
  res.render('Specials/specials.html', {
    page: 'specials',
    port: app.get('port'),
    blocks: specialBlocks
  });
});

// submit videos
app.get('/submit', (req, res) => {
    res.render('Submit/submit.html', {
        page: 'submit',
        port: app.get('port'),
        blocks: submitBlocks
    });
});

// tour
app.get('/tour', (req, res) => {
    Tour.find( (err, tours) => {
        if(err) {
            console.log(err);
        }

        res.render('Tour/tour.html', {
            page: 'tour',
            port: app.get('port'),
            tours: tours
        });
    });
});

// watch trailers
app.get('/watch', (req, res) => {
    Trailer.find( (err, trailers) => {
        if(err) {
            console.log(err);
        }

        res.render('Watch/watch.html', {
            page: 'watch',
            port: app.get('port'),
            trailers: [{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            },{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            },{
                name: 'name',
                date: Date.now(),
                votes: 123123,
                link: 'https://www.youtube.com/watch?v=p9nqQuu4lmQ',
                category: {
                    type: 'Video',
                    enum: ['Photo', 'Video']
                }
            }]
        });
    });
});

// shop
app.get('/shop', (req, res) => {
    res.render('Shop/shop.html', {
        page: 'shop',
        port: app.get('port'),
    });
});

// Admin tools
app.get('/admin', (req, res) => {
    res.render('Admin/admin.html', {
        page: 'admin',
        port: app.get('port'),
    });
});

// Kick start our server
app.listen(app.get('port'), () => {
  console.log('Server started on port', app.get('port'));
});
<|endoftext|>


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

// Types
import type {
  Action,
} from 'types';

// Describes the schedule state.
type State = {
  view: number,         // Current view to display in the Find navigator
};

// Initial schedule state.
const initialState: State = {
  view: 0,
};

/**
 * When provided with a schedule action, parses the parameters and returns an updated state.
 *
 * @param {State}  state  the current state
 * @param {Action} action the action being taken
 * @returns {State} an updated state based on the previous state and the action taken.
 */
function find(state: State = initialState, action: Action): State {
  switch (action.type) {
    case 'SCHEDULE_VIEW':
      return {
        ...state,
        view: action.view,
      };
    default:
      return state;
  }
}

module.exports = find;
<commit_msg>Fix wrongly named variables<commit_after>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @created 2016-10-27
 * @file schedule.js
 * @description Reducers for schedule actions
 *
 * @flow
 */
'use strict';

// Types
import type {
  Action,
} from 'types';

// Describes the schedule state.
type State = {
  view: number, // Current view to display in the schedule navigator
};

// Initial schedule state.
const initialState: State = {
  view: 0,
};

/**
 * When provided with a schedule action, parses the parameters and returns an updated state.
 *
 * @param {State}  state  the current state
 * @param {Action} action the action being taken
 * @returns {State} an updated state based on the previous state and the action taken.
 */
function schedule(state: State = initialState, action: Action): State {
  switch (action.type) {
    case 'SCHEDULE_VIEW':
      return {
        ...state,
        view: action.view,
      };
    default:
      return state;
  }
}

module.exports = schedule;
<|endoftext|>


<commit_before>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

define([
    "jquery",
    "base1/cockpit",
    "kubernetes/angular",
    "kubernetes/d3",
    "kubernetes/object-describer"
], function($, cockpit, angular, d3) {
    "use strict";

    var _ = cockpit.gettext;

    var icons = {
        Pod: '\uf1b3', /* fa-cubes */
        ReplicationController: '\uf1b8', /* fa-cog */
        Node: '\uf1c0', /* fa-database */
        Service: '\uf0ec', /* fa-exchange */
    };

    function topology_graph(selector, client, notify) {

        var outer = d3.select(selector);

        var width;
        var height;

        var all = { };
        var nodes = [];
        var links = [];

        var force = d3.layout.force()
            .charge(-400)
            .linkDistance(40);

        var drag = force.drag();

        var svg = outer.append("svg").attr("class", "kube-topology");

        var node = d3.select();
        var link = d3.select();

        force.on("tick", function() {
            link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
        });

        drag
            .on("dragstart", function(d) {
                notify(d);
                svg.selectAll("g").classed("selected", false);
                d3.select(this).classed("selected", true);

                d.fixed = true;
                d3.select(this).classed("fixed", true);
            })
            .on("dragend", function(d) {
                d.fixed = (d.x > 3 && d.x < (width - 3) && d.y >= 3 && d.y < (height - 3));
                d3.select(this).classed("fixed", d.fixed);
            });

        function dblclick(d) {
            d3.select(this).classed("fixed", d.fixed = false); /* jshint ignore:line */
        }

        function adjust() {
            force.size([width, height]);
            svg.attr("width", width).attr("height", height);
            update();
        }

        function update() {
            link = svg.selectAll("line")
                .data(links);

            link.exit().remove();
            link.enter().append("line");

            link.attr("class", function(d) { return d.kind; });

            node = svg.selectAll("g")
                .data(nodes, function(d) { return d.metadata.uid; });

            node.exit().remove();

            var group = node.enter().append("g")
                .attr("class", function(d) { return d.kind; })
                .on("dblclick", dblclick)
                .call(drag);

            group.append("circle")
                .attr("r", 15);
            group.append("text")
                .attr("y", 6)
                .text(function(d) { return icons[d.kind]; });
            group.append("title")
                .text(function(d) { return d.metadata.name; });

            /* HACK: around broken fonts */
            group.selectAll("g.ReplicationController > text")
                .attr("dy", "1");

            force
                .nodes(nodes)
                .links(links)
                .start();
        }

        function digest() {

            /* The actual data for the graph */
            nodes = [];
            links = [];

            /* Lookup of key to node index */
            var lookup = { };

            /* Items we're going to use for links */
            var leaves = { "Service": [], "Node": [], "ReplicationController": [] };

            var i, len, item, key, leaf, kind, pods;
            var items = all.items;
            for (i = 0, len = items.length; i < len; i++) {
                item = items[i];

                kind = item.kind;
                leaf = leaves[kind];

                if (leaf)
                    leaf.push(item);
                else if (kind !== "Pod")
                    continue;

                lookup[item.metadata.uid] = nodes.length;
                nodes.push(item);
            }

            var isnode, isservice;
            for (kind in leaves) {
                leaf = leaves[kind];
                for (i = 0, len = leaf.length; i < len; i++) {
                    item = leaf[i];
                    isnode = kind === "Node";
                    isservice = kind === "Service";
                    if (isnode)
                        pods = client.hosting("Pod", item.metadata.name);
                    else
                        pods = client.select("Pod", item.metadata.namespace, item.spec.selector);
                    for (key in pods) {

                        /* Don't link pods that aren't running to services */
                        if (isservice && pods[key].status.phase !== "Running")
                            continue;

                        links.push({
                            source: lookup[item.metadata.uid],
                            target: lookup[key],
                            kind: kind,
                        });
                    }
                }
            }

            update();
        }

        function resized() {
            width = outer.node().clientWidth;
            height = window.innerHeight - 15;
            adjust();
        }

        $(window).on('resize', resized);
        resized();

        client.wait(function() {
            all = client.select();
            client.track(all);
            $(all).on("changed", digest);
            digest();
        });

        return {
            close: function() {
                $(window).off('resize', resized);
                client.track(all, false);
                $(all).off();
            }
        };
    }

    return angular.module('kubernetes.topology', [ 'ngRoute', 'kubernetesUI' ])
        .config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/topology', {
                templateUrl: 'topology.html',
                controller: 'TopologyCtrl'
            });
        }])
        .controller('TopologyCtrl', [
                '$scope',
                'kubernetesClient',
                function($scope, client) {
            $scope.client = client;
            $scope.selected = null;
        }])
        .directive('kubeTopology', [
            'kubernetesClient',
            function(client) {
                return {
                    restrict: 'E',
                    link: function($scope, element, attributes) {
                        function notify(item) {
                            $scope.selected = item;
                            $scope.$digest();
                        }

                        var graph = topology_graph(element[0], client, notify);
                        element.on("$destroy", function() {
                            graph.close();
                        });
                    }
                };
            }
        ]);
});
<commit_msg>kubernetes: Stable nodes in topology graph<commit_after>/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

define([
    "jquery",
    "base1/cockpit",
    "kubernetes/angular",
    "kubernetes/d3",
    "kubernetes/object-describer"
], function($, cockpit, angular, d3) {
    "use strict";

    var _ = cockpit.gettext;

    var icons = {
        Pod: '\uf1b3', /* fa-cubes */
        ReplicationController: '\uf1b8', /* fa-cog */
        Node: '\uf1c0', /* fa-database */
        Service: '\uf0ec', /* fa-exchange */
    };

    function topology_graph(selector, client, notify) {

        var outer = d3.select(selector);

        var width;
        var height;

        var all = { };
        var nodes = [];
        var links = [];
        var lookup = { };

        var force = d3.layout.force()
            .charge(-400)
            .linkDistance(40);

        var drag = force.drag();

        var svg = outer.append("svg").attr("class", "kube-topology");

        var node = d3.select();
        var link = d3.select();

        force.on("tick", function() {
            link.attr("x1", function(d) { return d.source.x; })
                .attr("y1", function(d) { return d.source.y; })
                .attr("x2", function(d) { return d.target.x; })
                .attr("y2", function(d) { return d.target.y; });

            node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
        });

        drag
            .on("dragstart", function(d) {
                notify(d);
                svg.selectAll("g").classed("selected", false);
                d3.select(this).classed("selected", true);

                d.fixed = true;
                d3.select(this).classed("fixed", true);
            })
            .on("dragend", function(d) {
                d.fixed = (d.x > 3 && d.x < (width - 3) && d.y >= 3 && d.y < (height - 3));
                d3.select(this).classed("fixed", d.fixed);
            });

        function dblclick(d) {
            d3.select(this).classed("fixed", d.fixed = false); /* jshint ignore:line */
        }

        function adjust() {
            force.size([width, height]);
            svg.attr("width", width).attr("height", height);
            update();
        }

        function update() {
            link = svg.selectAll("line")
                .data(links);

            link.exit().remove();
            link.enter().append("line");

            link.attr("class", function(d) { return d.kind; });

            node = svg.selectAll("g")
                .data(nodes, function(d) { return d.metadata.uid; });

            node.exit().remove();

            var group = node.enter().append("g")
                .attr("class", function(d) { return d.kind; })
                .on("dblclick", dblclick)
                .call(drag);

            group.append("circle")
                .attr("r", 15);
            group.append("text")
                .attr("y", 6)
                .text(function(d) { return icons[d.kind]; });
            group.append("title")
                .text(function(d) { return d.metadata.name; });

            /* HACK: around broken fonts */
            group.selectAll("g.ReplicationController > text")
                .attr("dy", "1");

            force
                .nodes(nodes)
                .links(links)
                .start();
        }

        function digest() {
            var pnodes = nodes;
            var plookup = lookup;

            /* The actual data for the graph */
            nodes = [];
            links = [];
            lookup = { };

            /* Items we're going to use for links */
            var leaves = { "Service": [], "Node": [], "ReplicationController": [] };

            var i, len, item, key, leaf, kind, pods, old;
            var items = all.items;
            for (i = 0, len = items.length; i < len; i++) {
                item = items[i];

                key = item.metadata.uid;
                kind = item.kind;
                leaf = leaves[kind];

                if (leaf) {

                    /* Prevents flicker */
                    old = pnodes[plookup[key]];
                    if (old) {
                        item.x = old.x;
                        item.y = old.y;
                        item.px = old.px;
                        item.py = old.py;
                        item.fixed = old.fixed;
                        item.weight = old.weight;
                    }

                    leaf.push(item);

                } else if (kind !== "Pod") {
                    continue;
                }

                lookup[key] = nodes.length;
                nodes.push(item);
            }

            var isnode, isservice;
            for (kind in leaves) {
                leaf = leaves[kind];
                for (i = 0, len = leaf.length; i < len; i++) {
                    item = leaf[i];
                    isnode = kind === "Node";
                    isservice = kind === "Service";
                    if (isnode)
                        pods = client.hosting("Pod", item.metadata.name);
                    else
                        pods = client.select("Pod", item.metadata.namespace, item.spec.selector);
                    for (key in pods) {

                        /* Don't link pods that aren't running to services */
                        if (isservice && pods[key].status.phase !== "Running")
                            continue;

                        links.push({
                            source: lookup[item.metadata.uid],
                            target: lookup[key],
                            kind: kind,
                        });
                    }
                }
            }

            update();
        }

        function resized() {
            width = outer.node().clientWidth;
            height = window.innerHeight - 15;
            adjust();
        }

        $(window).on('resize', resized);
        resized();

        client.wait(function() {
            all = client.select();
            client.track(all);
            $(all).on("changed", digest);
            digest();
        });

        return {
            close: function() {
                $(window).off('resize', resized);
                client.track(all, false);
                $(all).off();
            }
        };
    }

    return angular.module('kubernetes.topology', [ 'ngRoute', 'kubernetesUI' ])
        .config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/topology', {
                templateUrl: 'topology.html',
                controller: 'TopologyCtrl'
            });
        }])
        .controller('TopologyCtrl', [
                '$scope',
                'kubernetesClient',
                function($scope, client) {
            $scope.client = client;
            $scope.selected = null;
        }])
        .directive('kubeTopology', [
            'kubernetesClient',
            function(client) {
                return {
                    restrict: 'E',
                    link: function($scope, element, attributes) {
                        function notify(item) {
                            $scope.selected = item;
                            $scope.$digest();
                        }

                        var graph = topology_graph(element[0], client, notify);
                        element.on("$destroy", function() {
                            graph.close();
                        });
                    }
                };
            }
        ]);
});
<|endoftext|>


<commit_before>var concat = require('concat-stream')
    , os = require('os')
    , streamify = require('stream-array')
    , stringify = require('..')
    , test = require('tape')
;

test('newline separated ints', function(t) {
    streamify([1,2,3]).pipe(stringify()).pipe(concat(function(res) {
        var match = [1,2,3].join(os.EOL);

        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal(match, res.toString(), 'result matches expectation');

        t.end();
    }));
});

test('array of ints', function(t) {
    var opts = {open:'[', close:']'};

    streamify([1,2,3]).pipe(stringify(opts)).pipe(concat(function(res) {
        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal('[1,2,3]', res.toString(), 'result matches expectation');

        t.end();
    }));
});

test('array of objects with unicode', function (t) {
    streamify([{ obj: '\u00bd' }, { otherObj: '\u00bc' }, { lastObj: '\u00be'}])
        .pipe(stringify())
        .pipe(concat(function (res) {
            t.type(res, 'Buffer', 'concat results into a buffer');
            t.equals('{"obj":"\u00bd"}\n{"otherObj":"\u00bc"}\n{"lastObj":"\u00be"}', res.toString(), 'result matches expectation');
            t.end();
    }));
});

test('pretty-print array of objects', function(t) {
    streamify([{one:1}]).pipe(stringify(null, null, '\t')).pipe(concat(function(res) {
        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal('{\n\t"one": 1\n}', res.toString(), 'result matches expectation');

        t.end();
    }));
});
<commit_msg>test/2.js :: update for tape's API<commit_after>var concat = require('concat-stream')
    , os = require('os')
    , streamify = require('stream-array')
    , stringify = require('..')
    , test = require('tape')
;

test('newline separated ints', function(t) {
    streamify([1,2,3]).pipe(stringify()).pipe(concat(function(res) {
        var match = [1,2,3].join(os.EOL);

        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal(match, res.toString(), 'result matches expectation');

        t.end();
    }));
});

test('array of ints', function(t) {
    var opts = {open:'[', close:']'};

    streamify([1,2,3]).pipe(stringify(opts)).pipe(concat(function(res) {
        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal('[1,2,3]', res.toString(), 'result matches expectation');

        t.end();
    }));
});

test('array of objects with unicode', function (t) {
    streamify([{ obj: '\u00bd' }, { otherObj: '\u00bc' }, { lastObj: '\u00be'}])
        .pipe(stringify())
        .pipe(concat(function (res) {
            t.ok(Buffer.isBuffer(res), 'concat results into a buffer');
            t.equals('{"obj":"\u00bd"}\n{"otherObj":"\u00bc"}\n{"lastObj":"\u00be"}', res.toString(), 'result matches expectation');
            t.end();
    }));
});

test('pretty-print array of objects', function(t) {
    streamify([{one:1}]).pipe(stringify(null, null, '\t')).pipe(concat(function(res) {
        t.ok(Buffer.isBuffer(res), 'concat results into a Buffer');
        t.equal('{\n\t"one": 1\n}', res.toString(), 'result matches expectation');

        t.end();
    }));
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');

var routes = require('./routes/index');
routes.publicFolderNm = 'public';
routes.combineJs = true;
var app = express();

// view engine setup
app.set('views', path.join(__dirname, routes.publicFolderNm));
app.set('view engine', 'ejs');

// trust proxy
app.set('trust proxy', true);

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());

//CORS and Referer validation
var validClients = [".*"];
try {
    validClients = JSON.parse(fs.readFileSync(path.join(__dirname, 'client-whitelist.json')).toString()).validClients;
}
catch (err) {}
validClients = validClients.map(function(v) {
    return new RegExp(v);
});

app.use(function(req, res, next) {
    // Referer
    if (req.headers.referer) {
        if (!validClients.some(function(v) {
                return v.test(req.headers.referer);
            })) {
            return res.status(403).end();
        }
    }

    if (req.headers.origin) {
        if (validClients.some(function(v) {
                return v.test(req.headers.origin);
            })) {
            res.header('Access-Control-Allow-Origin', req.headers.origin);
            if (req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
            }
            if (req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
            }
            // preflight caching age set to 1 day
            res.header('Access-Control-Max-Age', 86400);
            // intercept preflight OPTIONS method
            if (req.method === 'OPTIONS') {
                return res.status(200).end();
            }
        }
        else {
            return res.status(403).end();
        }
    }
    next();
});

app.use(express.static(path.join(__dirname, routes.publicFolderNm, 'assets')));

app.use('/', routes);

app.use(function(req, res, next) {
    require('fs').exists(path.join(__dirname, routes.publicFolderNm, 'assets', req.path + '.ejs'), function(exists) {
        if (exists) {
            res.type(path.extname(req.path));
            res.render(path.join('assets', req.path + '.ejs'), {
                unippearHost: req.protocol + "://" + req.host
            });

        }
        else {
            next();
        }
    });
});

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('api/error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('api/error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});

module.exports = app;
<commit_msg>add unippear host to client whitelist automatically<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');

var routes = require('./routes/index');
routes.publicFolderNm = 'public';
routes.combineJs = true;
var app = express();

// view engine setup
app.set('views', path.join(__dirname, routes.publicFolderNm));
app.set('view engine', 'ejs');

// trust proxy
app.set('trust proxy', true);

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());

//CORS and Referer validation
var validClients = [".*"];
try {
    validClients = JSON.parse(fs.readFileSync(path.join(__dirname, 'client-whitelist.json')).toString()).validClients;
}
catch (err) {}
validClients = validClients.map(function(v) {
    return new RegExp(v);
});

app.use(function(req, res, next) {
    // Referer
    if (req.headers.referer) {
        if (!validClients.some(function(v) {
                return v.test(req.headers.referer);
            }) && req.headers.referer.indexOf(req.protocol + "://" + req.host) !== 0) {
            return res.status(403).end();
        }
    }

    if (req.headers.origin) {
        if (validClients.some(function(v) {
                return v.test(req.headers.origin);
            }) || req.headers.origin.indexOf(req.protocol + "://" + req.host) === 0) {
            res.header('Access-Control-Allow-Origin', req.headers.origin);
            if (req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
            }
            if (req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
            }
            // preflight caching age set to 1 day
            res.header('Access-Control-Max-Age', 86400);
            // intercept preflight OPTIONS method
            if (req.method === 'OPTIONS') {
                return res.status(200).end();
            }
        }
        else {
            return res.status(403).end();
        }
    }
    next();
});

app.use(express.static(path.join(__dirname, routes.publicFolderNm, 'assets')));

app.use('/', routes);

app.use(function(req, res, next) {
    require('fs').exists(path.join(__dirname, routes.publicFolderNm, 'assets', req.path + '.ejs'), function(exists) {
        if (exists) {
            res.type(path.extname(req.path));
            res.render(path.join('assets', req.path + '.ejs'), {
                unippearHost: req.protocol + "://" + req.host
            });

        }
        else {
            next();
        }
    });
});

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('api/error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('api/error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});

module.exports = app;
<|endoftext|>