<commit_before>'use strict';
var assert = require('assert');
var escapeRegex = require('escape-string-regexp');
var path = require('path');
var slash = require('slash');
var sourceMapUrl = require('source-map-url');

function HtmlWebpackInlineSourcePlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackInlineSourcePlugin does not accept any options');
}

HtmlWebpackInlineSourcePlugin.prototype.apply = function (compiler) {
  var self = this;

  // Hook into the html-webpack-plugin processing

  (compiler.hooks
    ? compiler.hooks.compilation.tap.bind(compiler.hooks.compilation, 'html-webpack-inline-source-plugin')
    : compiler.plugin.bind(compiler, 'compilation'))(function (compilation) {
      (compilation.hooks
      ? compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync.bind(compilation.hooks.htmlWebpackPluginAlterAssetTags, 'html-webpack-inline-source-plugin')
      : compilation.plugin.bind(compilation, 'html-webpack-plugin-alter-asset-tags'))(function (htmlPluginData, callback) {
        if (!htmlPluginData.plugin.options.inlineSource) {
          return callback(null, htmlPluginData);
        }

        var regexStr = htmlPluginData.plugin.options.inlineSource;

        var result = self.processTags(compilation, regexStr, htmlPluginData);

        callback(null, result);
      });
    });
};

HtmlWebpackInlineSourcePlugin.prototype.processTags = function (compilation, regexStr, pluginData) {
  var self = this;

  var body = [];
  var head = [];

  var regex = new RegExp(regexStr);

  pluginData.head.forEach(function (tag) {
    head.push(self.processTag(compilation, regex, tag));
  });

  pluginData.body.forEach(function (tag) {
    body.push(self.processTag(compilation, regex, tag));
  });

  return { head: head, body: body, plugin: pluginData.plugin, chunks: pluginData.chunks, outputName: pluginData.outputName };
};

HtmlWebpackInlineSourcePlugin.prototype.resolveSourceMaps = function (compilation, assetName, asset) {
  var source = asset.source();
  var out = compilation.outputOptions;
  // Get asset file absolute path
  var assetPath = path.join(out.path, assetName);
  // Extract original sourcemap URL from source string
  if (typeof source !== 'string') {
    source = source.toString();
  }
  var mapUrlOriginal = sourceMapUrl.getFrom(source);
  // Return unmodified source if map is unspecified, URL-encoded, or already relative to site root
  if (!mapUrlOriginal || mapUrlOriginal.indexOf('data:') === 0 || mapUrlOriginal.indexOf('/') === 0) {
    return source;
  }
  // Figure out sourcemap file path *relative to the asset file path*
  var assetDir = path.dirname(assetPath);
  var mapPath = path.join(assetDir, mapUrlOriginal);
  var mapPathRelative = path.relative(out.path, mapPath);
  // Starting with Node 6, `path` module throws on `undefined`
  var publicPath = out.publicPath || '';
  // Prepend Webpack public URL path to source map relative path
  // Calling `slash` converts Windows backslashes to forward slashes
  var mapUrlCorrected = slash(path.join(publicPath, mapPathRelative));
  // Regex: exact original sourcemap URL, possibly '*/' (for CSS), then EOF, ignoring whitespace
  var regex = new RegExp(escapeRegex(mapUrlOriginal) + '(\\s*(?:\\*/)?\\s*$)');
  // Replace sourcemap URL and (if necessary) preserve closing '*/' and whitespace
  return source.replace(regex, function (match, group) {
    return mapUrlCorrected + group;
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTag = function (compilation, regex, tag) {
  var assetUrl;

  // inline js
  if (tag.tagName === 'script' && regex.test(tag.attributes.src)) {
    assetUrl = tag.attributes.src;
    tag = {
      tagName: 'script',
      closeTag: true,
      attributes: {
        type: 'text/javascript'
      }
    };

  // inline css
  } else if (tag.tagName === 'link' && regex.test(tag.attributes.href)) {
    assetUrl = tag.attributes.href;
    tag = {
      tagName: 'style',
      closeTag: true,
      attributes: {
        type: 'text/css'
      }
    };
  }

  if (assetUrl) {
    // Strip public URL prefix from asset URL to get Webpack asset name
    var publicUrlPrefix = compilation.outputOptions.publicPath || '';
    var assetName = path.posix.relative(publicUrlPrefix, assetUrl);
    var asset = compilation.assets[assetName];
    var updatedSource = this.resolveSourceMaps(compilation, assetName, asset);
    tag.innerHTML = (tag.tagName === 'script') ? updatedSource.replace(/(<)(\/script>)/g, '\\x3C$2') : updatedSource;
  }

  return tag;
};

module.exports = HtmlWebpackInlineSourcePlugin;
<commit_msg>fix error occured in filename in subfolder<commit_after>'use strict';
var assert = require('assert');
var escapeRegex = require('escape-string-regexp');
var path = require('path');
var slash = require('slash');
var sourceMapUrl = require('source-map-url');

function HtmlWebpackInlineSourcePlugin (options) {
  assert.equal(options, undefined, 'The HtmlWebpackInlineSourcePlugin does not accept any options');
}

HtmlWebpackInlineSourcePlugin.prototype.apply = function (compiler) {
  var self = this;

  // Hook into the html-webpack-plugin processing

  (compiler.hooks
    ? compiler.hooks.compilation.tap.bind(compiler.hooks.compilation, 'html-webpack-inline-source-plugin')
    : compiler.plugin.bind(compiler, 'compilation'))(function (compilation) {
      (compilation.hooks
      ? compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync.bind(compilation.hooks.htmlWebpackPluginAlterAssetTags, 'html-webpack-inline-source-plugin')
      : compilation.plugin.bind(compilation, 'html-webpack-plugin-alter-asset-tags'))(function (htmlPluginData, callback) {
        if (!htmlPluginData.plugin.options.inlineSource) {
          return callback(null, htmlPluginData);
        }

        var regexStr = htmlPluginData.plugin.options.inlineSource;

        var result = self.processTags(compilation, regexStr, htmlPluginData);

        callback(null, result);
      });
    });
};

HtmlWebpackInlineSourcePlugin.prototype.processTags = function (compilation, regexStr, pluginData) {
  var self = this;

  var body = [];
  var head = [];

  var regex = new RegExp(regexStr);
  var filename = pluginData.plugin.options.filename;

  pluginData.head.forEach(function (tag) {
    head.push(self.processTag(compilation, regex, tag, filename));
  });

  pluginData.body.forEach(function (tag) {
    body.push(self.processTag(compilation, regex, tag, filename));
  });

  return { head: head, body: body, plugin: pluginData.plugin, chunks: pluginData.chunks, outputName: pluginData.outputName };
};

HtmlWebpackInlineSourcePlugin.prototype.resolveSourceMaps = function (compilation, assetName, asset) {
  var source = asset.source();
  var out = compilation.outputOptions;
  // Get asset file absolute path
  var assetPath = path.join(out.path, assetName);
  // Extract original sourcemap URL from source string
  if (typeof source !== 'string') {
    source = source.toString();
  }
  var mapUrlOriginal = sourceMapUrl.getFrom(source);
  // Return unmodified source if map is unspecified, URL-encoded, or already relative to site root
  if (!mapUrlOriginal || mapUrlOriginal.indexOf('data:') === 0 || mapUrlOriginal.indexOf('/') === 0) {
    return source;
  }
  // Figure out sourcemap file path *relative to the asset file path*
  var assetDir = path.dirname(assetPath);
  var mapPath = path.join(assetDir, mapUrlOriginal);
  var mapPathRelative = path.relative(out.path, mapPath);
  // Starting with Node 6, `path` module throws on `undefined`
  var publicPath = out.publicPath || '';
  // Prepend Webpack public URL path to source map relative path
  // Calling `slash` converts Windows backslashes to forward slashes
  var mapUrlCorrected = slash(path.join(publicPath, mapPathRelative));
  // Regex: exact original sourcemap URL, possibly '*/' (for CSS), then EOF, ignoring whitespace
  var regex = new RegExp(escapeRegex(mapUrlOriginal) + '(\\s*(?:\\*/)?\\s*$)');
  // Replace sourcemap URL and (if necessary) preserve closing '*/' and whitespace
  return source.replace(regex, function (match, group) {
    return mapUrlCorrected + group;
  });
};

HtmlWebpackInlineSourcePlugin.prototype.processTag = function (compilation, regex, tag, filename) {
  var assetUrl;

  // inline js
  if (tag.tagName === 'script' && regex.test(tag.attributes.src)) {
    assetUrl = tag.attributes.src;
    tag = {
      tagName: 'script',
      closeTag: true,
      attributes: {
        type: 'text/javascript'
      }
    };

  // inline css
  } else if (tag.tagName === 'link' && regex.test(tag.attributes.href)) {
    assetUrl = tag.attributes.href;
    tag = {
      tagName: 'style',
      closeTag: true,
      attributes: {
        type: 'text/css'
      }
    };
  }

  if (assetUrl) {
    // Strip public URL prefix from asset URL to get Webpack asset name
    var publicUrlPrefix = compilation.outputOptions.publicPath || '';
    // if filename is in subfolder, assetUrl should be prepended folder path
    if (path.basename(filename) !== filename) {
      assetUrl = path.dirname(filename) + '/' + assetUrl;
    }
    var assetName = path.posix.relative(publicUrlPrefix, assetUrl);
    var asset = compilation.assets[assetName];
    var updatedSource = this.resolveSourceMaps(compilation, assetName, asset);
    tag.innerHTML = (tag.tagName === 'script') ? updatedSource.replace(/(<)(\/script>)/g, '\\x3C$2') : updatedSource;
  }

  return tag;
};

module.exports = HtmlWebpackInlineSourcePlugin;
<|endoftext|>


<commit_before>angular.module('codebrag.counters').factory('countersService', function($http, $timeout, $rootScope, Counter, branchesService, events) {

    var pollingInterval = 10000,
        syncTimer,
        commitsCounter = new Counter(),
        followupsCounter = new Counter();

    function fetchCounters(branch) {
        return $http.get('rest/updates', {params: {branch: branch}}).then(function(resp) {
            return {
                commits: resp.data.commits,
                followups: resp.data.followups
            }
        });
    }

    function initPolling(which, branch) {
        var currentBranch = branch || branchesService.selectedBranch();
        fetchCounters(currentBranch)
            .then(reInitializeCounters(which), angular.noop)
            .then(scheduleNextSync);

        function scheduleNextSync() {
            syncTimer && $timeout.cancel(syncTimer);
            syncTimer = $timeout(function() {
                fetchCounters(currentBranch)
                    .then(updateIncomingCounters)
                    .then(scheduleNextSync)
            }, pollingInterval);
        }
    }

    function reInitializeCounters(which) {
        return function(initialCounters) {
            if(angular.isUndefined(which) || which.commits) {
                commitsCounter.reInitialize(initialCounters.commits);
            }
            if(angular.isUndefined(which) || which.followups) {
                followupsCounter.reInitialize(initialCounters.followups);
            }
        }
    }

    function updateIncomingCounters(incomingCounters) {
        commitsCounter.setIncomingTo(incomingCounters.commits);
        followupsCounter.setIncomingTo(incomingCounters.followups);
    }

    function bindEventListeners() {
        $rootScope.$on(events.branches.branchChanged, function(e, branch) {
            initPolling({commits: true}, branch);
        });
        $rootScope.$on(events.commitsListFilterChanged, function() {
            initPolling({commits: true});
        });
        $rootScope.$on(events.commitReviewed, function() {
            commitsCounter.decrease();
        });
        $rootScope.$on(events.followupDone, function() {
            followupsCounter.decrease();
        });
        $rootScope.$on(events.nextCommitsLoaded, function() {
            commitsCounter.replace();
        });
        $rootScope.$on(events.previousCommitsLoaded, function() {
            commitsCounter.replace();
        });
    }

    branchesService.ready().then(function() {
        initPolling();
        bindEventListeners();
    });

    return {
        commitsCounter: commitsCounter,
        followupsCounter: followupsCounter,
        reloadCounters: initPolling
    }

});<commit_msg>UI polls for counter changes every 60 secs now<commit_after>angular.module('codebrag.counters').factory('countersService', function($http, $timeout, $rootScope, Counter, branchesService, events) {

    var pollingInterval = 60000,
        syncTimer,
        commitsCounter = new Counter(),
        followupsCounter = new Counter();

    function fetchCounters(branch) {
        return $http.get('rest/updates', {params: {branch: branch}}).then(function(resp) {
            return {
                commits: resp.data.commits,
                followups: resp.data.followups
            }
        });
    }

    function initPolling(which, branch) {
        var currentBranch = branch || branchesService.selectedBranch();
        fetchCounters(currentBranch)
            .then(reInitializeCounters(which), angular.noop)
            .then(scheduleNextSync);

        function scheduleNextSync() {
            syncTimer && $timeout.cancel(syncTimer);
            syncTimer = $timeout(function() {
                fetchCounters(currentBranch)
                    .then(updateIncomingCounters)
                    .then(scheduleNextSync)
            }, pollingInterval);
        }
    }

    function reInitializeCounters(which) {
        return function(initialCounters) {
            if(angular.isUndefined(which) || which.commits) {
                commitsCounter.reInitialize(initialCounters.commits);
            }
            if(angular.isUndefined(which) || which.followups) {
                followupsCounter.reInitialize(initialCounters.followups);
            }
        }
    }

    function updateIncomingCounters(incomingCounters) {
        commitsCounter.setIncomingTo(incomingCounters.commits);
        followupsCounter.setIncomingTo(incomingCounters.followups);
    }

    function bindEventListeners() {
        $rootScope.$on(events.branches.branchChanged, function(e, branch) {
            initPolling({commits: true}, branch);
        });
        $rootScope.$on(events.commitsListFilterChanged, function() {
            initPolling({commits: true});
        });
        $rootScope.$on(events.commitReviewed, function() {
            commitsCounter.decrease();
        });
        $rootScope.$on(events.followupDone, function() {
            followupsCounter.decrease();
        });
        $rootScope.$on(events.nextCommitsLoaded, function() {
            commitsCounter.replace();
        });
        $rootScope.$on(events.previousCommitsLoaded, function() {
            commitsCounter.replace();
        });
    }

    branchesService.ready().then(function() {
        initPolling();
        bindEventListeners();
    });

    return {
        commitsCounter: commitsCounter,
        followupsCounter: followupsCounter,
        reloadCounters: initPolling
    }

});<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var Generic = require('butter-provider');
var inherits = require('util').inherits;
var Q = require('q');
var querystring = require('querystring');
var request = require('request');
var sanitize = require('butter-sanitize');

var MovieApi = function(args) {
	if (!(this instanceof MovieApi)) return new MovieApi(args);

	Generic.call(this, args);

	this.apiURL = this.args.apiURL || ['https://movies-v2.api-fetch.website/'];
  this.lang = this.args.lang || 'en';
  this.quality = this.args.quality || '720p';
};

inherits(MovieApi, Generic);

MovieApi.prototype.config = {
	name: 'MovieApi',
	uniqueId: 'imdb_id',
	tabName: 'MovieApi',
	type: Generic.TabType.MOVIE,
  args: {
    apiURL: Generic.ArgType.ARRAY,
    lang: Generic.ArgType.STRING,
    quality: Generic.ArgType.STRING
	},
	metadata: 'trakttv:movie-metadata'
};

MovieApi.prototype.extractIds = function(items) {
	return _.map(items.results, 'imdb_id');
};

function formatFetch(movies) {
	var results = [];

	movies.forEach(function(movie) {
		if (movie.torrents) {
			results.push({
				type: 'movie',
				imdb_id: movie.imdb_id,
				title: movie.title,
				year: movie.year,
				genre: movie.genres,
				rating: parseInt(movie.rating.percentage, 10) / 10,
				runtime: movie.runtime,
        images: movie.images,
				image: movie.images.poster,
				cover: movie.images.poster,
				backdrop: movie.images.fanart,
        poster: movie.images.poster,
				synopsis: movie.synopsis,
				trailer: movie.trailer !== null ? movie.trailer : false,
				certification: movie.certification,
				torrents: movie.torrents['en'] !== null ? movie.torrents['en'] : movie.torrents[Object.keys(movie.torrents)[0]],
				langs: movie.torrents
			});
		}
	});

	return {
		results: sanitize(results),
		hasMore: true
	};
}

function formatDetail(movie) {
  return {
    type: 'movie',
    imdb_id: movie.imdb_id,
    title: movie.title,
    year: movie.year,
    genre: movie.genres,
    rating: parseInt(movie.rating.percentage, 10) / 10,
    runtime: movie.runtime,
    images: movie.images,
    image: movie.images.poster,
    cover: movie.images.poster,
    backdrop: movie.images.fanart,
    poster: movie.images.poster,
    synopsis: movie.synopsis,
    trailer: movie.trailer !== null ? movie.trailer : false,
    certification: movie.certification,
    torrents: movie.torrents['en'] !== null ? movie.torrents['en'] : movie.torrents[Object.keys(movie.torrents)[0]],
    langs: movie.torrents
  };
}

function processCloudFlareHack(options, url) {
	var req = options;
	var match = url.match(/^cloudflare\+(.*):\/\/(.*)/);
	if (match) {
		req = _.extend(req, {
			uri: match[1] + '://cloudflare.com/',
			headers: {
				'Host': match[2],
				'User-Agent': 'Mozilla/5.0 (Linux) AppleWebkit/534.30 (KHTML, like Gecko) PT/3.8.0'
			}
		});
	}
	return req;
}

function get(index, url, that) {
	var deferred = Q.defer();

	var options = {
		url: url,
		json: true
	};

	var req = processCloudFlareHack(options, that.apiURL[index]);
	console.info('Request to MovieApi', req.url);
	request(req, function(err, res, data) {
		if (err || res.statusCode >= 400) {
			console.warn('MovieAPI endpoint \'%s\' failed.', that.apiURL[index]);
			if (index + 1 >= that.apiURL.length) {
				return deferred.reject(err || 'Status Code is above 400');
			} else {
				return get(index + 1, url, that);
			}
		} else if (!data || data.error) {
			err = data ? data.status_message : 'No data returned';
			console.error('API error:', err);
			return deferred.reject(err);
		} else {
			return deferred.resolve(data);
		}
	});

	return deferred.promise;
}

MovieApi.prototype.resolveStream = function (src, filters, data) {
  filters.lang = filters.lang ? filters.lang : this.lang;
  filters.quality = filters.quality ? filters.quality : this.quality;

	return data.langs[filters.lang][filters.quality];
};

MovieApi.prototype.fetch = function (filters) {
	var that = this;

	var params = {};
	params.sort = 'seeds';
	params.limit = '50';

	if (filters.keywords) {
		params.keywords = filters.keywords.replace(/\s/g, '% ');
	}

	if (filters.genre) {
		params.genre = filters.genre;
	}

	if (filters.order) {
		params.order = filters.order;
	}

	if (filters.sorter && filters.sorter !== 'popularity') {
		params.sort = filters.sorter;
	}

  filters.page = filters.page ? filters.page : 1;

	var index = 0;
	var url = that.apiURL[index] + 'movies/' + filters.page + '?' + querystring.stringify(params).replace(/%25%20/g, '%20');
	return get(index, url, that).then(formatFetch);
};

MovieApi.prototype.random = function () {
	var that = this;
	var index = 0;
	var url = that.apiURL[index] + 'random/movie';
	return get(index, url, that).then(formatDetail);
};

MovieApi.prototype.detail = function (torrent_id, old_data, debug) {
  if (old_data) {
    return Q(old_data);
  }

  var that = this;
	var index = 0;
	var url = that.apiURL[index] + 'movie' + torrent_id;
	return get(index, url, that).then(formatDetail);
};

module.exports = MovieApi;
<commit_msg>added subtitle field to format functions<commit_after>'use strict';

var _ = require('lodash');
var Generic = require('butter-provider');
var inherits = require('util').inherits;
var Q = require('q');
var querystring = require('querystring');
var request = require('request');
var sanitize = require('butter-sanitize');

var MovieApi = function(args) {
	if (!(this instanceof MovieApi)) return new MovieApi(args);

	Generic.call(this, args);

	this.apiURL = this.args.apiURL || ['https://movies-v2.api-fetch.website/'];
  this.lang = this.args.lang || 'en';
  this.quality = this.args.quality || '720p';
};

inherits(MovieApi, Generic);

MovieApi.prototype.config = {
	name: 'MovieApi',
	uniqueId: 'imdb_id',
	tabName: 'MovieApi',
	type: Generic.TabType.MOVIE,
  args: {
    apiURL: Generic.ArgType.ARRAY,
    lang: Generic.ArgType.STRING,
    quality: Generic.ArgType.STRING
	},
	metadata: 'trakttv:movie-metadata'
};

MovieApi.prototype.extractIds = function(items) {
	return _.map(items.results, 'imdb_id');
};

function formatFetch(movies) {
	var results = [];

	movies.forEach(function(movie) {
		if (movie.torrents) {
			results.push({
				type: 'movie',
				imdb_id: movie.imdb_id,
				title: movie.title,
				year: movie.year,
				genre: movie.genres,
				rating: parseInt(movie.rating.percentage, 10) / 10,
				runtime: movie.runtime,
        images: movie.images,
				image: movie.images.poster,
				cover: movie.images.poster,
				backdrop: movie.images.fanart,
        poster: movie.images.poster,
				synopsis: movie.synopsis,
				trailer: movie.trailer !== null ? movie.trailer : false,
				certification: movie.certification,
				torrents: movie.torrents['en'] !== null ? movie.torrents['en'] : movie.torrents[Object.keys(movie.torrents)[0]],
				langs: movie.torrents,
        subtitle: {}
			});
		}
	});

	return {
		results: sanitize(results),
		hasMore: true
	};
}

function formatDetail(movie) {
  return {
    type: 'movie',
    imdb_id: movie.imdb_id,
    title: movie.title,
    year: movie.year,
    genre: movie.genres,
    rating: parseInt(movie.rating.percentage, 10) / 10,
    runtime: movie.runtime,
    images: movie.images,
    image: movie.images.poster,
    cover: movie.images.poster,
    backdrop: movie.images.fanart,
    poster: movie.images.poster,
    synopsis: movie.synopsis,
    trailer: movie.trailer !== null ? movie.trailer : false,
    certification: movie.certification,
    torrents: movie.torrents['en'] !== null ? movie.torrents['en'] : movie.torrents[Object.keys(movie.torrents)[0]],
    langs: movie.torrents,
    subtitle: {}
  };
}

function processCloudFlareHack(options, url) {
	var req = options;
	var match = url.match(/^cloudflare\+(.*):\/\/(.*)/);
	if (match) {
		req = _.extend(req, {
			uri: match[1] + '://cloudflare.com/',
			headers: {
				'Host': match[2],
				'User-Agent': 'Mozilla/5.0 (Linux) AppleWebkit/534.30 (KHTML, like Gecko) PT/3.8.0'
			}
		});
	}
	return req;
}

function get(index, url, that) {
	var deferred = Q.defer();

	var options = {
		url: url,
		json: true
	};

	var req = processCloudFlareHack(options, that.apiURL[index]);
	console.info('Request to MovieApi', req.url);
	request(req, function(err, res, data) {
		if (err || res.statusCode >= 400) {
			console.warn('MovieAPI endpoint \'%s\' failed.', that.apiURL[index]);
			if (index + 1 >= that.apiURL.length) {
				return deferred.reject(err || 'Status Code is above 400');
			} else {
				return get(index + 1, url, that);
			}
		} else if (!data || data.error) {
			err = data ? data.status_message : 'No data returned';
			console.error('API error:', err);
			return deferred.reject(err);
		} else {
			return deferred.resolve(data);
		}
	});

	return deferred.promise;
}

MovieApi.prototype.resolveStream = function (src, filters, data) {
  filters.lang = filters.lang ? filters.lang : this.lang;
  filters.quality = filters.quality ? filters.quality : this.quality;

	return data.langs[filters.lang][filters.quality];
};

MovieApi.prototype.fetch = function (filters) {
	var that = this;

	var params = {};
	params.sort = 'seeds';
	params.limit = '50';

	if (filters.keywords) {
		params.keywords = filters.keywords.replace(/\s/g, '% ');
	}

	if (filters.genre) {
		params.genre = filters.genre;
	}

	if (filters.order) {
		params.order = filters.order;
	}

	if (filters.sorter && filters.sorter !== 'popularity') {
		params.sort = filters.sorter;
	}

  filters.page = filters.page ? filters.page : 1;

	var index = 0;
	var url = that.apiURL[index] + 'movies/' + filters.page + '?' + querystring.stringify(params).replace(/%25%20/g, '%20');
	return get(index, url, that).then(formatFetch);
};

MovieApi.prototype.random = function () {
	var that = this;
	var index = 0;
	var url = that.apiURL[index] + 'random/movie';
	return get(index, url, that).then(formatDetail);
};

MovieApi.prototype.detail = function (torrent_id, old_data, debug) {
  if (old_data) {
    return Q(old_data);
  }

  var that = this;
	var index = 0;
	var url = that.apiURL[index] + 'movie' + torrent_id;
	return get(index, url, that).then(formatDetail);
};

module.exports = MovieApi;
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue.toString();

		if (propValue && propValue.length > 0) {
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(tableName, conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		var dynamoDb = self.GetDynamoConnection(config);
		dynamodb.query(params,function(err, data) {
			callback(err, data);
		});
	};

/*	self.LoadData = function(data) {
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var key = {
			ConspiracyId:{S: data.ConspiracyId}
		};
		var params = {
			Key: key,
			TableName: config.conspiracies.tableName // required
			//ProjectionExpression: 'STRING_VALUE'
		};
		dynamodb.getItem(params, function(err, data) {
			if (err) { callback(err); }
			else {
				for(var field in dataModel){
					var dName = dataModel[field].dynamo.name;

					self[field] = dynaHlpr.GetDynamoValue(data[dName], dataModel[field])
				}

				callback(null, data);
			}
		});
	};
*/

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var dynaSpec = dataModel.data[field].dynamo;

			if (field in values) {
				itemParams[dynaSpec.name] = self.DynamoUpdateFormatter(values[field], dynaSpec.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynaSpec = dataModel.key[keyItem].dynamo;
			key[dynaSpec.name] = {};
			key[dynaSpec.name][dynaSpec.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<commit_msg>change table name to full dynamo config<commit_after>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue.toString();

		if (propValue && propValue.length > 0) {
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(config, conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': config.tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		var dynamoDb = self.GetDynamoConnection(config);
		dynamodb.query(params,function(err, data) {
			callback(err, data);
		});
	};

/*	self.LoadData = function(data) {
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var key = {
			ConspiracyId:{S: data.ConspiracyId}
		};
		var params = {
			Key: key,
			TableName: config.conspiracies.tableName // required
			//ProjectionExpression: 'STRING_VALUE'
		};
		dynamodb.getItem(params, function(err, data) {
			if (err) { callback(err); }
			else {
				for(var field in dataModel){
					var dName = dataModel[field].dynamo.name;

					self[field] = dynaHlpr.GetDynamoValue(data[dName], dataModel[field])
				}

				callback(null, data);
			}
		});
	};
*/

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var dynaSpec = dataModel.data[field].dynamo;

			if (field in values) {
				itemParams[dynaSpec.name] = self.DynamoUpdateFormatter(values[field], dynaSpec.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynaSpec = dataModel.key[keyItem].dynamo;
			key[dynaSpec.name] = {};
			key[dynaSpec.name][dynaSpec.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<|endoftext|>


<commit_before><commit_msg>refactor(cache): add md5 cache<commit_after><|endoftext|>


<commit_before>import { module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import test from 'ember-sinon-qunit/test-support/test';
import setupNoDeprecations from '../../../helpers/setup-no-deprecations';

module('Integration | Component | bs-nav/item', function(hooks) {
  setupRenderingTest(hooks);
  setupNoDeprecations(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
  });

  test('it has correct markup', async function(assert) {
    await render(hbs`
      {{#bs-nav/item}}
        template block text
      {{/bs-nav/item}}
    `);

    assert.dom('*').hasText('template block text', 'Shows block content');
    assert.dom('li').exists({ count: 1 }, 'it is an list item');
    assert.ok(!this.element.querySelector('li').classList.contains('active'), 'has not active class');
    assert.ok(!this.element.querySelector('li').classList.contains('disabled'), 'has not disabled class');

  });

  test('can be disabled', async function(assert) {
    await render(hbs`{{bs-nav/item disabled=true}}`);

    assert.dom('li').hasClass('disabled', 'has disabled class');
  });

  test('can be active', async function(assert) {
    await render(hbs`{{bs-nav/item active=true}}`);

    assert.dom('li').hasClass('active', 'has active class');
  });

  test('active link makes nav item active', async function(assert) {

    await render(hbs`
      {{#bs-nav/item}}
        {{#bs-nav/link-to "application" active="foo"}}Test{{/bs-nav/link-to}}
      {{/bs-nav/item}}
    `);
    assert.dom('li').hasClass('active', 'has active class');
  });

  test('disabled link makes nav item disabled', async function(assert) {

    await render(hbs`
      {{#bs-nav/item}}
        {{#bs-nav/link-to "application" disabled="foo"}}Test{{/bs-nav/link-to}}
      {{/bs-nav/item}}
    `);
    assert.dom('li').hasClass('disabled', 'has disabled class');
  });

  test('clicking item calls onClick action', async function(assert) {
    let action = this.spy();
    this.actions.click = action;
    await render(hbs`{{bs-nav/item onClick=(action "click")}}`);
    await click('li');

    assert.ok(action.calledOnce, 'action has been called');
  });
});
<commit_msg>Skip nav link active tests for now<commit_after>import { module, skip } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import test from 'ember-sinon-qunit/test-support/test';
import setupNoDeprecations from '../../../helpers/setup-no-deprecations';

module('Integration | Component | bs-nav/item', function(hooks) {
  setupRenderingTest(hooks);
  setupNoDeprecations(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
  });

  test('it has correct markup', async function(assert) {
    await render(hbs`
      {{#bs-nav/item}}
        template block text
      {{/bs-nav/item}}
    `);

    assert.dom('*').hasText('template block text', 'Shows block content');
    assert.dom('li').exists({ count: 1 }, 'it is an list item');
    assert.ok(!this.element.querySelector('li').classList.contains('active'), 'has not active class');
    assert.ok(!this.element.querySelector('li').classList.contains('disabled'), 'has not disabled class');

  });

  test('can be disabled', async function(assert) {
    await render(hbs`{{bs-nav/item disabled=true}}`);

    assert.dom('li').hasClass('disabled', 'has disabled class');
  });

  test('can be active', async function(assert) {
    await render(hbs`{{bs-nav/item active=true}}`);

    assert.dom('li').hasClass('active', 'has active class');
  });

  // @todo add new test when refactoring component to user routing service, instead of current ugly hack
  // see https://github.com/kaliber5/ember-bootstrap/issues/762
  skip('active link makes nav item active', async function(assert) {

    await render(hbs`
      {{#bs-nav/item}}
        {{#bs-nav/link-to "application" active="foo"}}Test{{/bs-nav/link-to}}
      {{/bs-nav/item}}
    `);
    assert.dom('li').hasClass('active', 'has active class');
  });

  test('disabled link makes nav item disabled', async function(assert) {

    await render(hbs`
      {{#bs-nav/item}}
        {{#bs-nav/link-to "application" disabled="foo"}}Test{{/bs-nav/link-to}}
      {{/bs-nav/item}}
    `);
    assert.dom('li').hasClass('disabled', 'has disabled class');
  });

  test('clicking item calls onClick action', async function(assert) {
    let action = this.spy();
    this.actions.click = action;
    await render(hbs`{{bs-nav/item onClick=(action "click")}}`);
    await click('li');

    assert.ok(action.calledOnce, 'action has been called');
  });
});
<|endoftext|>


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

    var users = {},
        internal = {},
        _ = require("underscore"),
        async = require("async"),
        AVAILABLE_USER_ROLES = ['editor', 'author', 'reader', 'admin', 'none'],
        MINIMUM_USER_NAME_LENGTH = 4,
        MINIMUM_PASSWORD_LENGTH = 6,
        LOGGING_CATEGORY = "GRASSHOPPER-USER";

    internal.app = app;

    function validateUser(userObj, mandatoryProps, cb){
        var props = Object.keys(userObj);

        async.each(mandatoryProps, function(prop, callback) {

                if(!_.contains(props, prop)){
                    return callback(new Error("'" + prop + "' property not found when validating the user."));
                }
                else if(prop == "login" && (userObj[prop] == null || (userObj[prop] != null && userObj[prop].trim().length < MINIMUM_USER_NAME_LENGTH))){
                    return callback(new Error("The login property cannot be null and has to have a minimum length of " + MINIMUM_USER_NAME_LENGTH + " characters."));
                }
                else if(prop == "password" && (userObj[prop] == null || (userObj[prop] != null && userObj[prop].trim().length < MINIMUM_PASSWORD_LENGTH))){
                    return callback(new Error("The password property cannot be null and has to have a minimum length of " + MINIMUM_PASSWORD_LENGTH+ " characters."));
                }
                else if(prop == "role" && !_.contains(AVAILABLE_USER_ROLES, userObj[prop])){
                    return callback(new Error("The role provided is not understood. Available roles are: " + AVAILABLE_USER_ROLES.join(",")));
                }

                return callback(null);

            },function (err) {
                //All required fields have been checked. Now check optional params.
                if(err){
                    internal.app.log.error(LOGGING_CATEGORY, err.message);
                }
                else {
                    if(userObj["permissions"] != null){
                        //If permissions exist it has to be an array.
                        if(userObj["permissions"] instanceof Array){
                            //Empty array is ok, just validate of params exist.
                            if(userObj["permissions"].length > 0){
                                for(var x = 0; x < userObj["permissions"].length; x++){
                                    //Each element must be an object
                                    if(userObj["permissions"][x] instanceof Object){
                                        var mandatoryProps = ["nodeid", "role"];

                                        for(var y = 0; y < mandatoryProps.length; y++){
                                            var props = Object.keys(userObj["permissions"][x]);

                                            if(!_.contains(props, mandatoryProps[y])){
                                                err = new Error(mandatoryProps[y] + " not supplied.");
                                                break;
                                            }
                                            else if(mandatoryProps[y] == "role" && !_.contains(AVAILABLE_USER_ROLES, userObj["permissions"][x][mandatoryProps[y]])){
                                                err = new Error("role provided is not valid. ");
                                                break;
                                            }
                                        }

                                    }
                                    else {
                                        err = new Error("permissions array elements must be objects.");
                                        break;
                                    }
                                }
                            }
                        }
                        else {
                            err = new Error("permissions object must be a valid array.");
                        }
                    }
                }

                cb.call(this, err);
            }
        );

    }

    /**
     * Method to be called when you want to create a user in the system.
     * When saving a user all mandatory fields will be checked.
     * @param userObj
     * @param callback
     */
    users.create = function(userObj, callback){
        internal.app.db.users.create(userObj, function(err, val){
            callback(err, val);
        });
    };

    users.getById = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            callback(err, val);
        });
    };

    users.getByEmail = function(userEmail, callback){
        internal.app.db.users.getByEmail(userEmail, function(err, val){
            callback(err, val);
        });
    };

    users.getByLogin = function(userLogin, callback){
        internal.app.db.users.getByLogin(userLogin, function(err, val){
            callback(err, val);
        });
    };

    users.update = function(userObj, callback){
        validateUser(userObj,
                ['name',
                'email',
                'role',
                'login'],
                function(err){
            if(err){
                callback(err);
            }
            else {
                var currentUserId = userObj._id;

                internal.app.db.users.getByLogin(userObj.login, function(err, existingUserObj){
                    //Validate if the user tried to change their role without being an admin.
                    if(existingUserObj && (userObj.role != existingUserObj.role && existingUserObj.role != "admin")){
                        callback(new Error("You do not have the permissions to change your role."), null);
                    }
                    else if(err || existingUserObj._id.toString() == currentUserId) {
                        //If user changed their login and the new user login is not in the system it will return err
                        internal.app.db.users.update(userObj, function(err, obj){

                            //Check to see if user state went from enabled to disabled. If disabled kill all auth tokens for uid
                            if(!err && userObj.enabled == false && existingUserObj.enabled == true){
                                internal.app.db.tokens.deleteByUserId(userObj._id, function(err){
                                    callback(err, obj);
                                });
                            }
                            else {
                                callback(err, obj);
                            }
                        });
                    }
                    else {
                        callback(new Error("Different user with the same login already exists."));
                    }
                });
            }
        });
    };

    users.disable = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            if(err){
                callback(err, val);
            }
            else {
                if(val != null){
                    val.enabled = false;

                    internal.app.db.users.update(val, function(err){
                        callback(err);
                    });
                }
                else {
                    callback(new Error("Cannot disable user. User with provided ID could not be found."));
                }
            }
        });
    };

    users.enable = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            if(err){
                callback(err, val);
            }
            else {
                if(val != null){
                    val.enabled = true;

                    internal.app.db.users.update(val, function(err){
                        callback(err);
                    });
                }
                else {
                    callback(new Error("Cannot enable user. User with provided ID could not be found."));
                }
            }
        });
    };

    users.deleteById = function(userId, callback){
        internal.app.db.users.deleteById(userId, function(err){
            if(err){
                callback(err);
            }
            else {
                callback(null);
            }
        });
    };

    users.list = function(options, callback){

        async.parallel(
            [
                function(cb){
                    internal.app.db.users.list(options, function(err, userList){
                        cb(err, userList);
                    });
                },
                function(cb){
                    internal.app.db.users.describe(options, function(err, totals){
                        cb(err, totals);
                    });
                }
            ],function(err, results){
                if(err){
                    callback(err);
                }
                else {
                    callback(null, {
                        total: results[1][0].count,
                        results: results[0]
                    });
                }
            }
        );

    };

    return users;
};

<commit_msg>Added an authenticate method and removed validation. This is now done in the models.<commit_after>module.exports = function(app){
    "use strict";

    var users = {},
        internal = {},
        _ = require("underscore"),
        async = require("async"),
        AVAILABLE_USER_ROLES = ['editor', 'author', 'reader', 'admin', 'none'],
        MINIMUM_USER_NAME_LENGTH = 4,
        MINIMUM_PASSWORD_LENGTH = 6,
        LOGGING_CATEGORY = "GRASSHOPPER-USER";

    internal.app = app;

    /**
     * Method to be called when you want to create a user in the system.
     * When saving a user all mandatory fields will be checked.
     * @param userObj
     * @param callback
     */
    users.create = function(userObj, callback){
        internal.app.db.users.create(userObj, function(err, val){
            callback(err, val);
        });
    };

    users.getById = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            callback(err, val);
        });
    };

    users.getByEmail = function(userEmail, callback){
        internal.app.db.users.getByEmail(userEmail, function(err, val){
            callback(err, val);
        });
    };

    users.getByLogin = function(userLogin, callback){
        internal.app.db.users.getByLogin(userLogin, function(err, val){
            callback(err, val);
        });
    };

    users.authenticate = function(userLogin, userPassword, callback){
        internal.app.db.users.authenticate(userLogin, userPassword, function(err, val){
            callback(err, val);
        });
    };

    users.update = function(userObj, callback){
        var currentUserId = userObj._id;

        internal.app.db.users.getByLogin(userObj.login, function(err, existingUserObj){
            //Validate if the user tried to change their role without being an admin.
            if(existingUserObj && (userObj.role != existingUserObj.role && existingUserObj.role != "admin")){
                callback(new Error("You do not have the permissions to change your role."), null);
            }
            else if(err || existingUserObj._id.toString() == currentUserId) {
                //If user changed their login and the new user login is not in the system it will return err
                internal.app.db.users.update(userObj, function(err, obj){

                    //Check to see if user state went from enabled to disabled. If disabled kill all auth tokens for uid
                    if(!err && userObj.enabled == false && existingUserObj.enabled == true){
                        internal.app.db.tokens.deleteByUserId(userObj._id, function(err){
                            callback(err, obj);
                        });
                    }
                    else {
                        callback(err, obj);
                    }
                });
            }
            else {
                callback(new Error("Different user with the same login already exists."));
            }
        });
    };

    users.disable = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            if(err){
                callback(err, val);
            }
            else {
                if(val != null){
                    val.enabled = false;

                    internal.app.db.users.update(val, function(err){
                        callback(err);
                    });
                }
                else {
                    callback(new Error("Cannot disable user. User with provided ID could not be found."));
                }
            }
        });
    };

    users.enable = function(userId, callback){
        internal.app.db.users.getById(userId, function(err, val){
            if(err){
                callback(err, val);
            }
            else {
                if(val != null){
                    val.enabled = true;

                    internal.app.db.users.update(val, function(err){
                        callback(err);
                    });
                }
                else {
                    callback(new Error("Cannot enable user. User with provided ID could not be found."));
                }
            }
        });
    };

    users.deleteById = function(userId, callback){
        internal.app.db.users.deleteById(userId, function(err){
            if(err){
                callback(err);
            }
            else {
                callback(null);
            }
        });
    };

    users.list = function(options, callback){

        async.parallel(
            [
                function(cb){
                    internal.app.db.users.list(options, function(err, userList){
                        cb(err, userList);
                    });
                },
                function(cb){
                    internal.app.db.users.describe(options, function(err, totals){
                        cb(err, totals);
                    });
                }
            ],function(err, results){
                if(err){
                    callback(err);
                }
                else {
                    callback(null, {
                        total: results[1][0].count,
                        results: results[0]
                    });
                }
            }
        );

    };

    return users;
};

<|endoftext|>


<commit_before><commit_msg>fix error message in readPinMux<commit_after><|endoftext|>


<commit_before>var TimezoneAutocomplete = require('./src/components/TimezoneAutocomplete').default;
var timezoneShape = require('./src/utils/types').timezoneShape;
var injectTimezone = require('./src/inject').default;

module.exports = {
    TimezoneAutocomplete: TimezoneAutocomplete,
    timezoneShape: timezoneShape,
    injectTimezone: injectTimezone
};
<commit_msg>Missed updating the imported paths to the lib directory instead of src<commit_after>var TimezoneAutocomplete = require('./lib/components/TimezoneAutocomplete').default;
var timezoneShape = require('./lib/utils/types').timezoneShape;
var injectTimezone = require('./lib/inject').default;

module.exports = {
    TimezoneAutocomplete: TimezoneAutocomplete,
    timezoneShape: timezoneShape,
    injectTimezone: injectTimezone
};
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('site-chrome', 'Integration | Component | site chrome', {
  integration: true
});

test('it renders', function(assert) {

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{site-chrome}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#site-chrome}}
      template block text
    {{/site-chrome}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});
<commit_msg>adds tests for site-chrome<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('site-chrome', 'Integration | Component | site chrome', {
  integration: true
});

test('it renders', function(assert) {

  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{site-chrome}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#site-chrome}}
      template block text
    {{/site-chrome}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});

test('top level blocks', function(assert) {
  this.render(hbs`
    {{#site-chrome as |chrome|}}
      {{chrome.top}}
      {{chrome.nav}}
      {{chrome.body}}
      {{chrome.footer}}
    {{/site-chrome}}
  `);

  assert.equal(this.$('.site-chrome__top').length, 1, 'top bar renders');
  assert.equal(this.$('.site-chrome__nav').length, 1, 'nav section renders');
  assert.equal(this.$('.site-chrome__body').length, 1, 'body renders');
  assert.equal(this.$('footer.site-chrome__footer').length, 1, 'footer renders');
});

test('full usage', function(assert) {
  function directChildText(node) {
    return Array.from(node.childNodes).filter(n => n.nodeType === 3)
      .map(n => n.textContent.trim())
      .join('');
  }

  this.render(hbs`
    {{#site-chrome as |chrome|}}

      {{#chrome.top as |top|}}
        This is on the far left
        {{#top.body as |body|}}
          This is inside a full wrapper
          {{#body.corner as |button|}}
            Inside the corner with a button
            {{#component button}}
              The Button
            {{/component}}
          {{/body.corner}}
        {{/top.body}}
      {{/chrome.top}}

      {{#chrome.nav as |nav|}}
        {{#nav.corner}}
          The upper left corner
        {{/nav.corner}}

        {{#nav.links as |links|}}
          {{links.link text='foo'}}
          {{#links.link}}non link item{{/links.link}}
        {{/nav.links}}

        {{#nav.footer}}
          footer of the nav
        {{/nav.footer}}
      {{/chrome.nav}}

      {{#chrome.body}}
        body area
      {{/chrome.body}}

      {{#chrome.footer}}
        site footer
      {{/chrome.footer}}
    {{/site-chrome}}
  `);

  assert.equal(directChildText(this.$('.site-chrome__top')[0]), "This is on the far left");
  assert.equal(directChildText(this.$('.site-chrome__top__body__right')[0]), "This is inside a full wrapper");
  assert.equal(directChildText(this.$('.site-chrome__right-corner')[0]), "Inside the corner with a button");
  assert.equal(this.$('.site-chrome__top-button').text().trim(), 'The Button');

  assert.equal(this.$('.site-chrome__left-corner').text().trim(), 'The upper left corner');
  assert.equal(this.$('.site-chrome__links-list').text().split('\n').map(t => t.trim()).join(''), 'foonon link item');
  assert.equal(this.$('.site-chrome__link').eq(0).text().trim(), 'foo');
  assert.equal(this.$('.site-chrome__link').eq(0).find('a').length, 1);

  assert.equal(this.$('.site-chrome__nav__footer').text().trim(), 'footer of the nav');

  assert.equal(this.$('.site-chrome__body').text().trim(), 'body area');

  assert.ok(this.$('.site-chrome__footer').text().trim().match('site footer'));
});
<|endoftext|>


<commit_before><commit_msg>Convert alias update #3<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
import { describeComponent, it } from 'ember-mocha';
import { expect } from 'chai';
import hbs from 'htmlbars-inline-precompile';
import { is } from 'ember-version-is';

// remove alpha, beta, canary, etc. suffixes to the current Ember version
const BASE_VERSION =  Ember.VERSION.indexOf('-') === -1 ? Ember.VERSION : Ember.VERSION.substr(0, Ember.VERSION.indexOf('-'));

describeComponent('array-contains', 'helper:array-contains', { integration: true }, function() {

  it('should not throw error if array undefined or null', function () {
    this.set('array', undefined);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain anything");

    this.set('array', null);
    expect(this.$().text()).to.equal("false", "array should not contain anything");
  });

  it('should throw error if array is invalid', function () {
    this.set('array', 'any');

    expect(this.render.bind(this,hbs`{{array-contains array 'any'}}`))
      .to.throw("Assertion Failed: First parameter should be a valid array");
  });

  it('should return true if literal contained', function () {
    this.set('array', ['c', 'string', 0, true, null]);

    // before ember 2.9, null and undefined were both coerced to null
    // (see https://github.com/emberjs/ember.js/issues/14016)
    if (is(BASE_VERSION, "greaterThanOrEqualTo", "2.9.0")) {
      this.get('array').push(undefined);
    }

    this.render(hbs`{{array-contains array 'c'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'c'");

    this.render(hbs`{{array-contains array 'string'}}`);
    expect(this.$().text()).to.equal("true","array should contain 'string'");

    this.render(hbs`{{array-contains array 0}}`);
    expect(this.$().text()).to.equal("true", "array should contain '0'");

    this.render(hbs`{{array-contains array true}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'true'");

    this.render(hbs`{{array-contains array null}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'null'");

    this.render(hbs`{{array-contains array undefined}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'undefined'");
  });

  it('should return false if literal not contained', function () {
    this.set('array', ['c', 'string', 0, true, null]);

    this.render(hbs`{{array-contains array 'a'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'a'");

    this.render(hbs`{{array-contains array 'foo'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'foo'");

    this.render(hbs`{{array-contains array 2}}`);
    expect(this.$().text()).to.equal("false", "array should not contain '2'");

    this.render(hbs`{{array-contains array false}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'false'");

    // before ember 2.9, null and undefined were both coerced to null
    // (see https://github.com/emberjs/ember.js/issues/14016)
    if (is(BASE_VERSION, "greaterThanOrEqualTo", "2.9.0")) {
      this.render(hbs`{{array-contains array undefined}}`);
      expect(this.$().text()).to.equal("false", "array should not contain 'undefined'");
    }
  });

  it('should return true if native object contained', function () {
    let elem = {id: 1, title: 'any'};
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if native object not contained', function () {
    this.set('array', [{id: 2, title: 'other'}]);
    this.set('elem', {id: 1, title: 'any'});

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when native object change', function () {
    let elem = {id: 1, title: 'any'};
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {id: 1, title: 'any'});

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if Ember object contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if Ember object not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);
    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when Ember object change', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if native object property contained', function () {
    this.set('array', [{id: 1, title: 'any'}]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any' title");
  });

  it('should return false if native object property not contained', function () {
    this.set('array', [{id: 2, title: 'other'}]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'any' title");
  });

  it('should return true if Ember object contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if Ember object not contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when Ember object change', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if Ember object property contained', function () {
    this.set('array', [Ember.Object.create({id: 1, title: 'any'})]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any' title");
  });

  it('should return false if Ember object property not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'any' title");
  });

  it('should rerun test when array replaced', function () {
    this.set('array', ['any']);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any'");

    this.set('array', ['not']);

    expect(this.$().text()).to.equal("false", "array should not contain 'any'");
  });

  it('should rerun test when array changed', function () {
    let array = ['any'];
    this.set('array', array);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any'");

    Ember.run(() => {
      array.popObject();
    });

    expect(this.$().text()).to.equal("false", "array should not contain 'any'");

    Ember.run(() => {
      array.pushObject('any');
    });

    expect(this.$().text()).to.equal("true", "array should contain 'any'");
  });

  it('should rerun test when property in array changed', function () {
    let object = {id: 1, title: 'any'};
    let array = [object];
    this.set('array', array);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain object with prop 'any'");

    Ember.run(() => {
      Ember.set(object, 'title', 'not');
    });

    expect(this.$().text()).to.equal("false", "array should not contain object with prop 'any'");

    Ember.run(() => {
      Ember.set(object, 'title', 'any');
    });

    expect(this.$().text()).to.equal("true", "array should contain object with prop 'any'");
  });

  it('should return true in nested if if Ember object property contained', function () {
    this.set('array', [Ember.Object.create({id: 1, title: 'any'})]);

    this.render(hbs`{{if (array-contains array 'any' property='title') 'ifTrue' 'ifFalse'}}`);
    expect(this.$().text()).to.equal("ifTrue", "array should contain 'any' title");
  });

  it('should return false in nested if if Ember object property not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);

    this.render(hbs`{{if (array-contains array 'any' property='title') 'ifTrue' 'ifFalse'}}`);
    expect(this.$().text()).to.equal("ifFalse", "array should not contain 'any' title");
  });
});

<commit_msg>refactor(tests): use replace instead of substr<commit_after>import Ember from 'ember';
import { describeComponent, it } from 'ember-mocha';
import { expect } from 'chai';
import hbs from 'htmlbars-inline-precompile';
import { is } from 'ember-version-is';

// remove alpha, beta, canary, etc. suffixes to the current Ember version
const BASE_VERSION =  Ember.VERSION.replace(/-.*/, "");

describeComponent('array-contains', 'helper:array-contains', { integration: true }, function() {

  it('should not throw error if array undefined or null', function () {
    this.set('array', undefined);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain anything");

    this.set('array', null);
    expect(this.$().text()).to.equal("false", "array should not contain anything");
  });

  it('should throw error if array is invalid', function () {
    this.set('array', 'any');

    expect(this.render.bind(this,hbs`{{array-contains array 'any'}}`))
      .to.throw("Assertion Failed: First parameter should be a valid array");
  });

  it('should return true if literal contained', function () {
    this.set('array', ['c', 'string', 0, true, null]);

    // before ember 2.9, null and undefined were both coerced to null
    // (see https://github.com/emberjs/ember.js/issues/14016)
    if (is(BASE_VERSION, "greaterThanOrEqualTo", "2.9.0")) {
      this.get('array').push(undefined);
    }

    this.render(hbs`{{array-contains array 'c'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'c'");

    this.render(hbs`{{array-contains array 'string'}}`);
    expect(this.$().text()).to.equal("true","array should contain 'string'");

    this.render(hbs`{{array-contains array 0}}`);
    expect(this.$().text()).to.equal("true", "array should contain '0'");

    this.render(hbs`{{array-contains array true}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'true'");

    this.render(hbs`{{array-contains array null}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'null'");

    this.render(hbs`{{array-contains array undefined}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'undefined'");
  });

  it('should return false if literal not contained', function () {
    this.set('array', ['c', 'string', 0, true, null]);

    this.render(hbs`{{array-contains array 'a'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'a'");

    this.render(hbs`{{array-contains array 'foo'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'foo'");

    this.render(hbs`{{array-contains array 2}}`);
    expect(this.$().text()).to.equal("false", "array should not contain '2'");

    this.render(hbs`{{array-contains array false}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'false'");

    // before ember 2.9, null and undefined were both coerced to null
    // (see https://github.com/emberjs/ember.js/issues/14016)
    if (is(BASE_VERSION, "greaterThanOrEqualTo", "2.9.0")) {
      this.render(hbs`{{array-contains array undefined}}`);
      expect(this.$().text()).to.equal("false", "array should not contain 'undefined'");
    }
  });

  it('should return true if native object contained', function () {
    let elem = {id: 1, title: 'any'};
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if native object not contained', function () {
    this.set('array', [{id: 2, title: 'other'}]);
    this.set('elem', {id: 1, title: 'any'});

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when native object change', function () {
    let elem = {id: 1, title: 'any'};
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {id: 1, title: 'any'});

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if Ember object contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if Ember object not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);
    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when Ember object change', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if native object property contained', function () {
    this.set('array', [{id: 1, title: 'any'}]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any' title");
  });

  it('should return false if native object property not contained', function () {
    this.set('array', [{id: 2, title: 'other'}]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'any' title");
  });

  it('should return true if Ember object contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");
  });

  it('should return false if Ember object not contained', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should recompute when Ember object change', function () {
    let elem = Ember.Object.create({id: 1, title: 'any'});
    this.set('array', [elem]);
    this.set('elem', elem);

    this.render(hbs`{{array-contains array elem}}`);
    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', {});

    expect(this.$().text()).to.equal("false", "array should not contain elem");

    this.set('elem', elem);

    expect(this.$().text()).to.equal("true", "array should contain elem");

    this.set('elem', Ember.Object.create({id: 1, title: 'any'}));

    expect(this.$().text()).to.equal("false", "array should not contain elem");
  });

  it('should return true if Ember object property contained', function () {
    this.set('array', [Ember.Object.create({id: 1, title: 'any'})]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any' title");
  });

  it('should return false if Ember object property not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("false", "array should not contain 'any' title");
  });

  it('should rerun test when array replaced', function () {
    this.set('array', ['any']);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any'");

    this.set('array', ['not']);

    expect(this.$().text()).to.equal("false", "array should not contain 'any'");
  });

  it('should rerun test when array changed', function () {
    let array = ['any'];
    this.set('array', array);

    this.render(hbs`{{array-contains array 'any'}}`);
    expect(this.$().text()).to.equal("true", "array should contain 'any'");

    Ember.run(() => {
      array.popObject();
    });

    expect(this.$().text()).to.equal("false", "array should not contain 'any'");

    Ember.run(() => {
      array.pushObject('any');
    });

    expect(this.$().text()).to.equal("true", "array should contain 'any'");
  });

  it('should rerun test when property in array changed', function () {
    let object = {id: 1, title: 'any'};
    let array = [object];
    this.set('array', array);

    this.render(hbs`{{array-contains array 'any' property='title'}}`);
    expect(this.$().text()).to.equal("true", "array should contain object with prop 'any'");

    Ember.run(() => {
      Ember.set(object, 'title', 'not');
    });

    expect(this.$().text()).to.equal("false", "array should not contain object with prop 'any'");

    Ember.run(() => {
      Ember.set(object, 'title', 'any');
    });

    expect(this.$().text()).to.equal("true", "array should contain object with prop 'any'");
  });

  it('should return true in nested if if Ember object property contained', function () {
    this.set('array', [Ember.Object.create({id: 1, title: 'any'})]);

    this.render(hbs`{{if (array-contains array 'any' property='title') 'ifTrue' 'ifFalse'}}`);
    expect(this.$().text()).to.equal("ifTrue", "array should contain 'any' title");
  });

  it('should return false in nested if if Ember object property not contained', function () {
    this.set('array', [Ember.Object.create({id: 2, title: 'other'})]);

    this.render(hbs`{{if (array-contains array 'any' property='title') 'ifTrue' 'ifFalse'}}`);
    expect(this.$().text()).to.equal("ifFalse", "array should not contain 'any' title");
  });
});

<|endoftext|>


<commit_before>'use strict';

const crawler    = require('./lib/crawler');
const parse      = require('./lib/parse');
const fs         = require('fs');

let anos = [ 2012, 2013, 2014, 2015, 2016];

if (process.argv.length > 2)
  anos = process.argv.slice(2);

Promise.all(anos.map(ano => { return crawler.get(ano)} ))
  .then(function (data) {
    data.forEach(function (elem) {
      let arquivo = fs.createWriteStream('data/brasileiro' + elem.ano + '.json');

      arquivo.on('error', function(err) { /* error handling */ });
      elem.data('.tabela-jogos').find('.row.full-game').each(function (i) {
          arquivo.write(JSON.stringify(parse.jogoCampeonatoBrasileiro(elem.data(this))) + '\n');
      })
      arquivo.end();

      console.log(arquivo.path);
    })
  })
<commit_msg>Adicionar pasta data se não existe<commit_after>'use strict';

const crawler    = require('./lib/crawler');
const parse      = require('./lib/parse');
const fs         = require('fs');

let anos = [ 2012, 2013, 2014, 2015, 2016];

if (process.argv.length > 2)
  anos = process.argv.slice(2);

fs.mkdir('data', { recursive: true }, (err) => {
  if (err) throw err;
});

Promise.all(anos.map(ano => { return crawler.get(ano)} ))
  .then(function (data) {
    data.forEach(function (elem) {
      let arquivo = fs.createWriteStream('data/brasileiro' + elem.ano + '.json');

      arquivo.on('error', function(err) { /* error handling */ });
      elem.data('.tabela-jogos').find('.row.full-game').each(function (i) {
          arquivo.write(JSON.stringify(parse.jogoCampeonatoBrasileiro(elem.data(this))) + '\n');
      })
      arquivo.end();

      console.log(arquivo.path);
    })
  })
<|endoftext|>


<commit_before>// Core

var Sugar = function() {};

Sugar.Array    = function() {};
Sugar.Date     = function() {};
Sugar.Boolean  = function() {};
Sugar.Number   = function() {};
Sugar.String   = function() {};
Sugar.RegExp   = function() {};
Sugar.Function = function() {};

// Internal dependencies

Sugar.Date.get    = function() {};
Sugar.Date.create = function() {};

// Utility methods

Sugar.hasOwn             = function() {};
Sugar.setProperty        = function() {};
Sugar.defineProperty     = function() {};
Sugar.iterateOverObject  = function() {};
Sugar.wrapInstanceMethod = function() {};

var SugarNamespaceMethod = {
  flags: null,
  static: null,
  instance: null,
}

var SugarExtendOptions = {
  methods:         null,
  enhanceArray:    null,
  enhanceString:   null,
  objectPrototype: null,
}

// Numbers

Sugar.Number.thousands = null;
Sugar.Number.decimal   = null;

// Strings

Sugar.String.Inflector = {
  acronyms:      null,
  acronym:       null,
  acronymRegExp: null,
  plural:        null,
  singular:      null,
  irregular:     null,
  uncountable:   null,
  human:         null,
  clear:         null,
};

// ES6

Array.from                  = function() {};
Array.prototype.find        = function() {};
Array.prototype.findIndex   = function() {};

String.prototype.startsWith = function() {};
String.prototype.endsWith   = function() {};
String.prototype.contains   = function() {};
String.prototype.includes   = function() {};
String.prototype.repeat     = function() {};

// Dates

// Not exposed: monthSuffix, ordinalNumberMap
var Locale = function() {
  this.mdy                = null;
  this.code               = null;
  this.ampm               = null;
  this.ampmLower          = null;
  this.articles           = null;
  this.cachedFormat       = null;
  this.compiledFormats    = null;
  this.digitDate          = null;
  this.duration           = null;
  this.firstDayOfWeek     = null;
  this.firstDayOfWeekYear = null;
  this.full               = null;
  this.future             = null;
  this.long               = null;
  this.medium             = null;
  this.modifiers          = null;
  this.modifiersByName    = null;
  this.monthSuffix        = null;
  this.months             = null;
  this.monthsLower        = null;
  this.numbers            = null;
  this.optionals          = null;
  this.ordinalSuffix      = null;
  this.parse              = null;
  this.timeParse          = null;
  this.past               = null;
  this.plural             = null;
  this.relative           = null;
  this.short              = null;
  this.stamp              = null;
  this.timeMarker         = null;
  this.timeSuffixes       = null;
  this.time               = null;
  this.tokens             = null;
  this.units              = null;
  this.unitsLower         = null;
  this.variant            = null;
  this.weekdays           = null;
  this.weekdaysLower      = null;
}

Locale.prototype.addFormat = function() {};

var DateSet = {
  ampm:          null,
  date:          null,
  day:           null,
  days:          null,
  edge:          null,
  fullMonth:     null,
  hour:          null,
  hours:         null,
  millisecond:   null,
  milliseconds:  null,
  minute:        null,
  minutes:       null,
  month:         null,
  months:        null,
  num:           null,
  offsetHours:   null,
  offsetMinutes: null,
  offsetSign:    null,
  second:        null,
  seconds:       null,
  shift:         null,
  sign:          null,
  specificity:   null,
  unit:          null,
  utc:           null,
  timestamp:     null,
  week:          null,
  weekday:       null,
  weeks:         null,
  year:          null,
  yearSign:      null,
  years:         null,
}

var DateInputFormat = {
  variant:  null,
  locale:   null,
  reg:      null,
  to:       null,
}

var DateModifier = {
  src:    null,
  name:   null,
  value:  null,
}

var DateCreateOptions = {
  fromUTC: null,
  setUTC:  null,
  locale:  null,
  future:  null,
  past:    null,
}

// Ranges

Range.prototype.start   = null;
Range.prototype.end     = null;
Range.prototype.step    = function() {};
Range.prototype.clamp   = function() {};
Range.prototype.every   = function() {};
Range.prototype.isValid = function() {};

Sugar.Date.range   = function() {};
Sugar.Number.range = function() {};
Sugar.String.range = function() {};

// Objects

/**
 * @suppress {duplicate}
 */
function Hash(obj) {};

var ObjectMergeOptions = {
  deep:       null,
  hidden:     null,
  resolve:    null,
  descriptor: null,
}

var ObjectToQueryStringOptions = {
  deep:      null,
  prefix:    null,
  transform: null,
  separator: null,
}

var ObjectFromQueryStringOptions = {
  deep:      null,
  auto:      null,
  transform: null,
  separator: null,
}
<commit_msg>a few missing externs for Inflector<commit_after>// Core

var Sugar = function() {};

Sugar.Array    = function() {};
Sugar.Date     = function() {};
Sugar.Boolean  = function() {};
Sugar.Number   = function() {};
Sugar.String   = function() {};
Sugar.RegExp   = function() {};
Sugar.Function = function() {};

// Internal dependencies

Sugar.Date.get    = function() {};
Sugar.Date.create = function() {};

// Utility methods

Sugar.hasOwn             = function() {};
Sugar.setProperty        = function() {};
Sugar.defineProperty     = function() {};
Sugar.iterateOverObject  = function() {};
Sugar.wrapInstanceMethod = function() {};

var SugarNamespaceMethod = {
  flags: null,
  static: null,
  instance: null,
}

var SugarExtendOptions = {
  methods:         null,
  enhanceArray:    null,
  enhanceString:   null,
  objectPrototype: null,
}

// Numbers

Sugar.Number.thousands = null;
Sugar.Number.decimal   = null;

// Strings

Sugar.String.Inflector = {
  acronyms:      null,
  acronym:       null,
  acronymRegExp: null,
  humanize:      null,
  plural:        null,
  singular:      null,
  inflect:       null,
  irregular:     null,
  uncountable:   null,
  human:         null,
  clear:         null,
  reset:         null,
};

// ES6

Array.from                  = function() {};
Array.prototype.find        = function() {};
Array.prototype.findIndex   = function() {};

String.prototype.startsWith = function() {};
String.prototype.endsWith   = function() {};
String.prototype.contains   = function() {};
String.prototype.includes   = function() {};
String.prototype.repeat     = function() {};

// Dates

// Not exposed: monthSuffix, ordinalNumberMap
var Locale = function() {
  this.mdy                = null;
  this.code               = null;
  this.ampm               = null;
  this.ampmLower          = null;
  this.articles           = null;
  this.cachedFormat       = null;
  this.compiledFormats    = null;
  this.digitDate          = null;
  this.duration           = null;
  this.firstDayOfWeek     = null;
  this.firstDayOfWeekYear = null;
  this.full               = null;
  this.future             = null;
  this.long               = null;
  this.medium             = null;
  this.modifiers          = null;
  this.modifiersByName    = null;
  this.monthSuffix        = null;
  this.months             = null;
  this.monthsLower        = null;
  this.numbers            = null;
  this.optionals          = null;
  this.ordinalSuffix      = null;
  this.parse              = null;
  this.timeParse          = null;
  this.past               = null;
  this.plural             = null;
  this.relative           = null;
  this.short              = null;
  this.stamp              = null;
  this.timeMarker         = null;
  this.timeSuffixes       = null;
  this.time               = null;
  this.tokens             = null;
  this.units              = null;
  this.unitsLower         = null;
  this.variant            = null;
  this.weekdays           = null;
  this.weekdaysLower      = null;
}

Locale.prototype.addFormat = function() {};

var DateSet = {
  ampm:          null,
  date:          null,
  day:           null,
  days:          null,
  edge:          null,
  fullMonth:     null,
  hour:          null,
  hours:         null,
  millisecond:   null,
  milliseconds:  null,
  minute:        null,
  minutes:       null,
  month:         null,
  months:        null,
  num:           null,
  offsetHours:   null,
  offsetMinutes: null,
  offsetSign:    null,
  second:        null,
  seconds:       null,
  shift:         null,
  sign:          null,
  specificity:   null,
  unit:          null,
  utc:           null,
  timestamp:     null,
  week:          null,
  weekday:       null,
  weeks:         null,
  year:          null,
  yearSign:      null,
  years:         null,
}

var DateInputFormat = {
  variant:  null,
  locale:   null,
  reg:      null,
  to:       null,
}

var DateModifier = {
  src:    null,
  name:   null,
  value:  null,
}

var DateCreateOptions = {
  fromUTC: null,
  setUTC:  null,
  locale:  null,
  future:  null,
  past:    null,
}

// Ranges

Range.prototype.start   = null;
Range.prototype.end     = null;
Range.prototype.step    = function() {};
Range.prototype.clamp   = function() {};
Range.prototype.every   = function() {};
Range.prototype.isValid = function() {};

Sugar.Date.range   = function() {};
Sugar.Number.range = function() {};
Sugar.String.range = function() {};

// Objects

/**
 * @suppress {duplicate}
 */
function Hash(obj) {};

var ObjectMergeOptions = {
  deep:       null,
  hidden:     null,
  resolve:    null,
  descriptor: null,
}

var ObjectToQueryStringOptions = {
  deep:      null,
  prefix:    null,
  transform: null,
  separator: null,
}

var ObjectFromQueryStringOptions = {
  deep:      null,
  auto:      null,
  transform: null,
  separator: null,
}
<|endoftext|>


<commit_before>/*

 Created by LingaRaja.

 Has the events and helpers related to home page.

 */
Template.header.events({
    'click #pageName': function() {
        Session.set("pageId",this._id);
    }
});

Template.header.helpers({
    'pagesList' : function() {
        return Pages.find();
    },
});

Template.home.helpers({
    'postsList' : function() {
        return Posts.find({pageId:Session.get("pageId")});
    }
	'mediaList' : function() {
    	return Media.find();
    }
});<commit_msg>Added pages and their related posts in home page<commit_after>/*

 Created by LingaRaja.

 Has the events and helpers related to home page.

 */
Template.header.events({
    'click #pageName': function() {
        Session.set("pageId",this._id);
    }
});

Template.header.helpers({
    'pagesList' : function() {
        return Pages.find();
    },
});

Template.home.helpers({
    'postsList' : function() {
        return Posts.find({pageId:Session.get("pageId")});
    },
	'mediaList' : function() {
    	return Media.find();
    }
});<|endoftext|>


<commit_before><commit_msg>:lipstick:<commit_after><|endoftext|>