<commit_before>const frisby = require('frisby')
const Joi = frisby.Joi
const insecurity = require('../../lib/insecurity')

const API_URL = 'http://localhost:3000/api'

const injectionParam = '{"$lt":200}'

const authHeader = { 'Authorization': 'Bearer ' + insecurity.authorize(), 'content-type': 'application/json' }

describe('/api/Recycles', () => {
  it('POST new recycle', () => {
    return frisby.post(API_URL + '/Recycles', {
      headers: authHeader,
      body: {
        quantity: 200,
        address: 'Bjoern Kimminich, 123 Juicy Road, Test City',
        isPickup: true,
        date: '2017-05-31'
      }
    })
      .expect('status', 201)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data', {
        id: Joi.number(),
        createdAt: Joi.string(),
        updatedAt: Joi.string()
      })
  })

  it('Will prevent GET all recycles from this endpoint', () => {
    return frisby.get(API_URL + '/Recycles')
      .expect('status', 200)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data', {
        err: 'Sorry, this endpoint is not supported.'
      })
  })

  it('Will check if the injection works and returns the expected recycle', () => {
    return frisby.get(API_URL + '/Recycles/' + injectionParam)
      .expect('status', 200)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data[0]', { id: 33 })
  })

  it('PUT update existing recycle is forbidden', () => {
    return frisby.put(API_URL + '/Recycles/1', {
      headers: authHeader,
      body: {
        quantity: 100000
      }
    })
      .expect('status', 401)
  })

  it('DELETE existing recycle is forbidden', () => {
    return frisby.del(API_URL + '/Recycles/1', { headers: authHeader })
      .expect('status', 401)
  })
})
<commit_msg>Fix ID of injection recycle result and inline parameter<commit_after>const frisby = require('frisby')
const Joi = frisby.Joi
const insecurity = require('../../lib/insecurity')

const API_URL = 'http://localhost:3000/api'

const authHeader = { 'Authorization': 'Bearer ' + insecurity.authorize(), 'content-type': 'application/json' }

describe('/api/Recycles', () => {
  it('POST new recycle', () => {
    return frisby.post(API_URL + '/Recycles', {
      headers: authHeader,
      body: {
        quantity: 200,
        address: 'Bjoern Kimminich, 123 Juicy Road, Test City',
        isPickup: true,
        date: '2017-05-31'
      }
    })
      .expect('status', 201)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data', {
        id: Joi.number(),
        createdAt: Joi.string(),
        updatedAt: Joi.string()
      })
  })

  it('Will prevent GET all recycles from this endpoint', () => {
    return frisby.get(API_URL + '/Recycles')
      .expect('status', 200)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data', {
        err: 'Sorry, this endpoint is not supported.'
      })
  })

  it('Will check if the injection works and returns the expected recycle', () => {
    return frisby.get(API_URL + '/Recycles/' + '{"$lt":200}')
      .expect('status', 200)
      .expect('header', 'content-type', /application\/json/)
      .expect('jsonTypes', 'data[0]', { id: 42 })
  })

  it('PUT update existing recycle is forbidden', () => {
    return frisby.put(API_URL + '/Recycles/1', {
      headers: authHeader,
      body: {
        quantity: 100000
      }
    })
      .expect('status', 401)
  })

  it('DELETE existing recycle is forbidden', () => {
    return frisby.del(API_URL + '/Recycles/1', { headers: authHeader })
      .expect('status', 401)
  })
})
<|endoftext|>


<commit_before>'use strict';

var Country 		= require('mongoose').model('Country'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Link            = require('mongoose').model('Link'),
    Project 		= require('mongoose').model('Project'),
    Company 		= require('mongoose').model('Company'),
    Concession 		= require('mongoose').model('Concession'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request');

exports.getCountries = function(req, res) {
    var country_len,country_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        countryCount,
        getCountrySet,
        getCountryProjectCount
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function countryCount(callback) {
        Country.find({}).count().exec(function(err, country_count) {
            if(country_count) {
                callback(null, country_count);
            } else {
                callback(err);
            }
        });
    }
    function getCountrySet(country_count, callback) {
        Country.find(req.query)
            .sort({
                name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('country_aliases', ' _id alias model')
            //.populate('projects')
            .lean()
            .exec(function(err, countries) {
                if(countries) {
                    //res.send({data:countries, count:country_count});
                    callback(null, country_count, countries);
                } else {
                    callback(err);
                }
            });
    }
    function getCountryProjectCount(country_count, countries, callback) {
        country_len = countries.length;
        country_counter = 0;
        countries.forEach(function (c) {
            Project.find({'proj_country.country': c._id}).count().exec(function(err, project_count) {
                ++country_counter;
                c.projects = project_count;
                if(country_counter == country_len) {
                    res.send({data:countries, count:country_count});
                }
            });

        });
    }
};

exports.getCountryByID = function(req, res) {
	var concession_len, concession_counter, link_counter, link_len, company_counter, company_len, project_counter, project_len;
	async.waterfall([
		getCountry,
		getCountryCompanies,
		getCountryProjects,
		getCountryConcessions,
		getContracts,
		getCompanyGroupLinks,
		getProjectLinks,
		getConcessionLinks,
		getTransfers
	], function (err, result) {
		if (err) {
			res.send(err);
		}
	});

	function getCountry(callback) {
		Country.findOne({iso2:req.params.id})
			.populate('country_commodity.commodity')
			.lean()
			.exec(function(err, country) {
				if(country) {
					callback(null, country);
				} else {
					res.send(err);
				}
			});
	}
	function getCountryCompanies(country, callback) {
		country.companies = [];
		Company.find({'countries_of_operation.country': country._id,'country_of_incorporation.country': country._id})
				.populate('company_aliases', ' _id alias')
				.populate('company_group')
				.exec(function (err, company) {
				company_len = company.length;
				company_counter = 0;
				if (company_len>0) {
					_.each(company, function (c) {
						company_counter++;
						country.companies.push({_id:c._id,company_name: c.company_name,company_groups:[]});
					});
					if(company_counter==company_len){
						callback(null, country);
					}
				} else {
					callback(null, country);
				}
			});
	}
	function getCountryProjects(country, callback) {
		var project_counter= 0;
		country.projects = [];
		country.location = [];
		Project.find({'proj_country.country': country._id})
			.populate('proj_country.country')
			.populate('proj_aliases', ' _id alias')
			.populate('proj_commodity.commodity')
			.exec(function (err, project) {
				var project_len = project.length;
				if (project_len>0) {
					_.each(project, function (proj) {
							++project_counter;
							country.projects.push({
								_id: proj._id,
								proj_name: proj.proj_name,
								proj_commodity: proj.proj_commodity,
								proj_status: proj.proj_status,
								companies: []
							});
							_.each(proj.proj_coordinates, function (loc) {
								country.location.push({
									'lat': loc.loc[0],
									'lng': loc.loc[1],
									'message': "" + proj.proj_name + "
" + proj.proj_name
								});
							});
							if (project_counter == project_len) {
								callback(null, country);
							}
						}
					);
				} else {
					callback(null, country);
				}
			});
	}
	function getCountryConcessions(country, callback) {
		concession_counter = 0;
		country.concessions = [];
		Concession.find({'concession_country.country': country._id})
			.populate('concession_country.country')
			.populate('concession_commodity.commodity')
			.exec(function (err, concessions) {
				if (concessions.length>0) {
					concession_len = concessions.length;
					_.each(concessions, function (concession) {
						++concession_counter;
						country.concessions.push({
							_id: concession._id,
							concession_name: concession.concession_name,
							concession_country: _.find(concession.concession_country.reverse()).country,
							concession_type: _.find(concession.concession_type.reverse()),
							concession_commodities: concession.concession_commodity,
							concession_status: concession.concession_status,
							projects:[]
						});
						if (concession_counter == concession_len) {
							callback(null, country);
						}

					});
				} else {
					callback(null, country);
				}
			});
	}
	function getContracts(country, callback) {
		country.contracts = [];
		request('http://rc-api-stage.elasticbeanstalk.com/api/contracts/search?group=metadata&country_code=' + country.iso2.toLowerCase(), function (err, res, body) {
			var body = JSON.parse(body);
			body = body.results;
			var contract_counter = 0;
			var contract_len =body.length;
			if(contract_len>0) {
				country.concessions = [];
				_.each(body, function (contract) {
					++contract_counter;
					country.contracts.push({
						_id: contract.open_contracting_id,
						contract_name: contract.name,
						contract_commodity: contract.resource,
						companies:contract.company_name
					});
					if (contract_counter == contract_len) {
						callback(null, country);
					}
				});
			} else {
				callback(null, country);
			}
		});
	}
	function getCompanyGroupLinks(country, callback) {
		company_counter = 0;
		link_counter = 0;
		company_len = country.companies.length;
		if(company_len>0) {
			_.each(country.companies,function (company) {
				Link.find({company: company._id})
					.populate('company_group','_id company_group_name')
					.exec(function (err, links) {
						++company_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'company')[0];
							switch (entity) {
								case 'company_group':
									company.company_groups.push({
											_id:link._id,
											company_group_name: link.company_group.company_group_name
									});
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && company_len==company_counter) {
							callback(null, country);
						}
					});
			})
		} else {
			callback(null, country);
		}
	}
	function getProjectLinks(country, callback) {
		project_counter = 0;
		link_counter = 0;
		project_len = country.projects.length;
		if(project_len>0) {
			_.each(country.projects, function (project) {
				project.companies = 0;
				Link.find({project: project._id})
					.populate('company_group','_id company_group_name')
					.exec(function (err, links) {
						++project_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'project')[0];
							switch (entity) {
								case 'company':
									project.companies += 1;
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && project_counter==project_len) {
							callback(null, country);
						}
					});
			})
		} else {
			callback(null, country);
		}
	}
	function getConcessionLinks(country, callback) {
		concession_counter = 0;
		link_counter = 0;
		concession_len = country.concessions.length;
		if(concession_len>0) {
			_.each(country.concessions, function (concession) {
				concession.projects = 0;
				Link.find({concession: concession._id})
					.populate('project')
					.exec(function (err, links) {
						++concession_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'concession')[0];
							switch (entity) {
								case 'project':
									concession.projects += 1;
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && concession_counter==concession_len) {
							callback(null, country);
						}
					});
			})
		} else {
			callback(null, country);
		}
	}
	function getTransfers(country, callback) {
		country.transfers = [];
		Transfer.find({transfer_country: country._id})
			.populate('transfer_country')
			.populate('transfer_company', '_id company_name')
			.populate('transfer_project', '_id proj_name')
			.exec(function(err, transfers) {
				if(transfers) {
					_.each(transfers, function (transfer) {
						country.transfers.push(transfer);
					});
				}
				res.send(country);
			});
	}
};

exports.createCountry = function(req, res, next) {
	var countryData = req.body;
	Country.create(countryData, function(err, country) {
		if(err){
			res.status(400);
			err = new Error('Error');
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};
exports.updateCountry = function(req, res) {
	var countryUpdates = req.body;
	Country.findOne({_id:req.body._id}).exec(function(err, country) {
		if(err) {
			res.status(400);
			err = new Error('Error');
			return res.send({ reason: err.toString() });
		}
		country.iso2= countryUpdates.iso2;
		country.name= countryUpdates.name;
		//country.country_aliases= countryUpdates.country_aliases;
		//country.country_type= countryUpdates.country_type;
		//country.country_commodity= countryUpdates.country_commodity;
		country.save(function(err) {
			if(err) {
				err = new Error('Error');
				return res.send({reason: err.toString()});
			} else{
				res.send();
			}
		})
	});
};

exports.deleteCountry = function(req, res) {
	Country.remove({_id: req.params.id}, function(err) {
		if(!err) {
			res.send();
		}else{
			err = new Error('Error');
			return res.send({ reason: err.toString() });
		}
	});
};<commit_msg>SAVEPOINT<commit_after>'use strict';

var Country 		= require('mongoose').model('Country'),
    Transfer 	    = require('mongoose').model('Transfer'),
    Link            = require('mongoose').model('Link'),
    Project 		= require('mongoose').model('Project'),
    Company 		= require('mongoose').model('Company'),
    Concession 		= require('mongoose').model('Concession'),
    async           = require('async'),
    _               = require("underscore"),
    request         = require('request');

exports.getCountries = function(req, res) {
    var country_len,country_counter,
        limit = Number(req.params.limit),
        skip = Number(req.params.skip);

    async.waterfall([
        countryCount,
        getCountrySet,
        getCountryProjectCount
    ], function (err, result) {
        if (err) {
            res.send(err);
        }
    });

    function countryCount(callback) {
        Country.find({}).count().exec(function(err, country_count) {
            if(country_count) {
                callback(null, country_count);
            } else {
                callback(err);
            }
        });
    }
    function getCountrySet(country_count, callback) {
        Country.find(req.query)
            .sort({
                name: 'asc'
            })
            .skip(skip)
            .limit(limit)
            .populate('country_aliases', ' _id alias model')
            //.populate('projects')
            .lean()
            .exec(function(err, countries) {
                if(countries) {
                    //res.send({data:countries, count:country_count});
                    callback(null, country_count, countries);
                } else {
                    callback(err);
                }
            });
    }
    function getCountryProjectCount(country_count, countries, callback) {
        country_len = countries.length;
        country_counter = 0;
        countries.forEach(function (c) {
            Project.find({'proj_country.country': c._id}).count().exec(function(err, project_count) {
                ++country_counter;
                c.projects = project_count;
                if(country_counter == country_len) {
                    res.send({data:countries, count:country_count});
                }
            });

        });
    }
};

exports.getCountryByID = function(req, res) {
	var concession_len, concession_counter, link_counter, link_len, company_counter, company_len, project_counter, project_len;
	async.waterfall([
		getCountry,
		getCountryCompanies,
		getCountryProjects,
		getCountryConcessions,
		getContracts,
		getCompanyGroupLinks,
		getProjectLinks,
		getConcessionLinks,
		getTransfers
	], function (err, result) {
		if (err) {
			res.send(err);
		}
	});

	function getCountry(callback) {
		Country.findOne({iso2:req.params.id})
			.populate('country_commodity.commodity')
			.lean()
			.exec(function(err, country) {
				if(country) {
					callback(null, country);
				} else {
					res.send(err);
				}
			});
	}
	function getCountryCompanies(country, callback) {
		country.companies = [];
		Company.find({'countries_of_operation.country': country._id,'country_of_incorporation.country': country._id})
				.populate('company_aliases', ' _id alias')
				.populate('company_group')
				.exec(function (err, company) {
				company_len = company.length;
				company_counter = 0;
				if (company_len>0) {
					_.each(company, function (c) {
						company_counter++;
						country.companies.push({_id:c._id,company_name: c.company_name,company_groups:[]});
					});
					if(company_counter==company_len){
						callback(null, country);
					}
				} else {
					callback(null, country);
				}
			});
	}
	function getCountryProjects(country, callback) {
		var project_counter= 0;
		country.projects = [];
		country.location = [];
		Project.find({'proj_country.country': country._id})
			.populate('proj_country.country')
			.populate('proj_aliases', ' _id alias')
			.populate('proj_commodity.commodity')
			.exec(function (err, project) {
				var project_len = project.length;
				if (project_len>0) {
					_.each(project, function (proj) {
							++project_counter;
							country.projects.push({
								_id: proj._id,
								proj_name: proj.proj_name,
								proj_commodity: proj.proj_commodity,
								proj_status: proj.proj_status,
								companies: []
							});
							_.each(proj.proj_coordinates, function (loc) {
								country.location.push({
									'lat': loc.loc[0],
									'lng': loc.loc[1],
									'message': "" + proj.proj_name + "
" + proj.proj_name
								});
							});
							if (project_counter == project_len) {
								callback(null, country);
							}
						}
					);
				} else {
					callback(null, country);
				}
			});
	}
	function getCountryConcessions(country, callback) {
		concession_counter = 0;
		country.concessions = [];
		Concession.find({'concession_country.country': country._id})
			.populate('concession_country.country')
			.populate('concession_commodity.commodity')
			.exec(function (err, concessions) {
				if (concessions.length>0) {
					concession_len = concessions.length;
					_.each(concessions, function (concession) {
						++concession_counter;
						country.concessions.push({
							_id: concession._id,
							concession_name: concession.concession_name,
							concession_country: _.find(concession.concession_country.reverse()).country,
							concession_type: _.find(concession.concession_type.reverse()),
							concession_commodities: concession.concession_commodity,
							concession_status: concession.concession_status,
							projects:[]
						});
						if (concession_counter == concession_len) {
							callback(null, country);
						}

					});
				} else {
					callback(null, country);
				}
			});
	}
	function getContracts(country, callback) {
		country.contracts = [];
		request('http://rc-api-stage.elasticbeanstalk.com/api/contracts/search?group=metadata&country_code=' + country.iso2.toLowerCase(), function (err, res, body) {
			var body = JSON.parse(body);
			body = body.results;
			var contract_counter = 0;
			var contract_len =body.length;
			if(contract_len>0) {
				country.concessions = [];
				_.each(body, function (contract) {
					++contract_counter;
					country.contracts.push({
						_id: contract.open_contracting_id,
						contract_name: contract.name,
						contract_commodity: contract.resource,
						companies:contract.company_name
					});
					if (contract_counter == contract_len) {
						callback(null, country);
					}
				});
			} else {
				callback(null, country);
			}
		});
	}
	function getCompanyGroupLinks(country, callback) {
		company_counter = 0;
		link_counter = 0;
		company_len = country.companies.length;
		if(company_len>0) {
			_.each(country.companies,function (company) {
				Link.find({company: company._id})
					.populate('company_group','_id company_group_name')
					.exec(function (err, links) {
						++company_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'company')[0];
							switch (entity) {
								case 'company_group':
									company.company_groups.push({
											_id:link._id,
											company_group_name: link.company_group.company_group_name
									});
									console.log('4');
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && company_len==company_counter) {
							console.log('1');
							callback(null, country);
						}
					});
			})
		} else {
			console.log('3');
			callback(null, country);
		}
	}
	function getProjectLinks(country, callback) {
		project_counter = 0;
		link_counter = 0;
		project_len = country.projects.length;
		if(project_len>0) {
			_.each(country.projects, function (project) {
				project.companies = 0;
				Link.find({project: project._id})
					.populate('company_group','_id company_group_name')
					.exec(function (err, links) {
						++project_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'project')[0];
							switch (entity) {
								case 'company':
									project.companies += 1;
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && project_counter==project_len) {
							callback(null, country);
						}
					});
			})
		} else {
			callback(null, country);
		}
	}
	function getConcessionLinks(country, callback) {
		concession_counter = 0;
		link_counter = 0;
		concession_len = country.concessions.length;
		if(concession_len>0) {
			_.each(country.concessions, function (concession) {
				concession.projects = 0;
				Link.find({concession: concession._id})
					.populate('project')
					.exec(function (err, links) {
						++concession_counter;
						link_len = links.length;
						link_counter = 0;
						links.forEach(function (link) {
							++link_counter;
							var entity = _.without(link.entities, 'concession')[0];
							switch (entity) {
								case 'project':
									concession.projects += 1;
									break;
								default:
									console.log(entity, 'link skipped...');
							}
						});
						if (link_counter == link_len && concession_counter==concession_len) {
							callback(null, country);
						}
					});
			})
		} else {
			callback(null, country);
		}
	}
	function getTransfers(country, callback) {
		country.transfers = [];
		Transfer.find({transfer_country: country._id})
			.populate('transfer_country')
			.populate('transfer_company', '_id company_name')
			.populate('transfer_project', '_id proj_name')
			.exec(function(err, transfers) {
				if(transfers) {
					_.each(transfers, function (transfer) {
						country.transfers.push(transfer);
					});
				}
				res.send(country);
			});
	}
};

exports.createCountry = function(req, res, next) {
	var countryData = req.body;
	Country.create(countryData, function(err, country) {
		if(err){
			res.status(400);
			err = new Error('Error');
			return res.send({reason:err.toString()})
		} else{
			res.send();
		}
	});
};
exports.updateCountry = function(req, res) {
	var countryUpdates = req.body;
	Country.findOne({_id:req.body._id}).exec(function(err, country) {
		if(err) {
			res.status(400);
			err = new Error('Error');
			return res.send({ reason: err.toString() });
		}
		country.iso2= countryUpdates.iso2;
		country.name= countryUpdates.name;
		//country.country_aliases= countryUpdates.country_aliases;
		//country.country_type= countryUpdates.country_type;
		//country.country_commodity= countryUpdates.country_commodity;
		country.save(function(err) {
			if(err) {
				err = new Error('Error');
				return res.send({reason: err.toString()});
			} else{
				res.send();
			}
		})
	});
};

exports.deleteCountry = function(req, res) {
	Country.remove({_id: req.params.id}, function(err) {
		if(!err) {
			res.send();
		}else{
			err = new Error('Error');
			return res.send({ reason: err.toString() });
		}
	});
};<|endoftext|>


<commit_before><commit_msg>Updated Enabled option to style player<commit_after><|endoftext|>


<commit_before>var request = require('request');
var FeedParser = require('feedparser');

module.exports = function (model) {
	return {
		post: {
			preview: function (req, res, next) {
				var items = [];

				request(req.body.url)
					.pipe(new FeedParser())
					.on('error', function (e) {
						console.error(e);
						res.send(500);
					})
					.on('readable', function () {
						var item;

						while (item = this.read()) {
							items[items.length] = item;
						}
					})
					.on('end', function () {
						res.json(items.map(function (item) {
							return { title: item.title, categories: item.categories, summary: item.summary };
						}));
					});
			}
		}
	};
};<commit_msg>Start to implement the rss pulls<commit_after>var request = require('request');
var FeedParser = require('feedparser');
var _ = require('lodash');

var config = require('../../config');

module.exports = function (model) {
	setInterval(function () {
		var entries = _.values(model.get('entries'));
		for (var i = 0; i < entries.length; ++i) {
			var entry = entries[i];

			if (entry.downloadDir && entry.sources && entry.sources.length) {

			}
		}
	}, config.rssRefresh);

	return {
		post: {
			preview: function (req, res, next) {
				var items = [];

				request(req.body.url)
					.pipe(new FeedParser())
					.on('error', function (e) {
						console.error(e);
						res.send(500);
					})
					.on('readable', function () {
						var item;

						while (item = this.read()) {
							items[items.length] = item;
						}
					})
					.on('end', function () {
						res.json(items.map(function (item) {
							return { title: item.title, categories: item.categories, summary: item.summary };
						}));
					});
			}
		}
	};
};<|endoftext|>


<commit_before>"use strict";

const BalancedList = require("../src/balanced-list");

describe("Test BalancedList", () => {

	it("test constructor", () => {
		let opts = {
			mode: 1,
			preferLocal: false
		};
		let list = new BalancedList(opts);
		expect(list).toBeDefined();
		expect(list.list).toBeDefined();
		expect(list.opts).toBe(opts);
		expect(list.counter).toBe(0);

		expect(list.get()).toBeNull();
		expect(list.hasLocal()).toBeFalsy();
	});

	it("test get with remote & preferLocal", () => {
		let obj1 = { a: 1};
		let obj2 = { b: 2};
		let obj3 = { c: 3};
		let list = new BalancedList();
		list.add(obj1, 0, "node1"); // remote
		list.add(obj2, 20, "node2"); // remote
		list.add(obj3, 0); // local

		expect(list.hasLocal()).toBeTruthy();
		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeTruthy();
		expect(item.nodeID).toBeUndefined();
		expect(item.data).toBe(obj3);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(0);

		list.remove(obj3);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(2);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.hasLocal()).toBeFalsy();

	});

	it("test get with remote & NOT preferLocal", () => {
		let obj1 = { a: 1};
		let obj2 = { b: 2};
		let obj3 = { c: 3};
		let list = new BalancedList({ preferLocal: false});
		list.add(obj1, 0, "node1");
		list.add(obj2, 20, "node2");
		list.add(obj3, 0); // local
		expect(list.hasLocal()).toBeTruthy();

		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeFalsy();
		expect(item.nodeID).toBe("node1");
		expect(item.data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(2);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(3);

		list.remove(obj1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(2);

	});

	it("test add & get with local", () => {
		let obj1 = {};
		let obj2 = {};
		let list = new BalancedList();
		list.add(obj1);
		list.add(obj2, 20);
		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeTruthy();
		expect(item.nodeID).toBeUndefined();
		expect(item.data).toBe(obj1);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(0);
		expect(list.hasLocal()).toBeTruthy();

		list.remove(obj1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(0);

	});

});
<commit_msg>cover balanced-list<commit_after>"use strict";

const BalancedList = require("../src/balanced-list");

describe("Test BalancedList", () => {

	it("test constructor", () => {
		let opts = {
			mode: 1,
			preferLocal: false
		};
		let list = new BalancedList(opts);
		expect(list).toBeDefined();
		expect(list.list).toBeDefined();
		expect(list.opts).toBe(opts);
		expect(list.counter).toBe(0);
		expect(list.count()).toBe(0);

		expect(list.get()).toBeNull();
		expect(list.hasLocal()).toBeFalsy();
	});

	it("test get with remote & preferLocal", () => {
		let obj1 = { a: 1};
		let obj2 = { b: 2};
		let obj3 = { c: 3};
		let list = new BalancedList();
		list.add(obj1, 0, "node1"); // remote
		list.add(obj2, 20, "node2"); // remote
		list.add(obj3, 0); // local

		expect(list.count()).toBe(3);
		expect(list.hasLocal()).toBeTruthy();
		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeTruthy();
		expect(item.nodeID).toBeUndefined();
		expect(item.data).toBe(obj3);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(0);

		item = list.getLocalItem();
		expect(item.local).toBeTruthy();
		expect(item.nodeID).toBeUndefined();
		expect(item.data).toBe(obj3);

		list.remove(obj3);
		expect(list.count()).toBe(2);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(2);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.hasLocal()).toBeFalsy();

		item = list.getLocalItem();
		expect(item).toBeUndefined();

		list.removeByNode("no-id");
		expect(list.count()).toBe(2);

		list.removeByNode("node1");
		expect(list.count()).toBe(1);

	});

	it("test get with remote & NOT preferLocal", () => {
		let obj1 = { a: 1};
		let obj2 = { b: 2};
		let obj3 = { c: 3};
		let list = new BalancedList({ preferLocal: false});
		list.add(obj1, 0, "node1");
		list.add(obj2, 20, "node2");
		list.add(obj3, 0); // local
		expect(list.hasLocal()).toBeTruthy();

		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeFalsy();
		expect(item.nodeID).toBe("node1");
		expect(item.data).toBe(obj1);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(2);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(3);

		list.remove(obj1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(1);
		expect(list.get().data).toBe(obj3);
		expect(list.counter).toBe(2);

	});

	it("test add & get with local", () => {
		let obj1 = {};
		let obj2 = {};
		let list = new BalancedList();
		list.add(obj1);
		list.add(obj2, 20);
		expect(list.counter).toBe(0);
		let item = list.get();
		expect(item.local).toBeTruthy();
		expect(item.nodeID).toBeUndefined();
		expect(item.data).toBe(obj1);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj1);
		expect(list.counter).toBe(0);
		expect(list.hasLocal()).toBeTruthy();

		list.remove(obj1);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(0);
		expect(list.get().data).toBe(obj2);
		expect(list.counter).toBe(0);

	});

});
<|endoftext|>


<commit_before>// Show topics list (section)
//
'use strict';

const _       = require('lodash');
const Promise = require('bluebird');
const memoize = require('promise-memoize');

module.exports = function (N, apiPath) {

  N.validate(apiPath, {
    section_hid: { type: 'integer', required: true },
    topic_hid:   { type: 'integer', required: false },
    prev:        { type: 'string',  required: false },
    next:        { type: 'string',  required: false }
  });

  let buildTopicIdsBefore = require('./list/_build_topic_ids_before.js')(N);
  let buildTopicIdsAfter  = require('./list/_build_topic_ids_after.js')(N);

  let fetchSection = memoize(id =>
    N.models.forum.Section.findById(id).lean(true).exec(), { maxAge: 60000 });

  const buildTopicsIdsAndGetOffset = Promise.coroutine(function* (env) {
    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);
    let limit_direction = typeof env.params.prev !== 'undefined' || typeof env.params.next !== 'undefined';
    let current_topic;

    env.data.select_topics_start  = null;

    let results = [];

    if (env.params.topic_hid) {
      current_topic = yield N.models.forum.Topic.findOne({
        section: env.data.section._id,
        hid:     env.params.topic_hid,
        st:      { $in: statuses }
      });

      if (current_topic) {
        env.data.select_topics_start = current_topic[env.user_info.hb ? 'cache_hb' : 'cache'].last_post;
      }

      results.push(current_topic._id);
    }

    if (!limit_direction || typeof env.params.prev !== 'undefined') {
      env.data.select_topics_before = env.data.topics_per_page;
      yield buildTopicIdsBefore(env);
      results = env.data.topics_ids.slice(0).concat(results);
    }

    if (!limit_direction || typeof env.params.next !== 'undefined') {
      env.data.select_topics_after = env.data.topics_per_page;
      yield buildTopicIdsAfter(env);
      results = results.concat(env.data.topics_ids);
    }

    env.data.topics_ids = results;
  });

  // Subcall forum.topic_list
  //
  N.wire.on(apiPath, function* subcall_topic_list(env) {
    env.data.section_hid         = env.params.section_hid;
    env.data.build_topics_ids    = buildTopicsIdsAndGetOffset;
    env.data.topics_per_page     = yield env.extras.settings.fetch('topics_per_page');

    return N.wire.emit('internal:forum.topic_list', env);
  });

  // Fetch pagination
  //
  N.wire.after(apiPath, function* fetch_pagination(env) {
    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);

    //
    // Count total amount of visible topics in the section
    //
    let counters_by_status = yield Promise.map(
      statuses,
      st => N.models.forum.Topic
                .where('section').equals(env.data.section._id)
                .where('st').equals(st)
                .count()
    );

    let pinned_count = env.data.topics_visible_statuses.indexOf(N.models.forum.Topic.statuses.PINNED) === -1 ?
                       0 :
                       yield N.models.forum.Topic
                               .where('section').equals(env.data.section._id)
                               .where('st').equals(N.models.forum.Topic.statuses.PINNED)
                               .count();

    let topic_count = _.sum(counters_by_status) + pinned_count;

    //
    // Count an amount of visible topics before the first one
    //
    let topic_offset = 0;

    // if first topic is pinned, it's a first page and topic_offset is zero
    if (env.data.topics.length && env.data.topics[0].st !== N.models.forum.Topic.statuses.PINNED) {
      let cache        = env.user_info.hb ? 'cache_hb' : 'cache';
      let last_post_id = env.data.topics[0][cache].last_post;

      let counters_by_status = yield Promise.map(
        statuses,
        st => N.models.forum.Topic
                  .where(`${cache}.last_post`).gt(last_post_id)
                  .where('section').equals(env.data.section._id)
                  .where('st').equals(st)
                  .count()
      );

      topic_offset = _.sum(counters_by_status) + pinned_count;
    }

    env.res.pagination = {
      total:        topic_count,
      per_page:     env.data.topics_per_page,
      chunk_offset: topic_offset
    };
  });

  // Fetch visible sub-sections
  //
  N.wire.after(apiPath, function fetch_visible_subsections(env) {
    return N.wire.emit('internal:forum.subsections_fill', env);
  });

  // Fill subscription type
  //
  N.wire.after(apiPath, function* fill_subscription(env) {
    if (env.user_info.is_guest) {
      env.res.subscription = null;
      return;
    }

    let subscription = yield N.models.users.Subscription
                                .findOne({ user: env.user_info.user_id, to: env.data.section._id })
                                .lean(true);

    env.res.subscription = subscription ? subscription.type : null;
  });

  // Fill breadcrumbs info
  //
  N.wire.after(apiPath, function* fill_topic_breadcrumbs(env) {

    if (!env.data.section) return;

    let parents = yield N.models.forum.Section.getParentList(env.data.section._id);

    yield N.wire.emit('internal:forum.breadcrumbs_fill', { env, parents });
  });

  // Get parent section
  //
  N.wire.after(apiPath, function* fill_parent_hid(env) {
    let parents = yield N.models.forum.Section.getParentList(env.data.section._id);

    if (!parents.length) return;

    let section = yield fetchSection(parents[parents.length - 1]);

    if (!section) return;

    env.res.section_level = parents.length;
    env.res.parent_hid = section.hid;
  });

  // Fill head meta
  //
  N.wire.after(apiPath, function fill_head_and_breadcrumbs(env) {
    env.res.head = env.res.head || {};
    env.res.head.title = env.data.section.title;

    if (env.params.topic_hid) {
      env.res.head.robots = 'noindex,follow';
    }
  });

  // Fill 'prev' and 'next' links and meta tags
  //
  N.wire.after(apiPath, function* fill_prev_next(env) {
    env.res.head = env.res.head || {};

    let cache    = env.user_info.hb ? 'cache_hb' : 'cache';
    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);

    //
    // Fetch topic after last one, turn it into a link to the next page
    //
    if (env.data.topics.length > 0) {
      let last_post_id = env.data.topics[env.data.topics.length - 1][cache].last_post;

      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where(`${cache}.last_post`).lt(last_post_id)
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid -_id')
                                 .sort(`-${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.head.next = N.router.linkTo('forum.section', {
          section_hid: env.params.section_hid,
          topic_hid:   topic_data.hid
        }) + '?next';
      }
    }

    //
    // Fetch topic before first one, turn it into a link to the previous page;
    // (there is no previous page if the first topic is pinned)
    //
    if (env.data.topics.length > 0 &&
        env.data.topics[0].st !== N.models.forum.Topic.statuses.PINNED) {

      let last_post_id = env.data.topics[0][cache].last_post;

      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where(`${cache}.last_post`).gt(last_post_id)
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid')
                                 .sort(`${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.head.prev = N.router.linkTo('forum.section', {
          section_hid: env.params.section_hid,
          topic_hid:   topic_data.hid
        }) + '?prev';
      }
    }

    //
    // Fetch last topic for the "move to bottom" button
    //
    if (env.data.topics.length > 0) {
      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid')
                                 .sort(`${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.last_topic_hid = topic_data.hid;
      }
    }
  });
};
<commit_msg>Use env.params.$query for section prev/next params<commit_after>// Show topics list (section)
//
'use strict';

const _           = require('lodash');
const Promise     = require('bluebird');
const memoize     = require('promise-memoize');
const querystring = require('querystring');

module.exports = function (N, apiPath) {

  N.validate(apiPath, {
    section_hid: { type: 'integer', required: true },
    topic_hid:   { type: 'integer', required: false },
    $query:      { type: 'string',  required: false }
  });

  let buildTopicIdsBefore = require('./list/_build_topic_ids_before.js')(N);
  let buildTopicIdsAfter  = require('./list/_build_topic_ids_after.js')(N);

  let fetchSection = memoize(id =>
    N.models.forum.Section.findById(id).lean(true).exec(), { maxAge: 60000 });

  const buildTopicsIdsAndGetOffset = Promise.coroutine(function* (env) {
    let prev = false, next = false;

    if (env.params.$query) {
      let query = querystring.parse(env.params.$query);

      prev = typeof query.prev !== 'undefined';
      next = typeof query.next !== 'undefined';
    }

    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);
    let limit_direction = prev || next;
    let current_topic;

    env.data.select_topics_start  = null;

    let results = [];

    if (env.params.topic_hid) {
      current_topic = yield N.models.forum.Topic.findOne({
        section: env.data.section._id,
        hid:     env.params.topic_hid,
        st:      { $in: statuses }
      });

      if (current_topic) {
        env.data.select_topics_start = current_topic[env.user_info.hb ? 'cache_hb' : 'cache'].last_post;
      }

      results.push(current_topic._id);
    }

    if (!limit_direction || prev) {
      env.data.select_topics_before = env.data.topics_per_page;
      yield buildTopicIdsBefore(env);
      results = env.data.topics_ids.slice(0).concat(results);
    }

    if (!limit_direction || next) {
      env.data.select_topics_after = env.data.topics_per_page;
      yield buildTopicIdsAfter(env);
      results = results.concat(env.data.topics_ids);
    }

    env.data.topics_ids = results;
  });

  // Subcall forum.topic_list
  //
  N.wire.on(apiPath, function* subcall_topic_list(env) {
    env.data.section_hid         = env.params.section_hid;
    env.data.build_topics_ids    = buildTopicsIdsAndGetOffset;
    env.data.topics_per_page     = yield env.extras.settings.fetch('topics_per_page');

    return N.wire.emit('internal:forum.topic_list', env);
  });

  // Fetch pagination
  //
  N.wire.after(apiPath, function* fetch_pagination(env) {
    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);

    //
    // Count total amount of visible topics in the section
    //
    let counters_by_status = yield Promise.map(
      statuses,
      st => N.models.forum.Topic
                .where('section').equals(env.data.section._id)
                .where('st').equals(st)
                .count()
    );

    let pinned_count = env.data.topics_visible_statuses.indexOf(N.models.forum.Topic.statuses.PINNED) === -1 ?
                       0 :
                       yield N.models.forum.Topic
                               .where('section').equals(env.data.section._id)
                               .where('st').equals(N.models.forum.Topic.statuses.PINNED)
                               .count();

    let topic_count = _.sum(counters_by_status) + pinned_count;

    //
    // Count an amount of visible topics before the first one
    //
    let topic_offset = 0;

    // if first topic is pinned, it's a first page and topic_offset is zero
    if (env.data.topics.length && env.data.topics[0].st !== N.models.forum.Topic.statuses.PINNED) {
      let cache        = env.user_info.hb ? 'cache_hb' : 'cache';
      let last_post_id = env.data.topics[0][cache].last_post;

      let counters_by_status = yield Promise.map(
        statuses,
        st => N.models.forum.Topic
                  .where(`${cache}.last_post`).gt(last_post_id)
                  .where('section').equals(env.data.section._id)
                  .where('st').equals(st)
                  .count()
      );

      topic_offset = _.sum(counters_by_status) + pinned_count;
    }

    env.res.pagination = {
      total:        topic_count,
      per_page:     env.data.topics_per_page,
      chunk_offset: topic_offset
    };
  });

  // Fetch visible sub-sections
  //
  N.wire.after(apiPath, function fetch_visible_subsections(env) {
    return N.wire.emit('internal:forum.subsections_fill', env);
  });

  // Fill subscription type
  //
  N.wire.after(apiPath, function* fill_subscription(env) {
    if (env.user_info.is_guest) {
      env.res.subscription = null;
      return;
    }

    let subscription = yield N.models.users.Subscription
                                .findOne({ user: env.user_info.user_id, to: env.data.section._id })
                                .lean(true);

    env.res.subscription = subscription ? subscription.type : null;
  });

  // Fill breadcrumbs info
  //
  N.wire.after(apiPath, function* fill_topic_breadcrumbs(env) {

    if (!env.data.section) return;

    let parents = yield N.models.forum.Section.getParentList(env.data.section._id);

    yield N.wire.emit('internal:forum.breadcrumbs_fill', { env, parents });
  });

  // Get parent section
  //
  N.wire.after(apiPath, function* fill_parent_hid(env) {
    let parents = yield N.models.forum.Section.getParentList(env.data.section._id);

    if (!parents.length) return;

    let section = yield fetchSection(parents[parents.length - 1]);

    if (!section) return;

    env.res.section_level = parents.length;
    env.res.parent_hid = section.hid;
  });

  // Fill head meta
  //
  N.wire.after(apiPath, function fill_head_and_breadcrumbs(env) {
    env.res.head = env.res.head || {};
    env.res.head.title = env.data.section.title;

    if (env.params.topic_hid) {
      env.res.head.robots = 'noindex,follow';
    }
  });

  // Fill 'prev' and 'next' links and meta tags
  //
  N.wire.after(apiPath, function* fill_prev_next(env) {
    env.res.head = env.res.head || {};

    let cache    = env.user_info.hb ? 'cache_hb' : 'cache';
    let statuses = _.without(env.data.topics_visible_statuses, N.models.forum.Topic.statuses.PINNED);

    //
    // Fetch topic after last one, turn it into a link to the next page
    //
    if (env.data.topics.length > 0) {
      let last_post_id = env.data.topics[env.data.topics.length - 1][cache].last_post;

      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where(`${cache}.last_post`).lt(last_post_id)
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid -_id')
                                 .sort(`-${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.head.next = N.router.linkTo('forum.section', {
          section_hid: env.params.section_hid,
          topic_hid:   topic_data.hid
        }) + '?next';
      }
    }

    //
    // Fetch topic before first one, turn it into a link to the previous page;
    // (there is no previous page if the first topic is pinned)
    //
    if (env.data.topics.length > 0 &&
        env.data.topics[0].st !== N.models.forum.Topic.statuses.PINNED) {

      let last_post_id = env.data.topics[0][cache].last_post;

      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where(`${cache}.last_post`).gt(last_post_id)
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid')
                                 .sort(`${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.head.prev = N.router.linkTo('forum.section', {
          section_hid: env.params.section_hid,
          topic_hid:   topic_data.hid
        }) + '?prev';
      }
    }

    //
    // Fetch last topic for the "move to bottom" button
    //
    if (env.data.topics.length > 0) {
      let topic_data = yield N.models.forum.Topic.findOne()
                                 .where('section').equals(env.data.section._id)
                                 .where('st').in(statuses)
                                 .select('hid')
                                 .sort(`${cache}.last_post`)
                                 .lean(true);

      if (topic_data) {
        env.res.last_topic_hid = topic_data.hid;
      }
    }
  });
};
<|endoftext|>


<commit_before>var MIN_CONFIDENCE = 1;
VMX.config.useMagicCanvas = true;
VMX.storage.ledger = {}

VMX.callback = function(detections){
  if (! ( mc = VMX.getMagicCanvas() ) ){
    return; //canvas not open
  };
  var mcc = VMX.getMagicContext();
  if(!mcc) return;

  var modelName = detections[0].cls;

  for(var x in detections){
    if(detections[x].score > MIN_CONFIDENCE){
      VMX.storage.ledger[modelName] = parseInt(x,10) + 1;
    } else {
      break;
    }
  }

  console.log("the context", mcc);
  mcc.fillStyle = "blue";
  mcc.font = "bold 16px Arial";
  var coords = {x: 50, y:50};
  var output =[];
  for (var name in VMX.storage.ledger){
    line = name + ': ' + VMX.storage.ledger[name] + "\n";
    mcc.fillText(line,  coords.x, coords.y)
    coords.y += 50;
    output.push(line);
  }

  mcc.fillText(output, 100, 100)

  console.log(VMX.storage.ledger);
  console.log(coords,output);
}

<commit_msg>fast commit<commit_after>var MIN_CONFIDENCE = 1;
VMX.config.useMagicCanvas = true;
VMX.storage.ledger = {}

VMX.callback = function(detections){
  if (! ( mc = VMX.getMagicCanvas() ) ){
    return; //canvas not open
  };
  var mcc = VMX.getMagicContext();
  if(!mcc) return;

  var modelName = detections[0].cls;

  for(var x in detections){
    if(detections[x].score > MIN_CONFIDENCE){
      VMX.storage.ledger[modelName] = parseInt(x,10) + 1;
    } else {
      break;
    }
  }

  console.log("the context", mcc);
  mcc.fillStyle = "blue";
  mcc.font = "bold 16px Arial";
  var coords = {x: 50, y:50};
  var output =[];
  for (var name in VMX.storage.ledger){
    line = name + ': ' + VMX.storage.ledger[name] + "\n";
    mcc.fillText(line,  coords.x, coords.y)
    coords.y += 50;
    output.push(line);
  }

  mcc.fillText(output, 100, 100)
  mcc.restore();

  console.log(VMX.storage.ledger);
  console.log(coords,output);
}

<|endoftext|>


<commit_before>var expect = require('chai').expect;
var reverseMustacheUtils = require('./utils/reverse-mustache');

describe('A mustache template with a partial token', function () {
  describe('when reversed', function () {
    reverseMustacheUtils.save({
      template: 'hello {{> place}}',
      content: 'hello moon',
      partials: {
        place: 'moon'
      }
    });

    it.only('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.be.an('object');
    });
  });

  describe('when reversed in a loop', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#place}}{{> name}}{{/place}}',
      content: 'hello moon',
      partials: {
        place: '{{name}}'
      }
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.deep.equal({place: {name: 'moon'}});
    });
  });
});
<commit_msg>Added test for reversed with a variable<commit_after>var expect = require('chai').expect;
var reverseMustacheUtils = require('./utils/reverse-mustache');

describe('A mustache template with a partial token', function () {
  describe('when reversed', function () {
    reverseMustacheUtils.save({
      template: 'hello {{> place}}',
      content: 'hello moon',
      partials: {
        place: 'moon'
      }
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.be.an('object');
    });
  });

  describe('when reversed with a variable', function () {
    reverseMustacheUtils.save({
      template: 'hello {{> place}}',
      content: 'hello moon',
      partials: {
        place: '{{place}}'
      }
    });

    it.only('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.deep.equal({place: 'moon'});
    });
  });

  describe('when reversed in a loop and inner variable', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#place}}{{> name}}{{/place}}',
      content: 'hello moon',
      partials: {
        place: '{{name}}'
      }
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.deep.equal({place: {name: 'moon'}});
    });
  });
});
<|endoftext|>


<commit_before>module.exports = function() {
    'use strict';

    this.title = element(by.model('movie.title'));
    this.releaseYear = element(by.model('movie.releaseYear'));
    this.description = element(by.model('movie.description'));
    this.save = element(by.css('.btn-primary'));

    this.open = function() {
        browser.get('/movies/new');
    };

    this.addMovie = function(title, description, releaseYear) {
        this.open();
        this.title.clear();
        this.title.sendKeys(title);
        if (releaseYear !== undefined) {
            this.releaseYear.clear();
            this.releaseYear.sendKeys(releaseYear);
        }
        this.description.clear();
        this.description.sendKeys(description);
        this.save.click();
    };
};
<commit_msg>- fixed UI test<commit_after>module.exports = function() {
    'use strict';

    this.title = element(by.model('movie.title'));
    this.releaseYear = element(by.model('movie.releaseYear'));
    this.description = element(by.css('div[contenteditable=true]'));
    this.save = element(by.css('.btn-primary'));

    this.open = function() {
        browser.get('/movies/new');
    };

    this.addMovie = function(title, description, releaseYear) {
        this.open();
        this.title.clear();
        this.title.sendKeys(title);
        if (releaseYear !== undefined) {
            this.releaseYear.clear();
            this.releaseYear.sendKeys(releaseYear);
        }
        this.description.clear();
        this.description.sendKeys(description);
        this.save.click();
    };
};
<|endoftext|>


<commit_before>const yapi = require('../yapi.js');
const projectModel = require('../models/project.js');
const interfaceModel = require('../models/interface.js');
const mockExtra = require('../../common/mock-extra.js');
const _ = require('underscore');
const Mock = require('mockjs');

/**
 *
 * @param {*} apiPath /user/tom
 * @param {*} apiRule /user/:username
 */
function matchApi(apiPath, apiRule) {
    let apiRules = apiRule.split("/");
    let apiPaths = apiPath.split("/");
    if (apiPaths.length !== apiRules.length) {
        return false;
    }
    for (let i = 0; i < apiRules.length; i++) {
        if (apiRules[i] && apiRules[i].indexOf(":") !== 0) {
            if (apiRules[i] !== apiPaths[i]) {
                return false;
            }
        }
    }
    return true;
}

function handleCorsRequest(ctx) {
    let header = ctx.request.header;
    ctx.set('Access-Control-Allow-Origin', header.origin);
    ctx.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEADER, PATCH, OPTIONS");
    ctx.set('Access-Control-Allow-Headers', header['access-control-request-headers']);
    ctx.set('Access-Control-Allow-Credentials', true);
    ctx.set('Access-Control-Max-Age', 1728000);
    ctx.body = 'ok';

}

module.exports = async (ctx, next) => {
    // no used variable 'hostname' & 'config'
    // let hostname = ctx.hostname;
    // let config = yapi.WEBCONFIG;
    let path = ctx.path;

    if (path.indexOf('/mock/') !== 0) {
        if (next) await next();
        return true;
    }

    let paths = path.split("/");
    let projectId = paths[2];
    paths.splice(0, 3);
    path = "/" + paths.join("/");
    if (!projectId) {
        return ctx.body = yapi.commons.resReturn(null, 400, 'projectId不能为空');
    }

    yapi.commons.log('MockServer Running...');
    let projectInst = yapi.getInst(projectModel), project;
    try {
        project = await projectInst.get(projectId);
    } catch (e) {
        return ctx.body = yapi.commons.resReturn(null, 403, e.message);
    }

    if (!project) {
        return ctx.body = yapi.commons.resReturn(null, 400, '不存在的项目');
    }

    let interfaceData, newpath;
    let interfaceInst = yapi.getInst(interfaceModel);
    try {
        newpath = path.substr(project.basepath.length);
        interfaceData = await interfaceInst.getByPath(project._id, newpath, ctx.method);

        //处理query_path情况
        if (!interfaceData || interfaceData.length === 0) {
            interfaceData = await interfaceInst.getByQueryPath(project._id, newpath, ctx.method);

            let i, l, j, len, curQuery, match = false;
            for (i = 0, l = interfaceData.length; i < l; i++) {
                match = false;
                currentInterfaceData = interfaceData[i];
                curQuery = currentInterfaceData.query_path;
                if (!curQuery || typeof curQuery !== 'object' || !curQuery.path) {
                    continue;
                }
                for (j = 0, len = curQuery.params.length; j < len; j++) {
                    if (ctx.query[curQuery.params[j].name] !== curQuery.params[j].value) {
                        continue;
                    }
                    if (j === len - 1) {
                        match = true;
                    }
                }
                if (match) {
                    interfaceData = [currentInterfaceData];
                    break;
                }
                if (i === l - 1) {
                    interfaceData = [];
                }
            }
        }

        //处理动态路由
        if (!interfaceData || interfaceData.length === 0) {
            let newData = await interfaceInst.getVar(project._id, ctx.method);
            let findInterface = _.find(newData, (item) => {
                return matchApi(newpath, item.path)
            });

            if (!findInterface) {
                //非正常跨域预检请求回应
                if (ctx.method === 'OPTIONS' && ctx.request.header['access-control-request-method']) {
                    return handleCorsRequest(ctx);
                }
                return ctx.body = yapi.commons.resReturn(null, 404, `不存在的api, 当前请求path为 ${newpath}， 请求方法为 ${ctx.method} ，请确认是否定义此请求。`);
            }
            interfaceData = [
                await interfaceInst.get(findInterface._id)
            ]

        }

        if (interfaceData.length > 1) {
            return ctx.body = yapi.commons.resReturn(null, 405, '存在多个api，请检查数据库');
        } else {
            interfaceData = interfaceData[0];
        }

        ctx.set("Access-Control-Allow-Origin", "*")
        if (interfaceData.res_body_type === 'json') {
            try {
                let res = mockExtra(
                    yapi.commons.json_parse(interfaceData.res_body),
                    {
                        query: ctx.request.query,
                        body: ctx.request.body
                    }
                );

                try{
                    res = Mock.mock(res);
                }catch(e){
                    res = res;
                }

                let context = {
                    projectData: project,
                    interfaceData: interfaceData,
                    ctx: ctx,
                    mockJson: res,
                    resHeader: {},
                    httpCode: 200,
                    delay: 0
                }
                await yapi.emitHook('mock_after', context);
                let handleMock = new Promise(resolve=>{
                    setTimeout(()=>{
                      resolve(true)
                    }, context.delay)
                  })
                await handleMock;
                if(context.resHeader && typeof context.resHeader === 'object'){
                    for(let i in context.resHeader){
                        ctx.set(i, context.resHeader[i]);
                    }
                }

                ctx.status = context.httpCode;
                return ctx.body = context.mockJson;
            } catch (e) {
                yapi.commons.log(e, 'error')
                return ctx.body = {
                    errcode: 400,
                    errmsg: '解析出错，请检查。Error: ' + e.message,
                    data: null
                }
            }
        }
        return ctx.body = interfaceData.res_body;
    } catch (e) {
        console.error(e)
        return ctx.body = yapi.commons.resReturn(null, 409, e.message);
    }
};
<commit_msg>opti: add mockServer error log<commit_after>const yapi = require('../yapi.js');
const projectModel = require('../models/project.js');
const interfaceModel = require('../models/interface.js');
const mockExtra = require('../../common/mock-extra.js');
const _ = require('underscore');
const Mock = require('mockjs');

/**
 *
 * @param {*} apiPath /user/tom
 * @param {*} apiRule /user/:username
 */
function matchApi(apiPath, apiRule) {
    let apiRules = apiRule.split("/");
    let apiPaths = apiPath.split("/");
    if (apiPaths.length !== apiRules.length) {
        return false;
    }
    for (let i = 0; i < apiRules.length; i++) {
        if (apiRules[i] && apiRules[i].indexOf(":") !== 0) {
            if (apiRules[i] !== apiPaths[i]) {
                return false;
            }
        }
    }
    return true;
}

function handleCorsRequest(ctx) {
    let header = ctx.request.header;
    ctx.set('Access-Control-Allow-Origin', header.origin);
    ctx.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEADER, PATCH, OPTIONS");
    ctx.set('Access-Control-Allow-Headers', header['access-control-request-headers']);
    ctx.set('Access-Control-Allow-Credentials', true);
    ctx.set('Access-Control-Max-Age', 1728000);
    ctx.body = 'ok';

}

module.exports = async (ctx, next) => {
    // no used variable 'hostname' & 'config'
    // let hostname = ctx.hostname;
    // let config = yapi.WEBCONFIG;
    let path = ctx.path;

    if (path.indexOf('/mock/') !== 0) {
        if (next) await next();
        return true;
    }

    let paths = path.split("/");
    let projectId = paths[2];
    paths.splice(0, 3);
    path = "/" + paths.join("/");
    if (!projectId) {
        return ctx.body = yapi.commons.resReturn(null, 400, 'projectId不能为空');
    }

    yapi.commons.log('MockServer Running...');
    let projectInst = yapi.getInst(projectModel), project;
    try {
        project = await projectInst.get(projectId);
    } catch (e) {
        return ctx.body = yapi.commons.resReturn(null, 403, e.message);
    }

    if (!project) {
        return ctx.body = yapi.commons.resReturn(null, 400, '不存在的项目');
    }

    let interfaceData, newpath;
    let interfaceInst = yapi.getInst(interfaceModel);
    try {
        newpath = path.substr(project.basepath.length);
        interfaceData = await interfaceInst.getByPath(project._id, newpath, ctx.method);

        //处理query_path情况
        if (!interfaceData || interfaceData.length === 0) {
            interfaceData = await interfaceInst.getByQueryPath(project._id, newpath, ctx.method);

            let i, l, j, len, curQuery, match = false;
            for (i = 0, l = interfaceData.length; i < l; i++) {
                match = false;
                currentInterfaceData = interfaceData[i];
                curQuery = currentInterfaceData.query_path;
                if (!curQuery || typeof curQuery !== 'object' || !curQuery.path) {
                    continue;
                }
                for (j = 0, len = curQuery.params.length; j < len; j++) {
                    if (ctx.query[curQuery.params[j].name] !== curQuery.params[j].value) {
                        continue;
                    }
                    if (j === len - 1) {
                        match = true;
                    }
                }
                if (match) {
                    interfaceData = [currentInterfaceData];
                    break;
                }
                if (i === l - 1) {
                    interfaceData = [];
                }
            }
        }

        //处理动态路由
        if (!interfaceData || interfaceData.length === 0) {
            let newData = await interfaceInst.getVar(project._id, ctx.method);
            let findInterface = _.find(newData, (item) => {
                return matchApi(newpath, item.path)
            });

            if (!findInterface) {
                //非正常跨域预检请求回应
                if (ctx.method === 'OPTIONS' && ctx.request.header['access-control-request-method']) {
                    return handleCorsRequest(ctx);
                }
                return ctx.body = yapi.commons.resReturn(null, 404, `不存在的api, 当前请求path为 ${newpath}， 请求方法为 ${ctx.method} ，请确认是否定义此请求。`);
            }
            interfaceData = [
                await interfaceInst.get(findInterface._id)
            ]

        }

        if (interfaceData.length > 1) {
            return ctx.body = yapi.commons.resReturn(null, 405, '存在多个api，请检查数据库');
        } else {
            interfaceData = interfaceData[0];
        }

        ctx.set("Access-Control-Allow-Origin", "*")
        if (interfaceData.res_body_type === 'json') {
            try {
                let res = mockExtra(
                    yapi.commons.json_parse(interfaceData.res_body),
                    {
                        query: ctx.request.query,
                        body: ctx.request.body
                    }
                );

                try{
                    res = Mock.mock(res);
                }catch(e){
                    yapi.commons.log(e, 'error')
                    res = res;
                }

                let context = {
                    projectData: project,
                    interfaceData: interfaceData,
                    ctx: ctx,
                    mockJson: res,
                    resHeader: {},
                    httpCode: 200,
                    delay: 0
                }
                await yapi.emitHook('mock_after', context);
                let handleMock = new Promise(resolve=>{
                    setTimeout(()=>{
                      resolve(true)
                    }, context.delay)
                  })
                await handleMock;
                if(context.resHeader && typeof context.resHeader === 'object'){
                    for(let i in context.resHeader){
                        ctx.set(i, context.resHeader[i]);
                    }
                }

                ctx.status = context.httpCode;
                return ctx.body = context.mockJson;
            } catch (e) {
                yapi.commons.log(e, 'error')
                return ctx.body = {
                    errcode: 400,
                    errmsg: '解析出错，请检查。Error: ' + e.message,
                    data: null
                }
            }
        }
        return ctx.body = interfaceData.res_body;
    } catch (e) {
        console.error(e)
        return ctx.body = yapi.commons.resReturn(null, 409, e.message);
    }
};
<|endoftext|>


<commit_before>/**
 * Talisman clustering/k-means tests
 * ==================================
 *
 */
import {assert} from 'chai';
import kMeans, {KMeans} from '../../src/clustering/k-means';

describe('k-means', function() {

  it('should throw when given parameters are invalid.', function() {
    assert.throws(function() {
      kMeans({}, null);
    }, /vector/);

    assert.throws(function() {
      kMeans({k: -4}, [[1, 2]]);
    }, /`k`/);

    assert.throws(function() {
      kMeans({distance: 45, k: 1}, [[1, 2]]);
    }, /distance/);

    assert.throws(function() {
      kMeans({maxIterations: -45, k: 1}, [[1, 2]]);
    }, /max/);

    assert.throws(function() {
      kMeans({initialCentroids: 45, k: 1}, [[1, 2]]);
    }, /initialCentroids/);

    assert.throws(function() {
      kMeans({initialCentroids: [1], k: 1}, [[1, 2]]);
    }, /dimension/);

    assert.throws(function() {
      kMeans({initialCentroids: [[1, 2], [4]], k: 1}, [[1, 2]]);
    }, / k /);

    assert.throws(function() {
      kMeans({sampler: 'test', k: 1}, [[1, 2]]);
    }, /function/);

    assert.throws(function() {
      kMeans({k: 8}, [[1, 2], [2, 3]]);
    }, /greater/);
  });

  it('should be possible to apply clustering to simple vectors.', function() {
    const k1 = [[1, 2], [2, 1], [3, 1], [2, 4]],
          k2 = [[50, 45], [40, 55], [46, 52]],
          data = k1.concat(k2);

    const clusters = kMeans({k: 2}, data);

    assert.sameDeepMembers(clusters, [k1, k2]);
  });

  it('should be possible to pass initial centroids.', function() {
    const clustering = new KMeans([[1, 2], [3, 4]], {k: 2, initialCentroids: [[1, 2], [3, 4]]});

    assert.deepEqual(clustering.centroids, [[1, 2], [3, 4]]);
  });

  it('should be possible to compute initial centroids.', function() {
    const initialCentroids = (data, options) => {
      assert.deepEqual(data, [[1, 2], [3, 4]]);
      assert.strictEqual(options.k, 2);
      return [[1, 2], [3, 4]];
    };

    const clustering = new KMeans([[1, 2], [3, 4]], {k: 2, initialCentroids});

    assert.deepEqual(clustering.centroids, [[1, 2], [3, 4]]);
  });

  it('should work when k and dimension of the vectors is different (Issue #103).', function() {
    const k1 = [[1, 2, 3], [2, 1, 1], [3, 1, 4], [2, 4, 2]],
          k2 = [[50, 45, 45], [40, 55, 64], [46, 52, 62]],
          data = k1.concat(k2);

    const clusters = kMeans({k: 2}, data);

    assert.sameDeepMembers(clusters, [k1, k2]);
  });
});
<commit_msg>Fix #104 - using seeded RNG for k-means unit tests<commit_after>/**
 * Talisman clustering/k-means tests
 * ==================================
 *
 */
import {assert} from 'chai';
import kMeans, {KMeans} from '../../src/clustering/k-means';
import {createSample} from '../../src/helpers/random';
import seedrandom from 'seedrandom';

const createSampler = () => createSample(seedrandom('test'));

describe('k-means', function() {

  it('should throw when given parameters are invalid.', function() {
    assert.throws(function() {
      kMeans({}, null);
    }, /vector/);

    assert.throws(function() {
      kMeans({k: -4}, [[1, 2]]);
    }, /`k`/);

    assert.throws(function() {
      kMeans({distance: 45, k: 1}, [[1, 2]]);
    }, /distance/);

    assert.throws(function() {
      kMeans({maxIterations: -45, k: 1}, [[1, 2]]);
    }, /max/);

    assert.throws(function() {
      kMeans({initialCentroids: 45, k: 1}, [[1, 2]]);
    }, /initialCentroids/);

    assert.throws(function() {
      kMeans({initialCentroids: [1], k: 1}, [[1, 2]]);
    }, /dimension/);

    assert.throws(function() {
      kMeans({initialCentroids: [[1, 2], [4]], k: 1}, [[1, 2]]);
    }, / k /);

    assert.throws(function() {
      kMeans({sampler: 'test', k: 1}, [[1, 2]]);
    }, /function/);

    assert.throws(function() {
      kMeans({k: 8}, [[1, 2], [2, 3]]);
    }, /greater/);
  });

  it('should be possible to apply clustering to simple vectors.', function() {
    const k1 = [[1, 2], [2, 1], [3, 1], [2, 4]],
          k2 = [[50, 45], [40, 55], [46, 52]],
          data = k1.concat(k2);

    const clusters = kMeans({k: 2, sampler: createSampler()}, data);

    assert.deepEqual(clusters, [k2, k1]);
  });

  it('should be possible to pass initial centroids.', function() {
    const clustering = new KMeans([[1, 2], [3, 4]], {k: 2, initialCentroids: [[1, 2], [3, 4]]});

    assert.deepEqual(clustering.centroids, [[1, 2], [3, 4]]);
  });

  it('should be possible to compute initial centroids.', function() {
    const initialCentroids = (data, options) => {
      assert.deepEqual(data, [[1, 2], [3, 4]]);
      assert.strictEqual(options.k, 2);
      return [[1, 2], [3, 4]];
    };

    const clustering = new KMeans([[1, 2], [3, 4]], {k: 2, initialCentroids});

    assert.deepEqual(clustering.centroids, [[1, 2], [3, 4]]);
  });

  it('should work when k and dimension of the vectors is different (Issue #103).', function() {
    const k1 = [[1, 2, 3], [2, 1, 1], [3, 1, 4], [2, 4, 2]],
          k2 = [[50, 45, 45], [40, 55, 64], [46, 52, 62]],
          data = k1.concat(k2);

    const clusters = kMeans({k: 2, sampler: createSampler()}, data);

    assert.deepEqual(clusters, [k2, k1]);
  });
});
<|endoftext|>


<commit_before>define(["Tone/component/Envelope", "helper/Basic", "helper/Offline", "Test"],
function (Envelope, Basic, Offline, Test) {
	describe("Envelope", function(){

		Basic(Envelope);

		context("Envelope", function(){

			it("has an output connections", function(){
				var env = new Envelope();
				env.connect(Test);
				env.dispose();
			});

			it ("can get and set values an Objects", function(){
				var env = new Envelope();
				var values = {
					"attack" : 0,
					"decay" : 0.5,
					"sustain" : 1,
					"release" : "4n"
				};
				env.set(values);
				expect(env.get()).to.contain.keys(Object.keys(values));
				env.dispose();
			});

			it ("passes no signal before being triggered", function(done){
				var env;
				var offline = new Offline(0.1);
				offline.before(function(dest){
					env = new Envelope().connect(dest);
				});
				offline.test(function(sample){
					expect(sample).to.be.closeTo(0, 0.001);
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("passes signal once triggered", function(done){
				var env;
				var offline = new Offline(0.2);
				offline.before(function(dest){
					env = new Envelope().connect(dest);
					env.triggerAttack(0.1);
				});
				offline.test(function(sample, time){
					if (time <= 0.1){
						expect(sample).to.be.closeTo(0, 0.001);
					} else {
						expect(sample).to.be.above(0);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can take parameters as both an object and as arguments", function(){
				var env0 = new Envelope({
					"attack" : 0,
					"decay" : 0.5,
					"sustain" : 1
				});
				expect(env0.attack).to.equal(0);
				expect(env0.decay).to.equal(0.5);
				expect(env0.sustain).to.equal(1);
				env0.dispose();
				var env1 = new Envelope(0.1, 0.2, 0.3);
				expect(env1.attack).to.equal(0.1);
				expect(env1.decay).to.equal(0.2);
				expect(env1.sustain).to.equal(0.3);
				env1.dispose();
			});

			it("can set attack to exponential or linear", function(){
				var env = new Envelope(0.01, 0.01, 0.5, 0.3);
				env.attackCurve = "exponential";
				expect(env.attackCurve).to.equal("exponential");
				env.triggerAttack();
				env.dispose();
				//and can be linear
				var env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
				env2.attackCurve = "linear";
				expect(env2.attackCurve).to.equal("linear");
				env2.triggerAttack();
				//and test a non-curve
				expect(function(){
					env2.attackCurve = "other";
				}).to.throw(Error);
				env2.dispose();
			});

			it("can set release to exponential or linear", function(){
				var env = new Envelope(0.01, 0.01, 0.5, 0.3);
				env.releaseCurve = "exponential";
				expect(env.releaseCurve).to.equal("exponential");
				env.triggerRelease();
				env.dispose();
				//and can be linear
				var env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
				env2.releaseCurve = "linear";
				expect(env2.releaseCurve).to.equal("linear");
				env2.triggerRelease();
				//and test a non-curve
				expect(function(){
					env2.releaseCurve = "other";
				}).to.throw(Error);
				env2.dispose();
			});

			it ("correctly schedules an exponential attack", function(done){
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.01, 0.4, 0.5, 0.1);
					env.attackCurve = "exponential";
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else {
						expect(sample).to.be.closeTo(env.sustain, 0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedules an exponential attack", function(done){
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.3, 0.001, 0.5, 0.1);
					env.attackCurve = "exponential";
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else {
						expect(sample).to.be.closeTo(env.sustain, 0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a very short attack", function(done){
				var env;
				var offline = new Offline(0.2);
				offline.before(function(dest){
					env = new Envelope(0.001, 0.001, 0);
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(0, 1);
					} else {
						expect(sample).to.be.below(0.02);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedule a release", function(done){
				var releaseTime = 0.2;
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.001, 0.001, 0.5, 0.3);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerRelease(releaseTime);
				});
				offline.test(function(sample, time){
					if (time > env.attack + env.decay && time < env.attack + env.decay + releaseTime){
						expect(sample).to.be.below(env.sustain + 0.01);
					} else if (time > 0.5){
						//silent
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedule an attack release envelope", function(done){
				var env;
				var releaseTime = 0.4;
				var offline = new Offline(0.8);
				offline.before(function(dest){
					env = new Envelope(0.08, 0.2, 0.1, 0.2);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerRelease(releaseTime);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else if (time < releaseTime){
						expect(sample).to.be.closeTo(env.sustain, 0.1);
					} else if (time < releaseTime + env.release){
						expect(sample).to.be.within(0, env.sustain + 0.01);
					} else {
						//silent
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a combined AttackRelease", function(done){
				var env;
				var duration = 0.4;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0.35, 0.1);
					env.connect(dest);
					env.triggerAttackRelease(duration, 0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain - 0.001, 1);
					} else if (time < duration){
						expect(sample).to.be.closeTo(env.sustain, 0.1);
					} else if (time < duration + env.release){
						expect(sample).to.be.within(0, env.sustain + 0.01);
					} else {
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a combined AttackRelease with velocity", function(done){
				var env;
				var duration = 0.4;
				var velocity = 0.4;
				var offline = new Offline(0.8);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0.35, 0.1);
					env.connect(dest);
					env.triggerAttackRelease(duration, 0, velocity);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, velocity + 0.01);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain * velocity, velocity + 0.01);
					} else if (time < duration){
						expect(sample).to.be.closeTo(env.sustain * velocity, 0.1);
					} else if (time < duration + env.release){
						expect(sample).to.be.within(0, env.sustain * velocity + 0.01);
					} else {
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule multiple envelopes", function(done){
				var env;
				var offline = new Offline(1);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerAttack(0.5);
				});
				offline.test(function(sample, time){
					if (time > 0 && time < 0.3){
						expect(sample).to.be.above(0);
					} else if (time <= 0.5){
						expect(sample).to.be.below(0.02);
					} else if (time <= 0.8){
						expect(sample).to.be.above(0);
					} else {
						expect(sample).to.be.below(0.02);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("reports its current envelope value (.value)", function(done){
				var env = new Envelope(0.1, 0.2, 1).noGC();
				expect(env.value).to.be.closeTo(0, 0.01);
				env.triggerAttack();
				setTimeout(function(){
					expect(env.value).to.be.closeTo(1, 0.01);
					env.dispose();
					done();
				}, 200);
			});
		});
	});
});<commit_msg>increasing tolerance for test<commit_after>define(["Tone/component/Envelope", "helper/Basic", "helper/Offline", "Test"],
function (Envelope, Basic, Offline, Test) {
	describe("Envelope", function(){

		Basic(Envelope);

		context("Envelope", function(){

			it("has an output connections", function(){
				var env = new Envelope();
				env.connect(Test);
				env.dispose();
			});

			it ("can get and set values an Objects", function(){
				var env = new Envelope();
				var values = {
					"attack" : 0,
					"decay" : 0.5,
					"sustain" : 1,
					"release" : "4n"
				};
				env.set(values);
				expect(env.get()).to.contain.keys(Object.keys(values));
				env.dispose();
			});

			it ("passes no signal before being triggered", function(done){
				var env;
				var offline = new Offline(0.1);
				offline.before(function(dest){
					env = new Envelope().connect(dest);
				});
				offline.test(function(sample){
					expect(sample).to.be.closeTo(0, 0.001);
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("passes signal once triggered", function(done){
				var env;
				var offline = new Offline(0.2);
				offline.before(function(dest){
					env = new Envelope().connect(dest);
					env.triggerAttack(0.1);
				});
				offline.test(function(sample, time){
					if (time <= 0.1){
						expect(sample).to.be.closeTo(0, 0.001);
					} else {
						expect(sample).to.be.above(0);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can take parameters as both an object and as arguments", function(){
				var env0 = new Envelope({
					"attack" : 0,
					"decay" : 0.5,
					"sustain" : 1
				});
				expect(env0.attack).to.equal(0);
				expect(env0.decay).to.equal(0.5);
				expect(env0.sustain).to.equal(1);
				env0.dispose();
				var env1 = new Envelope(0.1, 0.2, 0.3);
				expect(env1.attack).to.equal(0.1);
				expect(env1.decay).to.equal(0.2);
				expect(env1.sustain).to.equal(0.3);
				env1.dispose();
			});

			it("can set attack to exponential or linear", function(){
				var env = new Envelope(0.01, 0.01, 0.5, 0.3);
				env.attackCurve = "exponential";
				expect(env.attackCurve).to.equal("exponential");
				env.triggerAttack();
				env.dispose();
				//and can be linear
				var env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
				env2.attackCurve = "linear";
				expect(env2.attackCurve).to.equal("linear");
				env2.triggerAttack();
				//and test a non-curve
				expect(function(){
					env2.attackCurve = "other";
				}).to.throw(Error);
				env2.dispose();
			});

			it("can set release to exponential or linear", function(){
				var env = new Envelope(0.01, 0.01, 0.5, 0.3);
				env.releaseCurve = "exponential";
				expect(env.releaseCurve).to.equal("exponential");
				env.triggerRelease();
				env.dispose();
				//and can be linear
				var env2 = new Envelope(0.01, 0.01, 0.5, 0.3);
				env2.releaseCurve = "linear";
				expect(env2.releaseCurve).to.equal("linear");
				env2.triggerRelease();
				//and test a non-curve
				expect(function(){
					env2.releaseCurve = "other";
				}).to.throw(Error);
				env2.dispose();
			});

			it ("correctly schedules an exponential attack", function(done){
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.01, 0.4, 0.5, 0.1);
					env.attackCurve = "exponential";
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else {
						expect(sample).to.be.closeTo(env.sustain, 0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedules an exponential attack", function(done){
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.3, 0.001, 0.5, 0.1);
					env.attackCurve = "exponential";
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else {
						expect(sample).to.be.closeTo(env.sustain, 0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a very short attack", function(done){
				var env;
				var offline = new Offline(0.2);
				offline.before(function(dest){
					env = new Envelope(0.001, 0.001, 0);
					env.connect(dest);
					env.triggerAttack(0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(0, 1);
					} else {
						expect(sample).to.be.below(0.02);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedule a release", function(done){
				var releaseTime = 0.2;
				var env;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.001, 0.001, 0.5, 0.3);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerRelease(releaseTime);
				});
				offline.test(function(sample, time){
					if (time > env.attack + env.decay && time < env.attack + env.decay + releaseTime){
						expect(sample).to.be.below(env.sustain + 0.01);
					} else if (time > 0.5){
						//silent
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("correctly schedule an attack release envelope", function(done){
				var env;
				var releaseTime = 0.4;
				var offline = new Offline(0.8);
				offline.before(function(dest){
					env = new Envelope(0.08, 0.2, 0.1, 0.2);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerRelease(releaseTime);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain, 1);
					} else if (time < releaseTime){
						expect(sample).to.be.closeTo(env.sustain, 0.1);
					} else if (time < releaseTime + env.release){
						expect(sample).to.be.within(0, env.sustain + 0.01);
					} else {
						//silent
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a combined AttackRelease", function(done){
				var env;
				var duration = 0.4;
				var offline = new Offline(0.7);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0.35, 0.1);
					env.connect(dest);
					env.triggerAttackRelease(duration, 0);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, 1);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain - 0.001, 1);
					} else if (time < duration){
						expect(sample).to.be.closeTo(env.sustain, 0.1);
					} else if (time < duration + env.release){
						expect(sample).to.be.within(0, env.sustain + 0.01);
					} else {
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule a combined AttackRelease with velocity", function(done){
				var env;
				var duration = 0.4;
				var velocity = 0.4;
				var offline = new Offline(0.8);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0.35, 0.1);
					env.connect(dest);
					env.triggerAttackRelease(duration, 0, velocity);
				});
				offline.test(function(sample, time){
					if (time < env.attack){
						expect(sample).to.be.within(0, velocity + 0.01);
					} else if (time < env.attack + env.decay){
						expect(sample).to.be.within(env.sustain * velocity - 0.01, velocity + 0.01);
					} else if (time < duration){
						expect(sample).to.be.closeTo(env.sustain * velocity, 0.1);
					} else if (time < duration + env.release){
						expect(sample).to.be.within(0, env.sustain * velocity + 0.01);
					} else {
						expect(sample).to.be.below(0.01);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("can schedule multiple envelopes", function(done){
				var env;
				var offline = new Offline(1);
				offline.before(function(dest){
					env = new Envelope(0.1, 0.2, 0);
					env.connect(dest);
					env.triggerAttack(0);
					env.triggerAttack(0.5);
				});
				offline.test(function(sample, time){
					if (time > 0 && time < 0.3){
						expect(sample).to.be.above(0);
					} else if (time <= 0.5){
						expect(sample).to.be.below(0.02);
					} else if (time <= 0.8){
						expect(sample).to.be.above(0);
					} else {
						expect(sample).to.be.below(0.02);
					}
				});
				offline.after(function(){
					env.dispose();
					done();
				});
				offline.run();
			});

			it ("reports its current envelope value (.value)", function(done){
				var env = new Envelope(0.1, 0.2, 1).noGC();
				expect(env.value).to.be.closeTo(0, 0.01);
				env.triggerAttack();
				setTimeout(function(){
					expect(env.value).to.be.closeTo(1, 0.01);
					env.dispose();
					done();
				}, 200);
			});
		});
	});
});<|endoftext|>


<commit_before>const express = require('express');
const querystring = require('querystring');
const _ = require('lodash');
const oauthClient = require('../../helpers/oauth');
const Util = require('../../helpers/jakduk_util');

function oauth2(providers) {
  const router = express.Router();

  _.forEach(providers, provider => {
    router.get(`/${provider}`, login.bind(null, provider));
    router.get(`/${provider}/callback`, callback.bind(null, provider));
  });

  return router;
}

function login(provider, req, res) {
  res.redirect(`${oauthClient[provider].getLoginUrl()}&state=${querystring.escape(`redir=${(req.query.redir || '')}`)}`);
}

function callback(provider, req, res) {
  oauthClient[provider].authorize(req.query.code).then(response => {
    if (response.statusCode === 200) {
      return Promise.all([
        response.data.access_token,
        req.api.loginWith(provider, response.data.access_token)
      ]);
    }
  }).then(responses => {
    const extra = querystring.parse(req.query.state);
    const status = responses[1].statusCode;
    const accessToken = responses[0];
    const loginResponse = responses[1];

    if (status === 200) {
      Util.saveSession(res, loginResponse);
      res.redirect(extra.redir || '/');
    } else if (status === 404) {
      Util.saveSession(res, loginResponse, true);
      Util.redirect(res, {
        target: '/join/oauth',
        query: {
          redir: extra.redir,
          provider: provider,
          accessToken: accessToken
        }
      });
    } else {
      return Promise.reject(loginResponse);
    }
  }).catch(() => {
    res.redirect('/login');
  });
}

module.exports.setup = function (app) {
  app.use('/auth', oauth2([
    'daum',
    'facebook'
  ]));
};
<commit_msg>3rd party 연동 로그인 로그 추가<commit_after>const express = require('express');
const querystring = require('querystring');
const _ = require('lodash');
const oauthClient = require('../../helpers/oauth');
const Util = require('../../helpers/jakduk_util');
const debug = require('debug')('jakduk-web:auth_3rd');

function oauth2(providers) {
  const router = express.Router();

  _.forEach(providers, provider => {
    router.get(`/${provider}`, login.bind(null, provider));
    router.get(`/${provider}/callback`, callback.bind(null, provider));
  });

  return router;
}

function login(provider, req, res) {
  res.redirect(`${oauthClient[provider].getLoginUrl()}&state=${querystring.escape(`redir=${(req.query.redir || '')}`)}`);
}

function callback(provider, req, res) {
  oauthClient[provider].authorize(req.query.code).then(response => {
    if (response.statusCode === 200) {
      debug(`[Login with ${provider}] %o`, response.data);
      return Promise.all([
        response.data.access_token,
        req.api.loginWith(provider, response.data.access_token)
      ]);
    }
  }).then(responses => {
    const extra = querystring.parse(req.query.state);
    const status = responses[1].statusCode;
    const accessToken = responses[0];
    const loginResponse = responses[1];

    if (status === 200) {
      Util.saveSession(res, loginResponse);
      res.redirect(extra.redir || '/');
    } else if (status === 404) {
      Util.saveSession(res, loginResponse, true);
      Util.redirect(res, {
        target: '/join/oauth',
        query: {
          redir: extra.redir,
          provider: provider,
          accessToken: accessToken
        }
      });
    } else {
      return Promise.reject(loginResponse);
    }
  }).catch(() => {
    res.redirect('/login');
  });
}

module.exports.setup = function (app) {
  app.use('/auth', oauth2([
    'daum',
    'facebook'
  ]));
};
<|endoftext|>