<commit_before>const dgram           = require('dgram')
    , util            = require('util')
    , events          = require('events')
    , LRU             = require('lru-cache')
    , parse           = require('coap-packet').parse
    , generate        = require('coap-packet').generate
    , IncomingMessage = require('./incoming_message')
    , OutgoingMessage = require('./outgoing_message')
    , parameters      = require('./parameters')
    , RetrySend       = require('./retry_send')

function CoAPServer(options, listener) {
  if (!(this instanceof CoAPServer)) {
    return new CoAPServer(options)
  }

  if (typeof options === 'function') {
    listener = options
    options = null
  }

  if (!options)
    options = {}

  var that = this
  this._sock = dgram.createSocket('udp4', function(msg, rsinfo) {
    var packet
    try {
      packet = parse(msg)
    } catch(err) {
      var message = generate({ code: '5.00', payload: new Buffer('Unable to parse packet') })
      that._sock.send(message, 0, message.length,
                      rsinfo.port, rsinfo.address)
      return
    }

    that._handle(packet, rsinfo)
  })

  // We use an LRU cache for the responses to avoid
  // DDOS problems.
  // max packet size is 1280
  // 32 MB / 1280 = 26214
  // The max lifetime is roughly 200s per packet.
  // Which gave us 131 packets/second guarantee
  this._lru = LRU({
      max: options.cacheSize || (32768 * 1024)
    , length: function(n) { return n.length }
    , maxAge: parameters.exchangeLifetime
    , dispose:  function(key, value) {
                  if (value.sender)
                    value.sender.reset()
                }
  })

  if (listener)
    this.on('request', listener)
}

util.inherits(CoAPServer, events.EventEmitter)

CoAPServer.prototype.listen = function(port, address, done) {
  if (typeof port === 'function') {
    done = port
    port = parameters.coapPort
  }

  if (typeof address === 'function') {
    done = address
    address = null
  }

  this._sock.bind(port, address, done)
  this._port = port
  this._address = address

  return this
}

CoAPServer.prototype.close = function(done) {
  this._sock.close()

  this._lru.reset()

  if (done) {
    done()
  }

  return this
}

CoAPServer.prototype._handle = function(packet, rsinfo) {
  var sender    = new RetrySend(this._sock, rsinfo.port,
                                rsinfo.address)

    , lru       = this._lru
    , acks      = this._acks
    , cached    = lru.peek(toKey(rsinfo.address, rsinfo.port, packet))

    , request
    , response

  if (cached && !packet.ack)
    return sender.send(cached)
  else if (cached && packet.ack)
    return lru.del(toKey(rsinfo.address, rsinfo.port, packet))

  request = new IncomingMessage(packet)
  response = new OutgoingMessage(packet, function(packet) {
    var buf

    try {
      buf = generate(packet)
    } catch(err) {
      return response.emit('error', err)
    }

    if (!packet.ack)
      buf.sender = sender

    if (!cached)
      lru.set(toKey(rsinfo.address, rsinfo.port, packet), buf)

    sender.send(buf, !packet.ack)
  })

  response.statusCode = '2.00'

  sender.on('error', response.emit.bind(response, 'error'))

  this.emit('request', request, response)
}

function toKey(address, port, packet) {
  return address + port + packet.token.toString('hex') + packet.messageId
}

module.exports = CoAPServer
<commit_msg>Removed spurious test failures.<commit_after>const dgram           = require('dgram')
    , util            = require('util')
    , events          = require('events')
    , LRU             = require('lru-cache')
    , parse           = require('coap-packet').parse
    , generate        = require('coap-packet').generate
    , IncomingMessage = require('./incoming_message')
    , OutgoingMessage = require('./outgoing_message')
    , parameters      = require('./parameters')
    , RetrySend       = require('./retry_send')

function CoAPServer(options, listener) {
  if (!(this instanceof CoAPServer)) {
    return new CoAPServer(options)
  }

  if (typeof options === 'function') {
    listener = options
    options = null
  }

  if (!options)
    options = {}

  var that = this
  this._sock = dgram.createSocket('udp4', function(msg, rsinfo) {
    var packet
    try {
      packet = parse(msg)
    } catch(err) {
      var message = generate({ code: '5.00', payload: new Buffer('Unable to parse packet') })
      that._sock.send(message, 0, message.length,
                      rsinfo.port, rsinfo.address)
      return
    }

    that._handle(packet, rsinfo)
  })

  // We use an LRU cache for the responses to avoid
  // DDOS problems.
  // max packet size is 1280
  // 32 MB / 1280 = 26214
  // The max lifetime is roughly 200s per packet.
  // Which gave us 131 packets/second guarantee
  this._lru = LRU({
      max: options.cacheSize || (32768 * 1024)
    , length: function(n) { return n.length }
    , maxAge: parameters.exchangeLifetime
    , dispose:  function(key, value) {
                  if (value.sender)
                    value.sender.reset()
                }
  })

  if (listener)
    this.on('request', listener)
}

util.inherits(CoAPServer, events.EventEmitter)

CoAPServer.prototype.listen = function(port, address, done) {
  if (typeof port === 'function') {
    done = port
    port = parameters.coapPort
  }

  if (typeof address === 'function') {
    done = address
    address = null
  }

  this._sock.bind(port, address, done)
  this._port = port
  this._address = address

  return this
}

CoAPServer.prototype.close = function(done) {
  this._sock.close()

  this._lru.reset()

  if (done) {
    done()
  }

  return this
}

CoAPServer.prototype._handle = function(packet, rsinfo) {
  var sender    = new RetrySend(this._sock, rsinfo.port,
                                rsinfo.address)

    , lru       = this._lru
    , acks      = this._acks
    , cached    = lru.peek(toKey(rsinfo.address, rsinfo.port, packet))

    , request
    , response

  if (cached && !packet.ack)
    return sender.send(cached)
  else if (cached && packet.ack)
    return lru.del(toKey(rsinfo.address, rsinfo.port, packet))
  else if (packet.ack)
    return // nothing to do, ignoring silently

  request = new IncomingMessage(packet)
  response = new OutgoingMessage(packet, function(packet) {
    var buf

    try {
      buf = generate(packet)
    } catch(err) {
      return response.emit('error', err)
    }

    if (!packet.ack)
      buf.sender = sender

    if (!cached)
      lru.set(toKey(rsinfo.address, rsinfo.port, packet), buf)

    sender.send(buf, !packet.ack)
  })

  response.statusCode = '2.00'

  sender.on('error', response.emit.bind(response, 'error'))

  this.emit('request', request, response)
}

function toKey(address, port, packet) {
  return address + port + packet.token.toString('hex') + packet.messageId
}

module.exports = CoAPServer
<|endoftext|>


<commit_before>angular
	.module('daily', ['ngRoute'])
	.service('historyParams', function() {
		var component, testCase, metric;

		return {
			getParams: function() {
				return {component: component, testCase: testCase, metric: metric};
			},
			setParams: function(_component, _testCase, _metric) {
				component = _component;
				testCase = _testCase;
				metric = _metric;
			}
		}
	})
	.config(function($routeProvider, $locationProvider) {
		$locationProvider.hashPrefix('');
		$routeProvider
			.when('/dashboard', {templateUrl: 'static/dashboard.html', controller: DashboardCtrl})
			.when('/history', {templateUrl: 'static/history.html', controller: HistoryCtrl})
			.otherwise({redirectTo: 'dashboard'});
	});

function DashboardCtrl($scope, $http, historyParams) {
	$( "#dashboard" ).show();

	$http.get('api/v1/builds').then(function(response) {
		$scope.builds = response.data;
		if ($scope.builds.indexOf('4.6.0-3572') !== -1) {
			$scope.lhb = '4.6.0-3572';
		} else {
			$scope.lhb = $scope.builds[0];
		};
		$scope.rhb = $scope.builds[$scope.builds.length - 1];
	});

	$scope.$watch('lhb', function() {
		Compare($scope, $http);
	});

	$scope.$watch('rhb', function() {
		Compare($scope, $http);
	});

	$scope.evalStatus = evalStatus;

	$scope.getValue = getValue;

	$scope.calcDelta = calcDelta;

	$scope.getReports = getReports;

	$scope.showHistory = function(component, testCase, metric) {
		historyParams.setParams(component, testCase, metric);
	};
}

function Compare($scope, $http) {
	if ( $scope.lhb === undefined || $scope.rhb === undefined ) {
		return;
	}

	$http.get('api/v1/comparison/' + $scope.lhb + '/' + $scope.rhb).then(function(response) {
		$scope.comparisons = response.data;
	});
}

function evalStatus(results, threshold) {
	if (results.length === 1) {
		return "Incomplete";
	}

	var delta = 100 * (results[1].value / results[0].value - 1);

	if (threshold < 0 && delta < threshold) {
		return "Failed"
	}
	if (threshold > 0 && delta > threshold) {
		return "Failed"
	}

	return "Passed";
}

function getValue(results, build) {
	for (var i = 0; i < results.length; i++) {
		if (results[i].build === build) {
			return results[i].value.toLocaleString();
		}
	}
	return '';
}

function calcDelta(results) {
	var delta = 100 * (results[1].value / results[0].value - 1);
	if (delta > 0) {
		return "+" + delta.toFixed(1);
	}
	return delta.toFixed(1);
}

function getReports(results) {
	var reports = [];

	if (results[0].snapshots.length !== results[1].snapshots.length) {
		return reports;
	}

	for (var i = 0; i < results.length; i++) {
		for (var j = 0; j < results[i].snapshots.length; j++) {
			var snapshot = results[i].snapshots[j];
			var report = 'http://cbmonitor.sc.couchbase.com/reports/html/?snapshot=' + snapshot;
			reports.push(report);
		}
	}

	return reports;
}
<commit_msg>Bump up baseline build<commit_after>angular
	.module('daily', ['ngRoute'])
	.service('historyParams', function() {
		var component, testCase, metric;

		return {
			getParams: function() {
				return {component: component, testCase: testCase, metric: metric};
			},
			setParams: function(_component, _testCase, _metric) {
				component = _component;
				testCase = _testCase;
				metric = _metric;
			}
		}
	})
	.config(function($routeProvider, $locationProvider) {
		$locationProvider.hashPrefix('');
		$routeProvider
			.when('/dashboard', {templateUrl: 'static/dashboard.html', controller: DashboardCtrl})
			.when('/history', {templateUrl: 'static/history.html', controller: HistoryCtrl})
			.otherwise({redirectTo: 'dashboard'});
	});

function DashboardCtrl($scope, $http, historyParams) {
	$( "#dashboard" ).show();

	$http.get('api/v1/builds').then(function(response) {
		$scope.builds = response.data;
		if ($scope.builds.indexOf('4.6.0-3573') !== -1) {
			$scope.lhb = '4.6.0-3573';
		} else {
			$scope.lhb = $scope.builds[0];
		};
		$scope.rhb = $scope.builds[$scope.builds.length - 1];
	});

	$scope.$watch('lhb', function() {
		Compare($scope, $http);
	});

	$scope.$watch('rhb', function() {
		Compare($scope, $http);
	});

	$scope.evalStatus = evalStatus;

	$scope.getValue = getValue;

	$scope.calcDelta = calcDelta;

	$scope.getReports = getReports;

	$scope.showHistory = function(component, testCase, metric) {
		historyParams.setParams(component, testCase, metric);
	};
}

function Compare($scope, $http) {
	if ( $scope.lhb === undefined || $scope.rhb === undefined ) {
		return;
	}

	$http.get('api/v1/comparison/' + $scope.lhb + '/' + $scope.rhb).then(function(response) {
		$scope.comparisons = response.data;
	});
}

function evalStatus(results, threshold) {
	if (results.length === 1) {
		return "Incomplete";
	}

	var delta = 100 * (results[1].value / results[0].value - 1);

	if (threshold < 0 && delta < threshold) {
		return "Failed"
	}
	if (threshold > 0 && delta > threshold) {
		return "Failed"
	}

	return "Passed";
}

function getValue(results, build) {
	for (var i = 0; i < results.length; i++) {
		if (results[i].build === build) {
			return results[i].value.toLocaleString();
		}
	}
	return '';
}

function calcDelta(results) {
	var delta = 100 * (results[1].value / results[0].value - 1);
	if (delta > 0) {
		return "+" + delta.toFixed(1);
	}
	return delta.toFixed(1);
}

function getReports(results) {
	var reports = [];

	if (results[0].snapshots.length !== results[1].snapshots.length) {
		return reports;
	}

	for (var i = 0; i < results.length; i++) {
		for (var j = 0; j < results[i].snapshots.length; j++) {
			var snapshot = results[i].snapshots[j];
			var report = 'http://cbmonitor.sc.couchbase.com/reports/html/?snapshot=' + snapshot;
			reports.push(report);
		}
	}

	return reports;
}
<|endoftext|>


<commit_before>'use strict';

var striptags = require('striptags');

var Answer      = require('mongoose').model('Answer'),
    Country     = require('mongoose').model('Country'),
    Question    = require('mongoose').model('Question'),
    Assessment  = require('mongoose').model('Assessment');

var filterAnswerScoreHistory = function(answer, skipJustificationComparison) {
    ['researcher', 'reviewer'].forEach(function(role) {
        var field = role + '_score_history';
        answer['raw_' + field] = answer[field].slice();
        answer[field] = getFilteredScoreHistory(answer[field], skipJustificationComparison);
    });
};

var getFilteredScoreHistory = function(rawHistory, skipJustificationComparison) {
    if(rawHistory.length <= 1) {
        return rawHistory;
    }

    var getScoreValue = function(score) {
        return (score === undefined) || (score === null) ? score : score.value;
    };

    var filteredHistory = [rawHistory[0]];

    for(var hisoryIndex = 1; hisoryIndex < rawHistory.length; hisoryIndex++) {
        var prevHistoryRecord = rawHistory[hisoryIndex - 1];
        var historyRecord = rawHistory[hisoryIndex];

        if((getScoreValue(historyRecord.score) !== getScoreValue(prevHistoryRecord.score)) ||
            ((historyRecord.justification !== prevHistoryRecord.justification) && !skipJustificationComparison)) {
            filteredHistory.push(historyRecord);
        }
    }

    return filteredHistory;
};

exports.getAnswers = function (req, res, next) {
    if (req.user.hasRole('supervisor')) {
        Answer.find(req.query)
            .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
            .populate('references.author', 'firstName lastName role')
            .exec(function (err, answers) {
                if (err) { return next(err); }
                if (!answers) { return next(new Error('No answers found')); }

                answers.forEach(function(answer) {
                    filterAnswerScoreHistory(answer);
                });

                res.send(answers);
            });
    } else {
        var criteria = {};
        criteria[req.user.role + '_ID'] = req.user._id;

        Assessment.find(criteria, {assessment_ID: 1}, function (err, assessments) {
            var assessments_ids = assessments.map(function (doc) { return doc.assessment_ID; });

            if (err) { return next(err); }
            if (!assessments) { return next(new Error('No assessments assigned to user')); }

            if (assessments_ids.indexOf(req.query.assessment_ID) > -1) {
                Answer.find(req.query)
                    .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
                    .exec(function (err, answers) {
                        if (err) { return next(err); }
                        if (!answers) { return next(new Error('No answers found')); }
                        res.send(answers);
                    });
            } else {
                res.sendStatus(404);
                return res.end();
            }
        });
    }
};

exports.listPublicData = function(req, res) {
    if (req.params.assessment_ID !== undefined) {
        Answer.find({assessment_ID: req.params.assessment_ID})
            .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
            .populate('references.author', 'firstName lastName role')
            .exec(function (err, answers) {
                if (err) { return res.send({reason: err}); }

                answers.forEach(function(answer) {
                    filterAnswerScoreHistory(answer);
                });

                res.send(answers);
            });
    } else {
        res.sendStatus(404);
        return res.end();
    }
};

exports.getAnswersPortion = function(req, res, next) {
    var limit = Number(req.params.limit),
        query = req.params.country ? {answer_ID: {$regex: new RegExp('^' + req.params.country + '.*')}} : {};

    if(req.deletedAssessments !== undefined) {
        query.assessment_ID = {$nin: req.deletedAssessments};
    }

    var getIso2Code = function(iso3Code, countries) {
        var iso2Code = iso3Code;

        countries.forEach(function(country) {
            if(iso3Code === country.country_ID) {
                iso2Code = country.iso2;
            }
        });

        return iso2Code;
    };

    Country.find().exec(function (err, countries) {
        if (err) {
            return res.send({reason: err.toString()});
        }

        Answer.find(query)
            .lean()
            .populate('question_ID', 'question_label question_label question_text dejure question_criteria component_text precept')
            .sort({answer_ID: 'asc'})
            .skip(Number(req.params.skip) * limit)
            .limit(limit)
            .exec(function(err, answers) {
                if(err) {
                    res.send({reason: err.toString()});
                } else {
                    req.answers = answers;

                    answers.forEach(function(answer) {
                        var idComponents = answer.answer_ID.split('-');
                        idComponents[0] = getIso2Code(idComponents[0], countries);
                        answer.iso2_code = idComponents.join('-');
                        filterAnswerScoreHistory(answer, true);
                    });

                    next();
                }
            });
    });
};

exports.getExportedAnswersData = function(req, res) {
    var
        scoreFieldIndex, SCORE_FIELDS = ['researcher', 'reviewer'],
        getListFieldPrefix = function(field) {
            return field.substr(0, field.length - 1);
        },
        getScoreFieldPrefix = function(scoreType) {
            return scoreType + '_score';
        },
        copyScore = function(outputAnswer, inputAnswer, scoreType) {
            var field = getScoreFieldPrefix(scoreType);
            outputAnswer[field + '_letter'] = inputAnswer[field] ? inputAnswer[field].letter : '';
        },
        copyScoreWithJustification = function(outputAnswer, inputAnswer, scoreType) {
            outputAnswer[getScoreFieldPrefix(scoreType) + '_justification'] =
                striptags(inputAnswer[scoreType + '_justification']);
            copyScore(outputAnswer, inputAnswer, scoreType);
        },
        copyListValues = function(outputAnswer, inputAnswer, field, valuesNumber) {
            for(var index = 0; index < valuesNumber; index++) {
                var data = inputAnswer[field][index];

                if(data) {
                    outputAnswer[getListFieldPrefix(field) + (index + 1)] = striptags(data.content);
                }
            }
        },
        getListFields = function(fieldName, fieldsNumberNumber) {
            var fields = [];

            for(var index = 0; index < fieldsNumberNumber; index++) {
                fields.push(getListFieldPrefix(fieldName) + (index + 1));
            }

            return fields;
        },
        getSectorName = function(version, lowerCase) {
            var result = '';

            if(version === 'MI') {
                result = 'Mining';
            } else if(['HY', 'OI'].indexOf(version) > -1) {
                result = 'Oil and Gas';
            }

            return lowerCase ? result.toLowerCase() : result;
        };

    var answers = [], listLength = {comments: 0, flags: 0},
        getFieldCounter = function(answerData) {
            return function(field) {
                if(answerData[field].length > listLength[field]) {
                    listLength[field] = answerData[field].length;
                }
            };
        };

    Country.find().exec(function(err, countries) {
        if(err) {
            return res.send({reason: err});
        }

        var
            getCountryData = function(iso3) {
                var countryData = {};

                countries.forEach(function(country) {
                    if(country.country_ID === iso3) {
                        countryData = country;
                    }
                });

                return countryData;
            },
            getCountryFullName = function(answerId) {
                var answerIdParts = answerId.split('-');
                var countryData = getCountryData(answerIdParts[0]);
                var countryName = countryData.country;

                if(countryData.includeSectorName) {
                    countryName += ' (' + getSectorName(answerIdParts[2], true) + ')';
                }

                return countryName;
            };

        req.answers.forEach(function(answerData) {
            Object.keys(listLength).forEach(getFieldCounter(answerData));
        });

        req.answers.forEach(function(answerData) {
            var answer = {
                country_code: answerData.answer_ID.split('-')[0],
                country_name: getCountryFullName(answerData.answer_ID),
                question_text: answerData.question_ID.question_text,
                version: getSectorName(answerData.answer_ID.split('-')[2], false)
            };

            ['answer_ID', 'question_order', 'status'].forEach(function(field) {
                answer[field] = answerData[field];
            });

            for(scoreFieldIndex = 0; scoreFieldIndex < SCORE_FIELDS.length; scoreFieldIndex++) {
                copyScoreWithJustification(answer, answerData, SCORE_FIELDS[scoreFieldIndex]);
            }

            copyScoreWithJustification(answer, answerData, 'final');

            Object.keys(listLength).forEach(function(field) {
                copyListValues(answer, answerData, field, listLength[field]);
            });

            Object.keys(answer).forEach(function(field) {
                if((answer[field] === undefined) || (answer[field] === null)) {
                    answer[field] = '';
                }
            });

            answers.push(answer);
        });

        var exportedFields = [
            'answer_ID',
            'country_code',
            'country_name',
            'version',
            'question_order',
            'question_text',
            'status',
            'researcher_score_justification',
            'researcher_score_letter',
            'reviewer_score_justification',
            'reviewer_score_letter',
            'final_score_justification',
            'final_score_letter'
        ];

        Object.keys(listLength).forEach(function(field) {
            exportedFields = exportedFields.concat(getListFields(field, listLength[field]));
        });

        res.send({data: answers, country: req.params.country, header: exportedFields});
    });
};

exports.getAnswersByID = function (req, res) {
    Answer.findOne({answer_ID: req.params.answer_ID})
        .populate('question_ID')
        .populate('external_answer.author', 'firstName lastName role external_type')
        .populate('comments.author', 'firstName lastName role')
        .populate('flags.author', 'firstName lastName role')
        .populate('flags.addressed_to', 'firstName lastName role')
        .populate('references.document_ID', 'title s3_url type year source authors')
        .populate('references.interviewee_ID', 'firstName lastName role')
        .populate('references.author', 'firstName lastName role')
        .exec(function (err, answer) {
            var respondError = function(error) {
                console.error('The answer ' + req.params.answer_ID + ' is not found');
                res.status(400);
                return res.send({reason: error.toString()});
            };

            if(err) {
                return respondError(err);
            }

            if(!answer) {
                return respondError(new Error('No answers found'));
            }

            filterAnswerScoreHistory(answer);
            res.send(answer);
        });
};

exports.createAnswers = function (req, res) {
    var new_answers, i;
    new_answers = req.body;

    function createNewAnswer(new_answer) {
        Answer.create(new_answer, function (err) {
            if (err) {
                if (err.toString().indexOf('E11000') > -1) {
                    err = new Error('Duplicate Assessment');
                }
                res.status(400);
                return res.send({reason: err.toString()});
            }
        });
    }

    for (i = new_answers.length - 1; i >= 0; i -= 1) {
        createNewAnswer(new_answers[i]);
    }
    res.send();
};

exports.updateAnswer = function (req, res, next) {
    var updateData = req.body,
        timestamp = new Date().toISOString();

    if (!req.user._id) {
        req.status = 404;
        next();
    } else {
        Answer.findOne({answer_ID: updateData.answer_ID}, function (err, answer) {
            var setFields = function(src, dst, fields) {
                fields.forEach(function(field) {
                    src[field] = dst[field];
                });
            };

            setFields(answer, updateData, [
                'comments',
                'external_answer',
                'flags',
                'guidance_dialog',
                'modified',
                'references',
                'researcher_resolve_flag_required',
                'status'
            ]);

            answer.last_modified = {modified_by: req.user._id, modified_date: timestamp};
            var scoreModified = false;

            ['researcher', 'reviewer'].forEach(function(userType) {
                if (updateData.hasOwnProperty(userType + '_score')) {
                    scoreModified = true;
                    setFields(answer, updateData, [userType + '_score']);

                    answer[userType + '_score_history'].push({
                        date: timestamp,
                        order: answer[userType + '_score_history'].length + 1,
                        score: answer[userType + '_score'],
                        justification: answer[userType + '_justification']
                    });
                }

                setFields(answer, updateData, [userType + '_justification']);
            });

            if (updateData.hasOwnProperty('final_score')) {
                scoreModified = true;
                setFields(answer, updateData, ['final_score', 'final_justification']);
                answer.final_role = updateData.final_role;
            }

            if(scoreModified) {
                req.last_modified = {user: req.user._id, date: timestamp};
                req.assessment_ID = answer.assessment_ID;
            }

            answer.save(function (err) {
                if (err !== null) {
                    req.error = err;
                }

                next();
            });
        });
    }
};
<commit_msg>hide personal consultant data in the public API<commit_after>'use strict';

var striptags = require('striptags');

var Answer      = require('mongoose').model('Answer'),
    Country     = require('mongoose').model('Country'),
    Question    = require('mongoose').model('Question'),
    Assessment  = require('mongoose').model('Assessment');

var filterAnswerScoreHistory = function(answer, skipJustificationComparison) {
    ['researcher', 'reviewer'].forEach(function(role) {
        var field = role + '_score_history';
        answer['raw_' + field] = answer[field].slice();
        answer[field] = getFilteredScoreHistory(answer[field], skipJustificationComparison);
    });
};

var getFilteredScoreHistory = function(rawHistory, skipJustificationComparison) {
    if(rawHistory.length <= 1) {
        return rawHistory;
    }

    var getScoreValue = function(score) {
        return (score === undefined) || (score === null) ? score : score.value;
    };

    var filteredHistory = [rawHistory[0]];

    for(var hisoryIndex = 1; hisoryIndex < rawHistory.length; hisoryIndex++) {
        var prevHistoryRecord = rawHistory[hisoryIndex - 1];
        var historyRecord = rawHistory[hisoryIndex];

        if((getScoreValue(historyRecord.score) !== getScoreValue(prevHistoryRecord.score)) ||
            ((historyRecord.justification !== prevHistoryRecord.justification) && !skipJustificationComparison)) {
            filteredHistory.push(historyRecord);
        }
    }

    return filteredHistory;
};

exports.getAnswers = function (req, res, next) {
    if (req.user.hasRole('supervisor')) {
        Answer.find(req.query)
            .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
            .populate('references.author', 'firstName lastName role')
            .exec(function (err, answers) {
                if (err) { return next(err); }
                if (!answers) { return next(new Error('No answers found')); }

                answers.forEach(function(answer) {
                    filterAnswerScoreHistory(answer);
                });

                res.send(answers);
            });
    } else {
        var criteria = {};
        criteria[req.user.role + '_ID'] = req.user._id;

        Assessment.find(criteria, {assessment_ID: 1}, function (err, assessments) {
            var assessments_ids = assessments.map(function (doc) { return doc.assessment_ID; });

            if (err) { return next(err); }
            if (!assessments) { return next(new Error('No assessments assigned to user')); }

            if (assessments_ids.indexOf(req.query.assessment_ID) > -1) {
                Answer.find(req.query)
                    .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
                    .exec(function (err, answers) {
                        if (err) { return next(err); }
                        if (!answers) { return next(new Error('No answers found')); }
                        res.send(answers);
                    });
            } else {
                res.sendStatus(404);
                return res.end();
            }
        });
    }
};

exports.listPublicData = function(req, res) {
    if (req.params.assessment_ID !== undefined) {
        Answer.find({assessment_ID: req.params.assessment_ID})
            .populate('question_ID', 'question_label question_text dejure question_criteria question_order component_text precept')
            .exec(function (err, answers) {
                if (err) { return res.send({reason: err}); }

                answers.forEach(function(answer) {
                    filterAnswerScoreHistory(answer);
                });

                res.send(answers);
            });
    } else {
        res.sendStatus(404);
        return res.end();
    }
};

exports.getAnswersPortion = function(req, res, next) {
    var limit = Number(req.params.limit),
        query = req.params.country ? {answer_ID: {$regex: new RegExp('^' + req.params.country + '.*')}} : {};

    if(req.deletedAssessments !== undefined) {
        query.assessment_ID = {$nin: req.deletedAssessments};
    }

    var getIso2Code = function(iso3Code, countries) {
        var iso2Code = iso3Code;

        countries.forEach(function(country) {
            if(iso3Code === country.country_ID) {
                iso2Code = country.iso2;
            }
        });

        return iso2Code;
    };

    Country.find().exec(function (err, countries) {
        if (err) {
            return res.send({reason: err.toString()});
        }

        Answer.find(query)
            .lean()
            .populate('question_ID', 'question_label question_label question_text dejure question_criteria component_text precept')
            .sort({answer_ID: 'asc'})
            .skip(Number(req.params.skip) * limit)
            .limit(limit)
            .exec(function(err, answers) {
                if(err) {
                    res.send({reason: err.toString()});
                } else {
                    req.answers = answers;

                    answers.forEach(function(answer) {
                        var idComponents = answer.answer_ID.split('-');
                        idComponents[0] = getIso2Code(idComponents[0], countries);
                        answer.iso2_code = idComponents.join('-');
                        filterAnswerScoreHistory(answer, true);
                    });

                    next();
                }
            });
    });
};

exports.getExportedAnswersData = function(req, res) {
    var
        scoreFieldIndex, SCORE_FIELDS = ['researcher', 'reviewer'],
        getListFieldPrefix = function(field) {
            return field.substr(0, field.length - 1);
        },
        getScoreFieldPrefix = function(scoreType) {
            return scoreType + '_score';
        },
        copyScore = function(outputAnswer, inputAnswer, scoreType) {
            var field = getScoreFieldPrefix(scoreType);
            outputAnswer[field + '_letter'] = inputAnswer[field] ? inputAnswer[field].letter : '';
        },
        copyScoreWithJustification = function(outputAnswer, inputAnswer, scoreType) {
            outputAnswer[getScoreFieldPrefix(scoreType) + '_justification'] =
                striptags(inputAnswer[scoreType + '_justification']);
            copyScore(outputAnswer, inputAnswer, scoreType);
        },
        copyListValues = function(outputAnswer, inputAnswer, field, valuesNumber) {
            for(var index = 0; index < valuesNumber; index++) {
                var data = inputAnswer[field][index];

                if(data) {
                    outputAnswer[getListFieldPrefix(field) + (index + 1)] = striptags(data.content);
                }
            }
        },
        getListFields = function(fieldName, fieldsNumberNumber) {
            var fields = [];

            for(var index = 0; index < fieldsNumberNumber; index++) {
                fields.push(getListFieldPrefix(fieldName) + (index + 1));
            }

            return fields;
        },
        getSectorName = function(version, lowerCase) {
            var result = '';

            if(version === 'MI') {
                result = 'Mining';
            } else if(['HY', 'OI'].indexOf(version) > -1) {
                result = 'Oil and Gas';
            }

            return lowerCase ? result.toLowerCase() : result;
        };

    var answers = [], listLength = {comments: 0, flags: 0},
        getFieldCounter = function(answerData) {
            return function(field) {
                if(answerData[field].length > listLength[field]) {
                    listLength[field] = answerData[field].length;
                }
            };
        };

    Country.find().exec(function(err, countries) {
        if(err) {
            return res.send({reason: err});
        }

        var
            getCountryData = function(iso3) {
                var countryData = {};

                countries.forEach(function(country) {
                    if(country.country_ID === iso3) {
                        countryData = country;
                    }
                });

                return countryData;
            },
            getCountryFullName = function(answerId) {
                var answerIdParts = answerId.split('-');
                var countryData = getCountryData(answerIdParts[0]);
                var countryName = countryData.country;

                if(countryData.includeSectorName) {
                    countryName += ' (' + getSectorName(answerIdParts[2], true) + ')';
                }

                return countryName;
            };

        req.answers.forEach(function(answerData) {
            Object.keys(listLength).forEach(getFieldCounter(answerData));
        });

        req.answers.forEach(function(answerData) {
            var answer = {
                country_code: answerData.answer_ID.split('-')[0],
                country_name: getCountryFullName(answerData.answer_ID),
                question_text: answerData.question_ID.question_text,
                version: getSectorName(answerData.answer_ID.split('-')[2], false)
            };

            ['answer_ID', 'question_order', 'status'].forEach(function(field) {
                answer[field] = answerData[field];
            });

            for(scoreFieldIndex = 0; scoreFieldIndex < SCORE_FIELDS.length; scoreFieldIndex++) {
                copyScoreWithJustification(answer, answerData, SCORE_FIELDS[scoreFieldIndex]);
            }

            copyScoreWithJustification(answer, answerData, 'final');

            Object.keys(listLength).forEach(function(field) {
                copyListValues(answer, answerData, field, listLength[field]);
            });

            Object.keys(answer).forEach(function(field) {
                if((answer[field] === undefined) || (answer[field] === null)) {
                    answer[field] = '';
                }
            });

            answers.push(answer);
        });

        var exportedFields = [
            'answer_ID',
            'country_code',
            'country_name',
            'version',
            'question_order',
            'question_text',
            'status',
            'researcher_score_justification',
            'researcher_score_letter',
            'reviewer_score_justification',
            'reviewer_score_letter',
            'final_score_justification',
            'final_score_letter'
        ];

        Object.keys(listLength).forEach(function(field) {
            exportedFields = exportedFields.concat(getListFields(field, listLength[field]));
        });

        res.send({data: answers, country: req.params.country, header: exportedFields});
    });
};

exports.getAnswersByID = function (req, res) {
    Answer.findOne({answer_ID: req.params.answer_ID})
        .populate('question_ID')
        .populate('external_answer.author', 'firstName lastName role external_type')
        .populate('comments.author', 'firstName lastName role')
        .populate('flags.author', 'firstName lastName role')
        .populate('flags.addressed_to', 'firstName lastName role')
        .populate('references.document_ID', 'title s3_url type year source authors')
        .populate('references.interviewee_ID', 'firstName lastName role')
        .populate('references.author', 'firstName lastName role')
        .exec(function (err, answer) {
            var respondError = function(error) {
                console.error('The answer ' + req.params.answer_ID + ' is not found');
                res.status(400);
                return res.send({reason: error.toString()});
            };

            if(err) {
                return respondError(err);
            }

            if(!answer) {
                return respondError(new Error('No answers found'));
            }

            filterAnswerScoreHistory(answer);
            res.send(answer);
        });
};

exports.createAnswers = function (req, res) {
    var new_answers, i;
    new_answers = req.body;

    function createNewAnswer(new_answer) {
        Answer.create(new_answer, function (err) {
            if (err) {
                if (err.toString().indexOf('E11000') > -1) {
                    err = new Error('Duplicate Assessment');
                }
                res.status(400);
                return res.send({reason: err.toString()});
            }
        });
    }

    for (i = new_answers.length - 1; i >= 0; i -= 1) {
        createNewAnswer(new_answers[i]);
    }
    res.send();
};

exports.updateAnswer = function (req, res, next) {
    var updateData = req.body,
        timestamp = new Date().toISOString();

    if (!req.user._id) {
        req.status = 404;
        next();
    } else {
        Answer.findOne({answer_ID: updateData.answer_ID}, function (err, answer) {
            var setFields = function(src, dst, fields) {
                fields.forEach(function(field) {
                    src[field] = dst[field];
                });
            };

            setFields(answer, updateData, [
                'comments',
                'external_answer',
                'flags',
                'guidance_dialog',
                'modified',
                'references',
                'researcher_resolve_flag_required',
                'status'
            ]);

            answer.last_modified = {modified_by: req.user._id, modified_date: timestamp};
            var scoreModified = false;

            ['researcher', 'reviewer'].forEach(function(userType) {
                if (updateData.hasOwnProperty(userType + '_score')) {
                    scoreModified = true;
                    setFields(answer, updateData, [userType + '_score']);

                    answer[userType + '_score_history'].push({
                        date: timestamp,
                        order: answer[userType + '_score_history'].length + 1,
                        score: answer[userType + '_score'],
                        justification: answer[userType + '_justification']
                    });
                }

                setFields(answer, updateData, [userType + '_justification']);
            });

            if (updateData.hasOwnProperty('final_score')) {
                scoreModified = true;
                setFields(answer, updateData, ['final_score', 'final_justification']);
                answer.final_role = updateData.final_role;
            }

            if(scoreModified) {
                req.last_modified = {user: req.user._id, date: timestamp};
                req.assessment_ID = answer.assessment_ID;
            }

            answer.save(function (err) {
                if (err !== null) {
                    req.error = err;
                }

                next();
            });
        });
    }
};
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var elementExplorerClient = require('./elementExplorerClient');
var cliHelper = require('./cliHelper');

var startExpress = function() {
  var app = express();
  app.use(bodyParser.json());

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    console.log('Got', query);
    res.send('Hello World!');
  });

  function handlePopupRequest(input, res) {
    console.log('Popup input [%s]', input);

    elementExplorerClient.runCommand(input).then(function(response) {
      var results = {};
      results[input] = response;

      res.send(JSON.stringify({
        results: results
      }));
    });
  }

  var server = app.listen(13000, function() {
    console.log('Elementor is listening on http://localhost:%s',
        server.address().port);
  });
};

var startProtractor = function() {
  return cliHelper.startProtractor();
};

var startServer = function() {
  startProtractor().then(function() {
    console.log('Done starting protractor');
    startExpress();
  });
};

module.exports = {
  start: startServer
};
<commit_msg>Implement by > count()<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var elementExplorerClient = require('./elementExplorerClient');
var cliHelper = require('./cliHelper');

var startExpress = function() {
  var app = express();
  app.use(bodyParser.json());

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    console.log('Got', query);
    res.send('Hello World!');
  });

  function handlePopupRequest(input, res) {
    // If the popup input starts with 'by' then execute a count expression.
    if (/^by/.test(input)) {
      input = 'element.all(' + input + ').count()';
    }

    console.log('Popup input [%s]', input);

    elementExplorerClient.runCommand(input).then(function(response) {
      var results = {};
      results[input] = response;

      res.send(JSON.stringify({
        results: results
      }));
    });
  }

  var server = app.listen(13000, function() {
    console.log('Elementor is listening on http://localhost:%s',
        server.address().port);
  });
};

var startProtractor = function() {
  return cliHelper.startProtractor();
};

var startServer = function() {
  startProtractor().then(function() {
    console.log('Done starting protractor');
    startExpress();
  });
};

module.exports = {
  start: startServer
};
<|endoftext|>


<commit_before>function deleteRow(row){
  window.alert(row)
  var tbl = document.getElementById('flowspace')
      tbl.deleteRow(row)
}

function deleteColumn(cell){
  window.alert(cell)
   var tbl = document.getElementById('flowspace')
   for (i = 0; i < tbl.rows.length; i++) {
       tbl.rows[i].deleteCell(cell)
   }
}

function clearText() {
  window.alert("corner")
}
function createCell(cell) {

    var content = document.createElement('DIV');

    var string = "

x	";
    string += "x
";
    string += "
<textarea></textarea>	";
    string += "x

";
    content.innerHTML = string;
    cell.appendChild(content);

}

function newSpeech() {
  var tbl = document.getElementById('flowspace'), // table reference
        i;
    // open loop for each row and append cell
    for (i = 0; i < tbl.rows.length; i++) {
        createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length));
    }

}

function newContention() {
  var tbl = document.getElementById('flowspace'), // table reference
      row = tbl.insertRow(tbl.rows.length),      // append table row
      i;
  // insert table cells to the new row
  for (i = 0; i < tbl.rows[0].cells.length; i++) {
      createCell(row.insertCell(i));
  }

}
<commit_msg>flowing works!<commit_after>function deleteRow(row){
  var tbl = document.getElementById('flowspace')
  if (tbl.rows.length > 1) {
      tbl.deleteRow(row)
    }
}

function deleteColumn(cell){
   var tbl = document.getElementById('flowspace')
   if (tbl.rows[0].cells.length > 1){
     for (i = 0; i < tbl.rows.length; i++) {
         tbl.rows[i].deleteCell(cell)
     }
 }

}

function clearText() {
  window.alert("corner")
}
function createCell(cell) {

    var content = document.createElement('DIV');

    var string = "

x	";
    string += "x
";
    string += "
<textarea></textarea>	";
    string += "x

";
    content.innerHTML = string;
    cell.appendChild(content);

}

function newSpeech() {
  var tbl = document.getElementById('flowspace'), // table reference
        i;
    // open loop for each row and append cell
    for (i = 0; i < tbl.rows.length; i++) {
        createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length));
    }

}

function newContention() {
  var tbl = document.getElementById('flowspace'), // table reference
      row = tbl.insertRow(tbl.rows.length),      // append table row
      i;
  // insert table cells to the new row
  for (i = 0; i < tbl.rows[0].cells.length; i++) {
      createCell(row.insertCell(i));
  }

}
<|endoftext|>


<commit_before>// Groups are groups, organisations, institutions, virtual or real instituts, departments or bodys...

testgroups = [{
	'name':        	    'Dynamo',
	'short':            'Dyn',
	'claim':            'Jugendkulturhaus',
	'description':      'Städtisches Jugendkulturhaus, Wasserwekstrasse 21',
},{
	'name':        	    'denk:mal Autonome Schule Bern',
	'short':            'Denki',
	'claim':            '',
	'description':      'Denk:mal Bern, Lorraine
 denk-mal.info',
	'members':          ['sb','Linda']

},{
	'name':             'CornerCollege',
	'short':            'CC',
	'claim':            '',
	'description':      'Das Corner College ist ein offener Raum für unregelmässig stattfindende, quasi-akademische Aktivitäten wie Workshops, Vorträge, Lesungen, Filmvorführungen und kulinarische Versuche.',
	'members':          ['Stefan','Roger']
},{
	'name':             'Dock18',
	'short':            'Dock',
	'claim':            'Raum für Medienkulturen der Welt',
	'description':      'Das Dock18 ist abwechselnd und von Zeit zu Zeit simultan unabhängiger Kunstraum, TV Studio, Medienlabor, Meeting Point, Bar, Club, Tanzboden und interaktiver Nährboden für verschiedene Medienkulturen der Welt.',
},{
	'name':        	    'Autonome Schule Zürich, Bildung für Alle',
	'short':            'ASZ',
	'claim':            'Bildung für alle',
	'description':      'Die Autonome Schule Zürich ist ein selbstverwaltetes Bildungsprojekt in Zürich. Es werden zahlreiche Kurse kostenlos angeboten, wobei stets die Möglichkeit besteht sich an Kursen bzw. am Schulprojekt zu beteiligen. Essentiell sind dabei die Deutschkurse, welche besonders für MigrantInnen und Sans-Papiers einen hürdenfreien und emanzipatorischen Zugang zur Sprache ermöglichen.',
	'members':          ['greg']
},{
	'name':        	    'Schweizerische Gesellschaft für Mechatronische Kunst',
	'short':            'SGMK',
	'claim':            '',
	'description':      'Die SGMK fördert das Schaffen im Bereich der Elektrotechnik, Mechanik und Informatik, sowie artverwandter Gebiete. Dieses wird als künstlerischer Ausdruck des menschlichen Geistes, der nicht primär durch seine Zweckmässigkeit, sondern der Gesamtheit des Besonderen geprägt ist verstanden. Dabei stehen Arbeit und Forschung, Veranstaltung und Weiterbildung, Austausch und Vernetzung sowie Hebung und Wahrung der Qualität in der Mechatronischen Kunst im Zentrum.',
	'members':          ['greg','ABCD'],
},{
	'name':        	    'Chaos Computer Club Zürich',
	'short':            'CCC-ZH',
	'claim':            '',
	'description':      'Der Chaos Computer Club Zürich (CCCZH) ist ein Verein, bei dem der Spass am Gerät grossgeschrieben wird, ohne aber den gesellschaftlichen Blick zu verlieren.
 Es geht uns darum Intransparenz und limitierende Faktoren von Computergeräten aufzuheben; auch möchten wir die Kontrolle über diese Geräte haben, weil sie in einer computerisierten Gesellschaft Fehlentwicklungen hervorrufen mögen und weil wir selbst bestimmen möchten, welche unserer Daten verfügbar sind und auch auf welche wir frei zugreifen möchten.
Wir arbeiten technisch und politisch, um unsere Forderungen durchzusetzen.

Hacker, Technikbegeisterte, Menschen mit gesellschaftlichem Blick - alle heissen wir willkommen. Wir verstehen uns nicht als eine elitäre Gruppierung und arbeiten deshalb offen mit allen Interessierten zusammmen.
',
},{
	'name':        	    'MAXIM Theater',
	'short':            'Maxim',
	'claim':            '',
	'description':      'Das MAXIM Theater im Langstrassenquartier in Zürich ist das interkulturell engagierte Theater der Stadt.
 Im MAXIM Theater spielen Laien und ausgebildete KünstlerInnen aus allen Teilen der Welt. In einem gemeinsamen künstlerischen Prozess geben sie den unterschiedlichsten Erfahrungen von MigrantInnen eine Stimme.',
},{
	'name':        	    'Nachhaltigkeitswoche',
	'short':            'NHW',
	'claim':            '',
	'description':      'Über 60 Studierende von fünf Zürcher Hochschulen stecken ehrenamtlich ihr Herzblut in die Organisation dieses Grossprojekts. Wir sind stolz einen Beitrag zu einer zukunftsfähigen Gesellschaft zu leisten.',
	'members':          ['Vera','Nicolle']

},{
	'name':        	    'Do It Yourself Züri',
	'short':            'DIY-ZH',
	'claim':            '',
	'description':      'We facilitate Do-It-Yourself-initiatives in the area of Zurich',
	'members':          ['Melinda']
},{
	'name':        	    'Wohlfühlgruppe-ZH',
	'short':            'WFG-ZH',
	'claim':            'Alles was gut tut.',
	'description':      'Wir unterstützen Initiativen von einzelpersonen zur Verbesserung des geistigen und körperlichen Wohlergehens.',
	'members':          ['Regula', 'Tiffany', 'Vlada']
},{
	'name':        	    'Geographisch-Ethnographische Gesellschaft Zürich',
	'short':            'GeoUZH',
	'claim':            '',
	'description':      '
Anliegen und Zielsetzungen:

 Förderung von geographischem und ethnographischem Wissen
 Erhaltung der Umwelt und der Qualität unserer Lebensräume Nachhaltige Nutzung unserer Ressourcen
 Verständnis für fremde Kulturen und globale Zusammenhänge

 Die Geographisch-Ethnographische Gesellschaft Zürich (GEGZ) kann auf eine rund hundertjährige Geschichte zurückblicken. Sie entstand 1899 durch den Zusammenschluss der Ethnographischen Gesellschaft (gegründet 1888) und der Geographischen Gesellschaft (gegründet 1897). Durch die Förderung der Völkerkundlichen Sammlung (die später an die Universität übergeben wurde und im heutigen Völkerkundemuseum weiterlebt), die Organisation von vielbeachteten Vorträgen, die Publikation von Aufsätzen und die Durchführung von Exkursionen hat sie sich einen Namen gemacht, der weit über Zürich hinaus reicht.

 Die GEGZ setzt sich für die Förderung und Verbreitung von geographischem und ethnographischem Wissen ein. Die Geographie beschäftigt sich heute mit verschiedenen gesellschaftlich relevanten Themen, wie Umweltschutz, nachhaltiger Umgang mit natürlichen und gesellschaftlichen Ressourcen, Klimawandel, Raumplanung, Probleme der Entwicklungsländer bis zu Aspekten der Globalisierung von Wirtschaft und Kultur. Geographisches Wissen und darauf aufbauendes Handeln ist für die Lösung globaler Herausforderungen und somit für die Zukunft unserer Gesellschaft von wachsender Bedeutung.

Die GEGZ sieht sich als Bindeglied zwischen Hochschule und Öffentlichkeit. Ihr Hauptanliegen ist es, durch Fachvorträge und Exkursionen wissenschaftliche Forschungsergebnisse in verständlicher Form an einen breiten Personenkreis weiterzugeben. Eine weitere Aufgabe ist die Förderung der geographischen und ethnographischen Wissenschaften an unseren Hochschulen.

Die Gesellschaft zählt zur Zeit über 450 Einzel- und Kollektivmitglieder. Ein grosser Teil der Mitglieder sind Geographen und Geographinnen, viele Mitglieder sind im Lehramt aller Stufen tätig, andere arbeiten in der öffentlichen Verwaltung, der Privatwirtschaft oder studieren.

Die GEGZ ist Mitherausgeberin der Geographica Helvetica (GH). Diese schweizerische Fachzeitschrift für Geographie bietet den Lesern und Leserinnen einen fundierten Einblick in das breite Spektrum der geographischen Forschung. Diese Zeitschrift, die vierteljährlich erscheint, erhalten unsere Mitglieder kostenlos.

Das Vortragsprogramm, das jeweils auf einen thematischen Schwerpunkt gerichtet ist, beginnt jeweils im Oktober und schliesst mit einem Referat anlässlich der Hauptversammlung im Februar. Die Vorträge finden jeweils am Mittwochabend um 18.15 Uhr im Hauptgebäude der ETH statt. Zusätzlich werden die Mitglieder der GEGZ zum «Zürcher Geographischen Kolloquium», einer wissenschaftlichen Vortragsserie der Geographischen Institute der Universität und der ETH Zürich, eingeladen.

 Die Gesellschaft organisiert für ihre Mitglieder Führungen und Besichtigungen sowie – vorwiegend im Sommerhalbjahr – ein- und mehrtägige Exkursionen im In- und Ausland.
',
	'members':          ['Norman Backhaus']
},{
	'name':        	    'Off-Spaces Schweiz',
	'short':            'OFFs',
	'claim':            '',
	'description':      'Zusammenschluss von LesComplices, CornerCollege, etc.',
	'members':          ['Simona', 'Marlene']
},{
	'name':        	    'CSA - regionale Vertragslandwirtschaft',
	'short':            'CSA',
	'claim':            'think global act local',
	'description':      'test test',
	'members':          ['greg']
},{
	'name':        	    'Outdoor/Survival Group',
	'short':            'Outdoor',
	'claim':            '',
	'description':      '',
	'members':          ['lu']
},{
	'name':        	    'Myzelia Openki',
	'short':            'Myzelia',
	'claim':            'selbstorganisation in der Bildung',
	'description':      '',
	'members':          ['sbalmer', 'Urban', 'lu40']
},{
	'name':        	    'Studiengang Kommunikationsguerilla',
	'short':            'SKG',
	'claim':            'nein, ja, nein, nein, ja.',
	'description':      'Das Ziel der KommunikationsGuerilla ist das Ziel. Die Kommunikationsguerilla ist das Mittel. Der Zweck ist die Befreiung. Das Mittel zur Befreiung ist der Mensch. Der Mensch, der in der fremdverschuldeten Unmündigkeit liegt.',
	'members':          ['1u']
},{
	'name':        	    '',
	'short':            '',
	'claim':            '',
	'description':      '',
	'members':          ['']
}]
<commit_msg>adds LDF as testgroup<commit_after>// Groups are groups, organisations, institutions, virtual or real instituts, departments or bodys...

testgroups = [{
	'name':        	    'Dynamo',
	'short':            'Dyn',
	'claim':            'Jugendkulturhaus',
	'description':      'Städtisches Jugendkulturhaus, Wasserwekstrasse 21',
},{
	'name':        	    'denk:mal Autonome Schule Bern',
	'short':            'Denki',
	'claim':            '',
	'description':      'Denk:mal Bern, Lorraine
 denk-mal.info',
	'members':          ['sb','Linda']

},{
	'name':             'CornerCollege',
	'short':            'CC',
	'claim':            '',
	'description':      'Das Corner College ist ein offener Raum für unregelmässig stattfindende, quasi-akademische Aktivitäten wie Workshops, Vorträge, Lesungen, Filmvorführungen und kulinarische Versuche.',
	'members':          ['Stefan','Roger']
},{
	'name':             'Dock18',
	'short':            'Dock',
	'claim':            'Raum für Medienkulturen der Welt',
	'description':      'Das Dock18 ist abwechselnd und von Zeit zu Zeit simultan unabhängiger Kunstraum, TV Studio, Medienlabor, Meeting Point, Bar, Club, Tanzboden und interaktiver Nährboden für verschiedene Medienkulturen der Welt.',
},{
	'name':        	    'Autonome Schule Zürich, Bildung für Alle',
	'short':            'ASZ',
	'claim':            'Bildung für alle',
	'description':      'Die Autonome Schule Zürich ist ein selbstverwaltetes Bildungsprojekt in Zürich. Es werden zahlreiche Kurse kostenlos angeboten, wobei stets die Möglichkeit besteht sich an Kursen bzw. am Schulprojekt zu beteiligen. Essentiell sind dabei die Deutschkurse, welche besonders für MigrantInnen und Sans-Papiers einen hürdenfreien und emanzipatorischen Zugang zur Sprache ermöglichen.',
	'members':          ['greg']
},{
	'name':        	    'Schweizerische Gesellschaft für Mechatronische Kunst',
	'short':            'SGMK',
	'claim':            '',
	'description':      'Die SGMK fördert das Schaffen im Bereich der Elektrotechnik, Mechanik und Informatik, sowie artverwandter Gebiete. Dieses wird als künstlerischer Ausdruck des menschlichen Geistes, der nicht primär durch seine Zweckmässigkeit, sondern der Gesamtheit des Besonderen geprägt ist verstanden. Dabei stehen Arbeit und Forschung, Veranstaltung und Weiterbildung, Austausch und Vernetzung sowie Hebung und Wahrung der Qualität in der Mechatronischen Kunst im Zentrum.',
	'members':          ['greg','ABCD'],
},{
	'name':        	    'Chaos Computer Club Zürich',
	'short':            'CCC-ZH',
	'claim':            '',
	'description':      'Der Chaos Computer Club Zürich (CCCZH) ist ein Verein, bei dem der Spass am Gerät grossgeschrieben wird, ohne aber den gesellschaftlichen Blick zu verlieren.
 Es geht uns darum Intransparenz und limitierende Faktoren von Computergeräten aufzuheben; auch möchten wir die Kontrolle über diese Geräte haben, weil sie in einer computerisierten Gesellschaft Fehlentwicklungen hervorrufen mögen und weil wir selbst bestimmen möchten, welche unserer Daten verfügbar sind und auch auf welche wir frei zugreifen möchten.
Wir arbeiten technisch und politisch, um unsere Forderungen durchzusetzen.

Hacker, Technikbegeisterte, Menschen mit gesellschaftlichem Blick - alle heissen wir willkommen. Wir verstehen uns nicht als eine elitäre Gruppierung und arbeiten deshalb offen mit allen Interessierten zusammmen.
',
},{
	'name':        	    'MAXIM Theater',
	'short':            'Maxim',
	'claim':            '',
	'description':      'Das MAXIM Theater im Langstrassenquartier in Zürich ist das interkulturell engagierte Theater der Stadt.
 Im MAXIM Theater spielen Laien und ausgebildete KünstlerInnen aus allen Teilen der Welt. In einem gemeinsamen künstlerischen Prozess geben sie den unterschiedlichsten Erfahrungen von MigrantInnen eine Stimme.',
},{
	'name':        	    'Nachhaltigkeitswoche',
	'short':            'NHW',
	'claim':            '',
	'description':      'Über 60 Studierende von fünf Zürcher Hochschulen stecken ehrenamtlich ihr Herzblut in die Organisation dieses Grossprojekts. Wir sind stolz einen Beitrag zu einer zukunftsfähigen Gesellschaft zu leisten.',
	'members':          ['Vera','Nicolle']

},{
	'name':        	    'Do It Yourself Züri',
	'short':            'DIY-ZH',
	'claim':            '',
	'description':      'We facilitate Do-It-Yourself-initiatives in the area of Zurich',
	'members':          ['Melinda']
},{
	'name':        	    'Wohlfühlgruppe-ZH',
	'short':            'WFG-ZH',
	'claim':            'Alles was gut tut.',
	'description':      'Wir unterstützen Initiativen von einzelpersonen zur Verbesserung des geistigen und körperlichen Wohlergehens.',
	'members':          ['Regula', 'Tiffany', 'Vlada']
},{
	'name':        	    'Geographisch-Ethnographische Gesellschaft Zürich',
	'short':            'GeoUZH',
	'claim':            '',
	'description':      '
Anliegen und Zielsetzungen:

 Förderung von geographischem und ethnographischem Wissen
 Erhaltung der Umwelt und der Qualität unserer Lebensräume Nachhaltige Nutzung unserer Ressourcen
 Verständnis für fremde Kulturen und globale Zusammenhänge

 Die Geographisch-Ethnographische Gesellschaft Zürich (GEGZ) kann auf eine rund hundertjährige Geschichte zurückblicken. Sie entstand 1899 durch den Zusammenschluss der Ethnographischen Gesellschaft (gegründet 1888) und der Geographischen Gesellschaft (gegründet 1897). Durch die Förderung der Völkerkundlichen Sammlung (die später an die Universität übergeben wurde und im heutigen Völkerkundemuseum weiterlebt), die Organisation von vielbeachteten Vorträgen, die Publikation von Aufsätzen und die Durchführung von Exkursionen hat sie sich einen Namen gemacht, der weit über Zürich hinaus reicht.

 Die GEGZ setzt sich für die Förderung und Verbreitung von geographischem und ethnographischem Wissen ein. Die Geographie beschäftigt sich heute mit verschiedenen gesellschaftlich relevanten Themen, wie Umweltschutz, nachhaltiger Umgang mit natürlichen und gesellschaftlichen Ressourcen, Klimawandel, Raumplanung, Probleme der Entwicklungsländer bis zu Aspekten der Globalisierung von Wirtschaft und Kultur. Geographisches Wissen und darauf aufbauendes Handeln ist für die Lösung globaler Herausforderungen und somit für die Zukunft unserer Gesellschaft von wachsender Bedeutung.

Die GEGZ sieht sich als Bindeglied zwischen Hochschule und Öffentlichkeit. Ihr Hauptanliegen ist es, durch Fachvorträge und Exkursionen wissenschaftliche Forschungsergebnisse in verständlicher Form an einen breiten Personenkreis weiterzugeben. Eine weitere Aufgabe ist die Förderung der geographischen und ethnographischen Wissenschaften an unseren Hochschulen.

Die Gesellschaft zählt zur Zeit über 450 Einzel- und Kollektivmitglieder. Ein grosser Teil der Mitglieder sind Geographen und Geographinnen, viele Mitglieder sind im Lehramt aller Stufen tätig, andere arbeiten in der öffentlichen Verwaltung, der Privatwirtschaft oder studieren.

Die GEGZ ist Mitherausgeberin der Geographica Helvetica (GH). Diese schweizerische Fachzeitschrift für Geographie bietet den Lesern und Leserinnen einen fundierten Einblick in das breite Spektrum der geographischen Forschung. Diese Zeitschrift, die vierteljährlich erscheint, erhalten unsere Mitglieder kostenlos.

Das Vortragsprogramm, das jeweils auf einen thematischen Schwerpunkt gerichtet ist, beginnt jeweils im Oktober und schliesst mit einem Referat anlässlich der Hauptversammlung im Februar. Die Vorträge finden jeweils am Mittwochabend um 18.15 Uhr im Hauptgebäude der ETH statt. Zusätzlich werden die Mitglieder der GEGZ zum «Zürcher Geographischen Kolloquium», einer wissenschaftlichen Vortragsserie der Geographischen Institute der Universität und der ETH Zürich, eingeladen.

 Die Gesellschaft organisiert für ihre Mitglieder Führungen und Besichtigungen sowie – vorwiegend im Sommerhalbjahr – ein- und mehrtägige Exkursionen im In- und Ausland.
',
	'members':          ['Norman Backhaus']
},{
	'name':        	    'Off-Spaces Schweiz',
	'short':            'OFFs',
	'claim':            '',
	'description':      'Zusammenschluss von LesComplices, CornerCollege, etc.',
	'members':          ['Simona', 'Marlene']
},{
	'name':        	    'CSA - regionale Vertragslandwirtschaft',
	'short':            'CSA',
	'claim':            'think global act local',
	'description':      'test test',
	'members':          ['greg']
},{
	'name':        	    'Outdoor/Survival Group',
	'short':            'Outdoor',
	'claim':            '',
	'description':      '',
	'members':          ['lu']
},{
	'name':        	    'Myzelia Openki',
	'short':            'Myzelia',
	'claim':            'selbstorganisation in der Bildung',
	'description':      '',
	'members':          ['sbalmer', 'Urban', 'lu40']
},{
	'name':        	    'Studiengang Kommunikationsguerilla',
	'short':            'SKG',
	'claim':            'nein, ja, nein, nein, ja.',
	'description':      'Das Ziel der KommunikationsGuerilla ist das Ziel. Die Kommunikationsguerilla ist das Mittel. Der Zweck ist die Befreiung. Das Mittel zur Befreiung ist der Mensch. Der Mensch, der in der fremdverschuldeten Unmündigkeit liegt.',
	'members':          ['1u']
},{
	'name':        	    'Lern Dich Frei',
	'short':            'LDF',
	'claim':            'In 365 Tagen zu einem nachhaltigeren Leben',
	'description':      '
Das Projekt “Lern Dich Frei!” ist als Initiative von Student/innen der Universität Zürich entstanden und bietet während gut eines Jahres Raum für ein breites Spektrum an Themen und öffentlichen Veranstaltungen rund um eine zukunftsfähige Welt.

Das Ziel des Projektes ist es, nicht nur Wissen zu vermitteln, sondern auch eine Plattform für Expert/innen zu bieten, Netzwerke zu bilden und anregende und umsetzbare Ideen für den Alltag zu liefern.

Während eines Jahreszyklus’ finden wöchentlich öffentliche Events zu unterschiedlichen Themen statt. Die Teilnahme ist in der Regel kostenlos. Die Agenda ist hier zu finden - nutze diese Gelegenheit und nimm an einer unserer Veranstaltungen teil!

Wichtig: es gibt noch viel Raum für weitere Events, und Deine Ideen sind äusserst willkommen. Mehr zu Möglichkeiten, dich einzubringen, erfährst du hier.
',
	'members':          ['greg']
},{
	'name':        	    '',
	'short':            '',
	'claim':            '',
	'description':      '',
	'members':          ['']
}]
<|endoftext|>


<commit_before>

var config = require('../app/config')
  , request = require('../app/request')
  , token = require('../app/token')
  , vault = require('../app/setup/vault')

var credentials = vault.keys[config.host.ix].latest
  , payload =
    { iss: config.host.setup
    , aud: config.host.ix
    , 'request.a2p3.org':
      { 'AS': config.host.as
      , 'RS': []

    }
  }

function jwsCreate  () {
  var jws = request.create( payload, credentials )
}

function jwsCreateParse () {
  var jws = request.create( payload, credentials )
  var output = request.parse( jws, function() { return credentials})
}

function jweCreate () {
  var jwe = token.create( payload, credentials )
}

function jweCreateParse () {
  var jwe = token.create( payload, credentials )
  var output = token.parse( jwe, function() { return credentials})
}

var timing = function (func) {
  var times = []
  for (var x=0; x<10; x++) {
    var start = new Date()
    for (var i=0; i<10000; i++) {
      func()
    }
    var stop = new Date()
    times.push(stop-start)
  }
  var avg = 0
  times.forEach( function(v) {avg += v})
  avg = avg/10
  console.log( func.name, times, avg)
}

console.log(config.alg.JWS)
timing( jwsCreate )
timing( jwsCreateParse )
timing( jweCreate )
timing( jweCreateParse )

config.alg.JWS = 'HS256'
config.alg.JWE = 'A128CBC+HS256'
vault = require('../app/setup/128vault')
credentials = vault.keys[config.host.ix].latest

console.log(config.alg.JWS)
timing( jwsCreate )
timing( jwsCreateParse )
timing( jweCreate )
timing( jweCreateParse )
<commit_msg>changed output to microseconds and using high res timer<commit_after>

var config = require('../app/config')
  , request = require('../app/request')
  , token = require('../app/token')
  , vault = require('../app/setup/vault')

var credentials = vault.keys[config.host.ix].latest
  , payload =
    { iss: config.host.setup
    , aud: config.host.ix
    , 'request.a2p3.org':
      { 'AS': config.host.as
      , 'RS': []

    }
  }

function jwsCreate  () {
  var jws = request.create( payload, credentials )
}

function jwsCreateParse () {
  var jws = request.create( payload, credentials )
  var output = request.parse( jws, function() { return credentials})
}

function jweCreate () {
  var jwe = token.create( payload, credentials )
}

function jweCreateParse () {
  var jwe = token.create( payload, credentials )
  var output = token.parse( jwe, function() { return credentials})
}

var timing = function (func) {
  var times = []
  for (var x=0; x<10; x++) {
    var start = process.hrtime()
    for (var i=0; i<1000; i++) {
      func()
    }
    times.push( Math.round( process.hrtime(start)[1]/1000000 ) )
  }
  var avg = 0
  times.forEach( function(v) {avg += v})
  avg = avg/10
  console.log( func.name, times, avg)
}

console.log(config.alg.JWS)
timing( jwsCreate )
timing( jwsCreateParse )
timing( jweCreate )
timing( jweCreateParse )

config.alg.JWS = 'HS256'
config.alg.JWE = 'A128CBC+HS256'
vault = require('../app/setup/128vault')
credentials = vault.keys[config.host.ix].latest

console.log(config.alg.JWS)
timing( jwsCreate )
timing( jwsCreateParse )
timing( jweCreate )
timing( jweCreateParse )
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var FluentInterface = require('./fluent');
var corsMiddleware = require('./cors');
var util = require('core-util-is');
var url = require('url');
var connectJson = require('connect-json');
var bodyParser = require('body-parser');
var Route = require('./route');

function createInvalidDataException(data) {
	return new Error('You have to provide a JSON object with the following structure: \n' + JSON.stringify({ request : { method : '[GET|PUT|POST|DELETE]', url : '(relative URL e.g. /hello)' }, response : { code : '(HTTP Response code e.g. 200/400/500)', body : '(a JSON object)' } }, null, 4) + ' but you provided: \n' + JSON.stringify(data, null, 4));
}

function determineDelay(delayInput) {
	var result = 0, range, upper, lower;
	if(util.isNumber(delayInput)) {
		result = delayInput;
	} else if(util.isString(delayInput)) {
		range = /([0-9]+)..([0-9]+)/.exec(delayInput);
		upper = +range[2];
		lower = +range[1];
		result = Math.floor( Math.random() * (upper - lower + 1) + lower );
	}

	return result;
}

function Interfake(o) {
	o = o || { debug: false };
	var app = express();
	var router = express.Router();
	var fluentInterface = new FluentInterface(this, o);
	var debug = require('./debug')('interfake-server', o.debug);
	var expectationsLookup = {};
	var server;

	o.path = url.resolve('/', o.path || '');

	debug('Root path is', o.path);

	app.use(o.path, router);
	app.use(connectJson());
	app.use(bodyParser());
	app.use(corsMiddleware);

	app.post('/_requests?', function(req, res){
		try {
			debug('Being hit with a _request request');
			createRoute(req.body);
			debug('Returning');
			res.send(201, { done : true });
		} catch (e) {
			debug('Error: ', e);
			res.send(400, e);
		}
	});

	app.all('/*', function(req, res) {
		debug(req.method, 'request to', req.url);
		var hashData = {
			method: req.method,
			url: req.path,
			query: req.query
		};
		var rootPathRegex;

		if (o.path.length > 1) {
			rootPathRegex = new RegExp('^' + o.path);
			if (!rootPathRegex.test(hashData.url)) {
				return res.send(404);
			}
			hashData.url = hashData.url.replace(rootPathRegex, '');
		}

		var incomingRoute = new Route({
			request: hashData
		}, o);

		var expectData = expectationsLookup[incomingRoute.simpleHash()];
		var expectedRoute;

		if (!expectData || (util.isArray(expectData.length) && expectData.length === 0)) {
			return res.send(404);
		}

		expectData = expectData.filter(function (route) {
			return route.compare(incomingRoute);
		});

		if (expectData.length > 0) {
			expectedRoute = expectData.pop();
		} else {
			return res.send(404);
		}

		var specifiedResponse = expectedRoute.response; // req.route.responseData;
		var afterSpecifiedResponse = expectedRoute.afterResponse; //req.route.afterResponseData;
		var responseDelay = determineDelay(specifiedResponse.delay);

		debug(req.method, 'request to', req.url, 'returning', specifiedResponse.code);
		debug(req.method, 'request to', req.url, 'will be delayed by', responseDelay, 'millis');
		debug('Expected route is', expectedRoute);

		var responseBody = specifiedResponse.body;

		res.setHeader('Content-Type', 'application/json');

		if (specifiedResponse.headers) {
			Object.keys(specifiedResponse.headers).forEach(function (k) {
				res.setHeader(k, specifiedResponse.headers[k]);
			});
		}

		if (req.query.callback) {
			debug('Request is asking for jsonp');
			if (typeof responseBody !== 'string') responseBody = JSON.stringify(responseBody);
			responseBody = req.query.callback.trim() + '(' + responseBody + ');';
		}

		setTimeout(function() {
			var modification;
			debug('Expected response is', specifiedResponse);

			res.send(specifiedResponse.code, responseBody);

			if (afterSpecifiedResponse && afterSpecifiedResponse.endpoints) {
				debug('Response sent, setting up', afterSpecifiedResponse.endpoints.length, 'endpoints');
				afterSpecifiedResponse.endpoints.forEach(function (route) {
					debug('Setting up route', route.hash());
					addRoute(route);
				});
			}

			if (afterSpecifiedResponse && afterSpecifiedResponse.modifications) {
				debug('Response sent, making', afterSpecifiedResponse.modifications.length, 'modifications');
				while (afterSpecifiedResponse.modifications.length > 0) {
					modification = afterSpecifiedResponse.modifications.pop();

					modification.route = this.routeMatching(modification.routeDescriptor);

					if (!modification.route) {
						throw new Error('No route matching', modification.routeDescriptor, 'was found');
					}

					if (modification.body) {
						debug('Modifying body');
						modification.route.mergeResponseBody(modification.body);
					}

					if (modification.code) {
						debug('Modifying code to', modification.code);
						modification.route.setStatusCode(modification.code);
					}

					if (modification.delay) {
						debug('Modifying delay to', modification.delay);
						modification.route.setResponseDelay(modification.delay);
					}

					if (modification.responseHeaders) {
						debug('Modifying response headers');
						modification.route.mergeResponseHeaders(modification.responseHeaders);
					}
				}
			}
		}.bind(this), responseDelay);
	}.bind(this));

	function addRoute(route) {
		if (expectationsLookup[route.simpleHash()]) {
			expectationsLookup[route.simpleHash()].push(route);
		} else {
			expectationsLookup[route.simpleHash()] = [ route ];
		}
	}

	function createRoute(data) {
		var newRoute;

		debug('Setting up new route');

		newRoute = new Route(data, o);

		addRoute(newRoute);

		debug('Setup complete');

		return newRoute;
	}

	this.createRoute = createRoute;

	this.get = fluentInterface.fluentCreate('get');
	this.post = fluentInterface.fluentCreate('post');
	this.put = fluentInterface.fluentCreate('put');
	this.delete = fluentInterface.fluentCreate('delete');

	this.serveStatic = function (path, directory) {
		path = path || '/_static';
		app.use(path, express.static(directory));
	};

	this.routeMatching = function (requestDescriptor) {
		var incomingRoute = new Route({
			request: requestDescriptor
		}, o);

		var expectData = expectationsLookup[incomingRoute.simpleHash()];

		if (!expectData || (util.isArray(expectData.length) && expectData.length === 0)) {
			return;
		}

		expectData = expectData.filter(function (route) {
			return route.compare(incomingRoute);
		});

		if (expectData.length > 0) {
			return expectData.pop();
		} else {
			return;
		}
	};

	this.listen = function (port, callback) {
		port = port || 3000;
		server = app.listen(port, function () {
		    debug('Interfake is listening for requests on port', server.address().port);
			// debug('Interfake is listening for requests on port ' + port);
			if(util.isFunction(callback)) {
				callback();
			}
		});
	};

	this.stop = function () {
		if (server) {
			debug('Interfake is stopping');
			server.close(function () {
				debug('Interfake has stopped');
				server = undefined;
			});
		}
	};
}

Interfake.prototype.loadFile = function (filePath) {
	var file;

	filePath = path.resolve(process.cwd(), filePath);

	file = require(filePath);

	file.forEach(function (endpoint) {
		this.createRoute(endpoint);
	}.bind(this));
};

module.exports = Interfake;
<commit_msg>Deleted unnecessary method<commit_after>var express = require('express');
var path = require('path');
var FluentInterface = require('./fluent');
var corsMiddleware = require('./cors');
var util = require('core-util-is');
var url = require('url');
var connectJson = require('connect-json');
var bodyParser = require('body-parser');
var Route = require('./route');

function determineDelay(delayInput) {
	var result = 0, range, upper, lower;
	if(util.isNumber(delayInput)) {
		result = delayInput;
	} else if(util.isString(delayInput)) {
		range = /([0-9]+)..([0-9]+)/.exec(delayInput);
		upper = +range[2];
		lower = +range[1];
		result = Math.floor( Math.random() * (upper - lower + 1) + lower );
	}

	return result;
}

function Interfake(o) {
	o = o || { debug: false };
	var app = express();
	var router = express.Router();
	var fluentInterface = new FluentInterface(this, o);
	var debug = require('./debug')('interfake-server', o.debug);
	var expectationsLookup = {};
	var server;

	o.path = url.resolve('/', o.path || '');

	debug('Root path is', o.path);

	app.use(o.path, router);
	app.use(connectJson());
	app.use(bodyParser());
	app.use(corsMiddleware);

	app.post('/_requests?', function(req, res){
		try {
			debug('Being hit with a _request request');
			createRoute(req.body);
			debug('Returning');
			res.send(201, { done : true });
		} catch (e) {
			debug('Error: ', e);
			res.send(400, e);
		}
	});

	app.all('/*', function(req, res) {
		debug(req.method, 'request to', req.url);
		var hashData = {
			method: req.method,
			url: req.path,
			query: req.query
		};
		var rootPathRegex;

		if (o.path.length > 1) {
			rootPathRegex = new RegExp('^' + o.path);
			if (!rootPathRegex.test(hashData.url)) {
				return res.send(404);
			}
			hashData.url = hashData.url.replace(rootPathRegex, '');
		}

		var incomingRoute = new Route({
			request: hashData
		}, o);

		var expectData = expectationsLookup[incomingRoute.simpleHash()];
		var expectedRoute;

		if (!expectData || (util.isArray(expectData.length) && expectData.length === 0)) {
			return res.send(404);
		}

		expectData = expectData.filter(function (route) {
			return route.compare(incomingRoute);
		});

		if (expectData.length > 0) {
			expectedRoute = expectData.pop();
		} else {
			return res.send(404);
		}

		var specifiedResponse = expectedRoute.response; // req.route.responseData;
		var afterSpecifiedResponse = expectedRoute.afterResponse; //req.route.afterResponseData;
		var responseDelay = determineDelay(specifiedResponse.delay);

		debug(req.method, 'request to', req.url, 'returning', specifiedResponse.code);
		debug(req.method, 'request to', req.url, 'will be delayed by', responseDelay, 'millis');
		debug('Expected route is', expectedRoute);

		var responseBody = specifiedResponse.body;

		res.setHeader('Content-Type', 'application/json');

		if (specifiedResponse.headers) {
			Object.keys(specifiedResponse.headers).forEach(function (k) {
				res.setHeader(k, specifiedResponse.headers[k]);
			});
		}

		if (req.query.callback) {
			debug('Request is asking for jsonp');
			if (typeof responseBody !== 'string') responseBody = JSON.stringify(responseBody);
			responseBody = req.query.callback.trim() + '(' + responseBody + ');';
		}

		setTimeout(function() {
			var modification;
			debug('Expected response is', specifiedResponse);

			res.send(specifiedResponse.code, responseBody);

			if (afterSpecifiedResponse && afterSpecifiedResponse.endpoints) {
				debug('Response sent, setting up', afterSpecifiedResponse.endpoints.length, 'endpoints');
				afterSpecifiedResponse.endpoints.forEach(function (route) {
					debug('Setting up route', route.hash());
					addRoute(route);
				});
			}

			if (afterSpecifiedResponse && afterSpecifiedResponse.modifications) {
				debug('Response sent, making', afterSpecifiedResponse.modifications.length, 'modifications');
				while (afterSpecifiedResponse.modifications.length > 0) {
					modification = afterSpecifiedResponse.modifications.pop();

					modification.route = this.routeMatching(modification.routeDescriptor);

					if (!modification.route) {
						throw new Error('No route matching', modification.routeDescriptor, 'was found');
					}

					if (modification.body) {
						debug('Modifying body');
						modification.route.mergeResponseBody(modification.body);
					}

					if (modification.code) {
						debug('Modifying code to', modification.code);
						modification.route.setStatusCode(modification.code);
					}

					if (modification.delay) {
						debug('Modifying delay to', modification.delay);
						modification.route.setResponseDelay(modification.delay);
					}

					if (modification.responseHeaders) {
						debug('Modifying response headers');
						modification.route.mergeResponseHeaders(modification.responseHeaders);
					}
				}
			}
		}.bind(this), responseDelay);
	}.bind(this));

	function addRoute(route) {
		if (expectationsLookup[route.simpleHash()]) {
			expectationsLookup[route.simpleHash()].push(route);
		} else {
			expectationsLookup[route.simpleHash()] = [ route ];
		}
	}

	function createRoute(data) {
		var newRoute;

		debug('Setting up new route');

		newRoute = new Route(data, o);

		addRoute(newRoute);

		debug('Setup complete');

		return newRoute;
	}

	this.createRoute = createRoute;

	this.get = fluentInterface.fluentCreate('get');
	this.post = fluentInterface.fluentCreate('post');
	this.put = fluentInterface.fluentCreate('put');
	this.delete = fluentInterface.fluentCreate('delete');

	this.serveStatic = function (path, directory) {
		path = path || '/_static';
		app.use(path, express.static(directory));
	};

	this.routeMatching = function (requestDescriptor) {
		var incomingRoute = new Route({
			request: requestDescriptor
		}, o);

		var expectData = expectationsLookup[incomingRoute.simpleHash()];

		if (!expectData || (util.isArray(expectData.length) && expectData.length === 0)) {
			return;
		}

		expectData = expectData.filter(function (route) {
			return route.compare(incomingRoute);
		});

		if (expectData.length > 0) {
			return expectData.pop();
		} else {
			return;
		}
	};

	this.listen = function (port, callback) {
		port = port || 3000;
		server = app.listen(port, function () {
			debug('Interfake is listening for requests on port', server.address().port);
			// debug('Interfake is listening for requests on port ' + port);
			if(util.isFunction(callback)) {
				callback();
			}
		});
	};

	this.stop = function () {
		if (server) {
			debug('Interfake is stopping');
			server.close(function () {
				debug('Interfake has stopped');
				server = undefined;
			});
		}
	};
}

Interfake.prototype.loadFile = function (filePath) {
	var file;

	filePath = path.resolve(process.cwd(), filePath);

	file = require(filePath);

	file.forEach(function (endpoint) {
		this.createRoute(endpoint);
	}.bind(this));
};

module.exports = Interfake;
<|endoftext|>


<commit_before>'use strict';

var Chat = require('./chat');

var ChatInterface = {
	initSocket: function(socket) {

		socket.onAccount('chat', function(data, account) {
			socket.isSilenced(function(err, silenced) {
				if(err) {
					return err;
				}
				if(silenced) {
					return socket.emit('silenced', 'you have been silenced');
				}
				return Chat.safeAdd(account, data.txt, data.roomName);
			});
		});

		socket.on('chatHistory', function(roomName) {
			socket.emit('chatHistory', {
				roomName: roomName,
				history: Chat.safeGetHistory(roomName)
			});
		});

		socket.on('createChat', function(roomName) {
			Chat.safeCreate(roomName);
		});
	}
};

module.exports = ChatInterface;<commit_msg>restrict sending chats in guild chat<commit_after>'use strict';

var Chat = require('./chat');
var canJoinRoom = require('./canJoinRoom');

var ChatInterface = {
	initSocket: function(socket) {

		socket.onAccount('chat', function(data, account) {
			socket.isSilenced(function(err, silenced) {
				if(err) {
					return err;
				}
				if(silenced) {
					return socket.emit('silenced', 'you have been silenced');
				}
				if(!canJoinRoom(account, data.roomName)) {
					return 'You can not send messages to this room';
				}
				return Chat.safeAdd(account, data.txt, data.roomName);
			});
		});

		socket.on('chatHistory', function(roomName) {
			socket.emit('chatHistory', {
				roomName: roomName,
				history: Chat.safeGetHistory(roomName)
			});
		});

		socket.on('createChat', function(roomName) {
			Chat.safeCreate(roomName);
		});
	}
};

module.exports = ChatInterface;<|endoftext|>