<commit_before>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var child_process = require('child_process');
var fs = require('fs');

//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------

var RegistryBuilderChild = function() {};

//-------------------------------------------------------------------------------
// Public Class Methods
//-------------------------------------------------------------------------------

RegistryBuilderChild.prototype.start = function() {
    var _this = this;
    process.on('message', function(message) {
        _this.handleMessage(message);
    });
};

RegistryBuilderChild.prototype.error = function(message) {
    process.send({
        error: true,
        message: message
    });
};

//-------------------------------------------------------------------------------
// Private Class Methods
//-------------------------------------------------------------------------------

/**
 * @private
 * @param {string} argumentsString
 * @return {Array.<(string|number)>}
 */
RegistryBuilderChild.prototype.parseArguments = function(argumentsString) {
    var args = [];
    var parts = argumentsString.split(',');
    parts.forEach(function(part) {
        var results = part.match(/\s*('|")(.*?)\1\s*/);
        if (results) {
            args.push(results[2]);
        } else {
            var num = parseFloat(part);
            if (isNaN(num)) {
                throw new Error("Could not parse parameter '" + part + "'");
            }
            args.push(num);
        }
    });
    return args;
};

/**
 * @private
 * @param {string} sourceFile
 */
RegistryBuilderChild.prototype.processSourceFile = function(sourceFile) {
    var _this = this;
    fs.readFile(sourceFile, 'utf8', function(error, data) {
        if (error) {
            throw new Error(error);
        }
        var annotations = [];
        var lines = data.split('\n');
        lines.forEach(function(line) {
            var results = line.match(/\s*\/\/\s*@([a-zA-Z][0-9a-zA-Z]*)(?:\((.+)?\))?\s*/);
            if (results) {
                var annotation = {
                    name: results[1]
                };
                var argumentsString = results[2];
                if (argumentsString !== undefined) {
                    annotation.arguments = _this.parseArguments(argumentsString);
                }
                annotations.push(annotation);
            }
        });
        process.send({
            sourceFile: sourceFile,
            annotations: annotations
        });
    });
};

//-------------------------------------------------------------------------------
// Message Handlers
//-------------------------------------------------------------------------------

RegistryBuilderChild.prototype.handleMessage = function(message) {
    if (message.sourceFile) {
        try {
            this.processSourceFile(message.sourceFile);
        } catch(e) {
            this.error(e.message);
        }
    } else {
        this.error("RegistryBuilderChild received message that did not have a source file");
    }
};

//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------

module.exports = RegistryBuilderChild;
<commit_msg>- improve the error message that occurs when a parse error occurs so that it tells us the file the error occurred in.<commit_after>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var child_process = require('child_process');
var fs = require('fs');

//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------

var RegistryBuilderChild = function() {};

//-------------------------------------------------------------------------------
// Public Class Methods
//-------------------------------------------------------------------------------

RegistryBuilderChild.prototype.start = function() {
    var _this = this;
    process.on('message', function(message) {
        _this.handleMessage(message);
    });
};

RegistryBuilderChild.prototype.error = function(message) {
    process.send({
        error: true,
        message: message
    });
};

//-------------------------------------------------------------------------------
// Private Class Methods
//-------------------------------------------------------------------------------

/**
 * @private
 * @param {string} argumentsString
 * @return {Array.<(string|number)>}
 */
RegistryBuilderChild.prototype.parseArguments = function(argumentsString) {
    var args = [];
    var parts = argumentsString.split(',');
    parts.forEach(function(part) {
        var results = part.match(/\s*('|")(.*?)\1\s*/);
        if (results) {
            args.push(results[2]);
        } else {
            var num = parseFloat(part);
            if (isNaN(num)) {
                throw new Error("Could not parse parameter '" + part + "'");
            }
            args.push(num);
        }
    });
    return args;
};

/**
 * @private
 * @param {string} sourceFile
 */
RegistryBuilderChild.prototype.processSourceFile = function(sourceFile) {
    var _this = this;
    fs.readFile(sourceFile, 'utf8', function(error, data) {
        if (error) {
            throw new Error(error);
        }
        try {
            var annotations = [];
            var lines = data.split('\n');
            lines.forEach(function(line) {
                var results = line.match(/\s*\/\/\s*@([a-zA-Z][0-9a-zA-Z]*)(?:\((.+)?\))?\s*/);
                if (results) {
                    var annotation = {
                        name: results[1]
                    };
                    var argumentsString = results[2];
                    if (argumentsString !== undefined) {
                        annotation.arguments = _this.parseArguments(argumentsString);
                    }
                    annotations.push(annotation);
                }
            });
        } catch(error) {
            error.message += " while processing file '" + sourceFile + "'";
            throw error;
        }
        process.send({
            sourceFile: sourceFile,
            annotations: annotations
        });
    });
};

//-------------------------------------------------------------------------------
// Message Handlers
//-------------------------------------------------------------------------------

RegistryBuilderChild.prototype.handleMessage = function(message) {
    if (message.sourceFile) {
        try {
            this.processSourceFile(message.sourceFile);
        } catch(e) {
            this.error(e.message);
        }
    } else {
        this.error("RegistryBuilderChild received message that did not have a source file");
    }
};

//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------

module.exports = RegistryBuilderChild;
<|endoftext|>


<commit_before>'use strict';

angular.module('core').controller('promoController', ['$scope', 'Authentication', 'promoService',
	function($scope, Authentication, promoService) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

	// Some example string - remove in prod
        $scope.helloText = 'Promo form Test';
        $scope.testuser = $scope.authentication.user.displayName;

    	$scope.promos = promoService.query();
		$scope.newPromo = {};

	$scope.post = function() {
	  promoService.save({
	  	  created_by: $scope.authentication.user._id
	  	, created_by_name: $scope.authentication.user.displayName
		, Deal_Type: $scope.newPromo.Deal_Type
		, Account: $scope.newPromo.Account
		, Product_Group: $scope.newPromo.Product_Group
		, Feature: $scope.newPromo.Feature
		, Display_Level: $scope.newPromo.Display_Level
		, Normal_Retail: $scope.newPromo.Normal_Retail
		, Promo_Price: $scope.newPromo.Promo_Price
		, Allowance_Type: $scope.newPromo.Allowance_Type
		, Allowance_Amount: $scope.newPromo.Allowance_Amount
		, Retailer_Margin: $scope.newPromo.Retailer_Margin
		, Start_Date: $scope.newPromo.Start_Date
		, End_Date: $scope.newPromo.End_Date
		, Allocation: $scope.newPromo.Allocation
		, Allocation_Quantity: $scope.newPromo.Allocation_Quantity
		, Allocation_UOM: $scope.newPromo.Allocation_UOM
		, Forecast_Units: $scope.newPromo.Forecast_Units
		, ROI: $scope.newPromo.ROI
		, Notes: $scope.newPromo.Notes

	  	}, function(){
	    $scope.promos = promoService.query();
	    $scope.newPromo = {};
	    $window.location.href = '/promos';
	  });
	};

	$scope.delete = function(promo)	{
		promoService.delete({id: promo._id});
		$scope.promo = promoService.query();
	};

	}
]);
<commit_msg>Update promo.client.controller.js<commit_after>'use strict';

angular.module('core').controller('promoController', ['$scope', 'Authentication', 'promoService',
	function($scope, Authentication, promoService) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

	// Some example string - remove in prod
        $scope.helloText = 'Promo form Test';
        $scope.testuser = $scope.authentication.user.displayName;

    	$scope.promos = promoService.query();
		$scope.newPromo = {};

	$scope.post = function() {
	  promoService.save({
	  	  created_by: $scope.authentication.user._id
	  	, created_by_name: $scope.authentication.user.displayName
		, Deal_Type: $scope.newPromo.Deal_Type
		, Account: $scope.newPromo.Account
		, Product_Group: $scope.newPromo.Product_Group
		, Feature: $scope.newPromo.Feature
		, Display_Level: $scope.newPromo.Display_Level
		, Normal_Retail: $scope.newPromo.Normal_Retail
		, Promo_Price: $scope.newPromo.Promo_Price
		, Allowance_Type: $scope.newPromo.Allowance_Type
		, Allowance_Amount: $scope.newPromo.Allowance_Amount
		, Retailer_Margin: $scope.newPromo.Retailer_Margin
		, Start_Date: $scope.newPromo.Start_Date
		, End_Date: $scope.newPromo.End_Date
		, Allocation: $scope.newPromo.Allocation
		, Allocation_Quantity: $scope.newPromo.Allocation_Quantity
		, Allocation_UOM: $scope.newPromo.Allocation_UOM
		, Forecast_Units: $scope.newPromo.Forecast_Units
		, ROI: $scope.newPromo.ROI
		, Notes: $scope.newPromo.Notes

	  	}, function(){
	    $scope.promos = promoService.query();
	    $scope.newPromo = {};
	    $location.path('/promos');
	  });
	};

	$scope.delete = function(promo)	{
		promoService.delete({id: promo._id});
		$scope.promo = promoService.query();
	};

	}
]);
<|endoftext|>


<commit_before>phast.ResourceLoader = {};

phast.ResourceLoader.Request = function () {

    var onsuccess,
        onerror,
        onend,
        successText,
        success,
        resolved = false,
        called = false;

    Object.defineProperty(this, 'onsuccess', {

        get: function () {
            return onsuccess;
        },

        set: function (func) {
            onsuccess = func;
            if (resolved && success) {
                onsuccess(successText);
            }
        }
    });

    Object.defineProperty(this, 'onerror', {

        get: function () {
            return onerror;
        },

        set: function (func) {
            onerror = func;
            if (resolved && !success) {
                onerror();
            }
        }
    });

    Object.defineProperty(this, 'onend', {

        get: function () {
            return onend;
        },

        set: function (func) {
            onend = func;
            if (resolved) {
                onend();
            }
        }
    });

    this.success = function (responseText) {
        resolved = true;
        successText = responseText;
        success = true;
        if (!called && onsuccess) {
            onsuccess(responseText);
        }
        end();
        called = true;
    };

    this.error = function () {
        resolved = true;
        success = false;
        if (!called && onerror) {
            onerror();
        }
        end();
        called = true;
    };

    function end() {
        if (!called && onend) {
            onend();
        }
    }
};

phast.ResourceLoader.RequestParams = function (faulty) {

    this.isFaulty = function () {
        return faulty;
    };
};

phast.ResourceLoader.RequestParams.fromString = function(string) {
    try {
        var parsed = JSON.parse(string);
        return phast.ResourceLoader.RequestParams.fromObject(parsed);
    } catch (e) {
        return new phast.ResourceLoader.RequestParams(true);
    }
};

phast.ResourceLoader.RequestParams.fromObject = function (parsed) {
    var params = new phast.ResourceLoader.RequestParams(false);
    for (var x in parsed) {
        params[x] = parsed[x];
    }
    return params;
};

phast.ResourceLoader.BundlerServiceClient = function (serviceUrl) {

    var timeoutHandler;
    var accumulatingPack = [];

    this.get = function (params) {
        var request = new phast.ResourceLoader.Request();
        if (params.isFaulty()) {
            request.error();
            return request;
        }
        accumulatingPack.push(new PackItem(request, params));
        clearTimeout(timeoutHandler);
        timeoutHandler = setTimeout(this.flush);
        return request;
    };

    this.flush = function () {
        var pack = accumulatingPack;
        accumulatingPack = [];
        clearTimeout(timeoutHandler);
        makeRequest(pack);
    };

    function packToQuery(pack) {
        var glue = serviceUrl.indexOf('?') > -1 ? '&' : '?';
        var parts = [];
        pack.forEach(function (item, idx) {
            for (var key in item.params) {
                if (key === 'isFaulty') {
                    continue;
                }
                parts.push(encodeURIComponent(key) + '_' + idx + '=' + encodeURIComponent(item.params[key]));
            }
        });
        return serviceUrl + glue + parts.join('&');
    }

    function makeRequest(pack) {
        var query = packToQuery(pack);
        var errorHandler = function () {
            handleError(pack);
        };
        var successHandler = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                handleResponse(xhr.responseText, pack);
            } else {
                handleError(pack);
            }
        };
        var xhr = new XMLHttpRequest();
        xhr.open('GET', query);
        xhr.addEventListener('error', errorHandler);
        xhr.addEventListener('abort', errorHandler);
        xhr.addEventListener('load', successHandler);
        xhr.send();
    }

    function handleError(pack) {
        pack.forEach(function (item) {
            try {
                item.request.error();
            } catch (e) {}
        });
    }

    function handleResponse(responseText, pack) {
        try {
            var responses = JSON.parse(responseText);
        } catch (e) {
            handleError(pack);
            return;
        }
        responses.forEach(function (response, idx) {
            try {
                if (response.status === 200) {
                    pack[idx].request.success(response.content);
                } else {
                    pack[idx].request.error();
                }
            } catch (e) {};
        });
    }

    function PackItem(request, params) {
        this.request = request;
        this.params = params;
    }

};

phast.ResourceLoader.IndexedDBResourceCache = function (client) {

    var Request = phast.ResourceLoader.Request;
    var Cache = phast.ResourceLoader.IndexedDBResourceCache;

    this.get = function (params) {
        var request = new Request();
        var cacheRequest = getFromCache(params);
        cacheRequest.onsuccess = request.success;
        cacheRequest.onerror = function () {
            getFromClient(params, request);
        };
        return request;
    };

    function getFromCache(params, noRetry) {
        var request = new Request();
        var dbRequest = getDB();
        dbRequest.onerror = function () {
            request.error();
        };
        dbRequest.onsuccess = function (db) {
            try {
                var storeRequest = db
                    .transaction(Cache.storeName)
                    .objectStore(Cache.storeName)
                    .get(params.token);
                storeRequest.onerror = function () {
                    request.error();
                };
                storeRequest.onsuccess = function () {
                    if (storeRequest.result) {
                        request.success(storeRequest.result.content);
                    } else {
                        request.error();
                    }
                };
            } catch (e) {
                request.error();
            }
        };
        return request;
    }

    function getFromClient(params, request) {
        var clientRequest = client.get(params);
        clientRequest.onerror = request.error;
        clientRequest.onsuccess = function (responseText) {
            storeInCache(params, responseText);
            request.success(responseText);
        };
    }

    function storeInCache(params, responseText) {
        var dbRequest = getDB();
        try {
            dbRequest.onsuccess = function (db) {
                db.transaction(Cache.storeName, 'readwrite')
                    .objectStore(Cache.storeName)
                    .put({token: params.token, content: responseText});
            };
        } catch (e) {}
    }

    function getDB() {
        var request = new Request();
        if (Cache.dbConnection) {
            request.success(Cache.dbConnection);
        } else {
            Cache.dbConnectionRequests.push(request);
            if (Cache.dbConnectionRequests.length === 1) {
                openDB();
            }
        }
        return request;
    }

    function openDB() {
        var dbOpenRequest = indexedDB.open(
            Cache.dbName,
            Cache.dbVersion
        );
        dbOpenRequest.onupgradeneeded = function () {
            createDB(dbOpenRequest.result);
        };
        dbOpenRequest.onsuccess = function () {
            Cache.dbConnection = dbOpenRequest.result;
            callStoredConnectionRequests(function (request) {
                request.success(dbOpenRequest.result);
            });
        };
        dbOpenRequest.onerror = function () {
            callStoredConnectionRequests(function (request) {
                request.error();
            });
        }
    }

    function callStoredConnectionRequests(cb) {
        var requests = Cache.dbConnectionRequests;
        while (requests.length) {
            cb(requests.shift());
        }
    }

    function createDB(db) {
        db.createObjectStore(Cache.storeName, {keyPath: 'token'});
    }
};

phast.ResourceLoader.IndexedDBResourceCache.close = function () {
    if (phast.ResourceLoader.IndexedDBResourceCache.dbConnection) {
        phast.ResourceLoader.IndexedDBResourceCache.dbConnection.close();
        phast.ResourceLoader.IndexedDBResourceCache.dbConnection = null;
    }
};

phast.ResourceLoader.IndexedDBResourceCache.dbName = 'phastResourcesCache';
phast.ResourceLoader.IndexedDBResourceCache.storeName = 'resources';
phast.ResourceLoader.IndexedDBResourceCache.dbVersion = 1;
phast.ResourceLoader.IndexedDBResourceCache.dbConnection = null;
phast.ResourceLoader.IndexedDBResourceCache.dbConnectionRequests = [];

phast.ResourceLoader.make = function (serviceUrl) {
    var client = new phast.ResourceLoader.BundlerServiceClient(serviceUrl);
    return new phast.ResourceLoader.IndexedDBResourceCache(client);
};

<commit_msg>Drop database on store exception<commit_after>phast.ResourceLoader = {};

phast.ResourceLoader.Request = function () {

    var onsuccess,
        onerror,
        onend,
        successText,
        success,
        resolved = false,
        called = false;

    Object.defineProperty(this, 'onsuccess', {

        get: function () {
            return onsuccess;
        },

        set: function (func) {
            onsuccess = func;
            if (resolved && success) {
                onsuccess(successText);
            }
        }
    });

    Object.defineProperty(this, 'onerror', {

        get: function () {
            return onerror;
        },

        set: function (func) {
            onerror = func;
            if (resolved && !success) {
                onerror();
            }
        }
    });

    Object.defineProperty(this, 'onend', {

        get: function () {
            return onend;
        },

        set: function (func) {
            onend = func;
            if (resolved) {
                onend();
            }
        }
    });

    this.success = function (responseText) {
        resolved = true;
        successText = responseText;
        success = true;
        if (!called && onsuccess) {
            onsuccess(responseText);
        }
        end();
        called = true;
    };

    this.error = function () {
        resolved = true;
        success = false;
        if (!called && onerror) {
            onerror();
        }
        end();
        called = true;
    };

    function end() {
        if (!called && onend) {
            onend();
        }
    }
};

phast.ResourceLoader.RequestParams = function (faulty) {

    this.isFaulty = function () {
        return faulty;
    };
};

phast.ResourceLoader.RequestParams.fromString = function(string) {
    try {
        var parsed = JSON.parse(string);
        return phast.ResourceLoader.RequestParams.fromObject(parsed);
    } catch (e) {
        return new phast.ResourceLoader.RequestParams(true);
    }
};

phast.ResourceLoader.RequestParams.fromObject = function (parsed) {
    var params = new phast.ResourceLoader.RequestParams(false);
    for (var x in parsed) {
        params[x] = parsed[x];
    }
    return params;
};

phast.ResourceLoader.BundlerServiceClient = function (serviceUrl) {

    var timeoutHandler;
    var accumulatingPack = [];

    this.get = function (params) {
        var request = new phast.ResourceLoader.Request();
        if (params.isFaulty()) {
            request.error();
            return request;
        }
        accumulatingPack.push(new PackItem(request, params));
        clearTimeout(timeoutHandler);
        timeoutHandler = setTimeout(this.flush);
        return request;
    };

    this.flush = function () {
        var pack = accumulatingPack;
        accumulatingPack = [];
        clearTimeout(timeoutHandler);
        makeRequest(pack);
    };

    function packToQuery(pack) {
        var glue = serviceUrl.indexOf('?') > -1 ? '&' : '?';
        var parts = [];
        pack.forEach(function (item, idx) {
            for (var key in item.params) {
                if (key === 'isFaulty') {
                    continue;
                }
                parts.push(encodeURIComponent(key) + '_' + idx + '=' + encodeURIComponent(item.params[key]));
            }
        });
        return serviceUrl + glue + parts.join('&');
    }

    function makeRequest(pack) {
        var query = packToQuery(pack);
        var errorHandler = function () {
            handleError(pack);
        };
        var successHandler = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
                handleResponse(xhr.responseText, pack);
            } else {
                handleError(pack);
            }
        };
        var xhr = new XMLHttpRequest();
        xhr.open('GET', query);
        xhr.addEventListener('error', errorHandler);
        xhr.addEventListener('abort', errorHandler);
        xhr.addEventListener('load', successHandler);
        xhr.send();
    }

    function handleError(pack) {
        pack.forEach(function (item) {
            try {
                item.request.error();
            } catch (e) {}
        });
    }

    function handleResponse(responseText, pack) {
        try {
            var responses = JSON.parse(responseText);
        } catch (e) {
            handleError(pack);
            return;
        }
        responses.forEach(function (response, idx) {
            try {
                if (response.status === 200) {
                    pack[idx].request.success(response.content);
                } else {
                    pack[idx].request.error();
                }
            } catch (e) {};
        });
    }

    function PackItem(request, params) {
        this.request = request;
        this.params = params;
    }

};

phast.ResourceLoader.IndexedDBResourceCache = function (client) {

    var Request = phast.ResourceLoader.Request;
    var Cache = phast.ResourceLoader.IndexedDBResourceCache;

    this.get = function (params) {
        var request = new Request();
        var cacheRequest = getFromCache(params);
        cacheRequest.onsuccess = request.success;
        cacheRequest.onerror = function () {
            getFromClient(params, request);
        };
        return request;
    };

    function getFromCache(params, noRetry) {
        var request = new Request();
        var dbRequest = getDB();
        dbRequest.onerror = function () {
            request.error();
        };
        dbRequest.onsuccess = function (db) {
            try {
                var storeRequest = db
                    .transaction(Cache.storeName)
                    .objectStore(Cache.storeName)
                    .get(params.token);
                storeRequest.onerror = function () {
                    request.error();
                };
                storeRequest.onsuccess = function () {
                    if (storeRequest.result) {
                        request.success(storeRequest.result.content);
                    } else {
                        request.error();
                    }
                };
            } catch (e) {
                dropDB();
                request.error();
            }
        };
        return request;
    }

    function getFromClient(params, request) {
        var clientRequest = client.get(params);
        clientRequest.onerror = request.error;
        clientRequest.onsuccess = function (responseText) {
            storeInCache(params, responseText);
            request.success(responseText);
        };
    }

    function storeInCache(params, responseText) {
        var dbRequest = getDB();
        try {
            dbRequest.onsuccess = function (db) {
                db.transaction(Cache.storeName, 'readwrite')
                    .objectStore(Cache.storeName)
                    .put({token: params.token, content: responseText});
            };
        } catch (e) {}
    }

    function getDB() {
        var request = new Request();
        if (Cache.dbConnection) {
            request.success(Cache.dbConnection);
        } else {
            Cache.dbConnectionRequests.push(request);
            if (Cache.dbConnectionRequests.length === 1) {
                openDB();
            }
        }
        return request;
    }

    function openDB() {
        var dbOpenRequest = indexedDB.open(
            Cache.dbName,
            Cache.dbVersion
        );
        dbOpenRequest.onupgradeneeded = function () {
            createDB(dbOpenRequest.result);
        };
        dbOpenRequest.onsuccess = function () {
            Cache.dbConnection = dbOpenRequest.result;
            callStoredConnectionRequests(function (request) {
                request.success(dbOpenRequest.result);
            });
        };
        dbOpenRequest.onerror = function () {
            callStoredConnectionRequests(function (request) {
                request.error();
            });
        }
    }

    function callStoredConnectionRequests(cb) {
        var requests = Cache.dbConnectionRequests;
        while (requests.length) {
            cb(requests.shift());
        }
    }

    function createDB(db) {
        db.createObjectStore(Cache.storeName, {keyPath: 'token'});
    }

    function dropDB() {
        Cache.close();
        indexedDB.deleteDatabase(Cache.dbName);
    }
};

phast.ResourceLoader.IndexedDBResourceCache.close = function () {
    if (phast.ResourceLoader.IndexedDBResourceCache.dbConnection) {
        phast.ResourceLoader.IndexedDBResourceCache.dbConnection.close();
        phast.ResourceLoader.IndexedDBResourceCache.dbConnection = null;
    }
};

phast.ResourceLoader.IndexedDBResourceCache.dbName = 'phastResourcesCache';
phast.ResourceLoader.IndexedDBResourceCache.storeName = 'resources';
phast.ResourceLoader.IndexedDBResourceCache.dbVersion = 1;
phast.ResourceLoader.IndexedDBResourceCache.dbConnection = null;
phast.ResourceLoader.IndexedDBResourceCache.dbConnectionRequests = [];

phast.ResourceLoader.make = function (serviceUrl) {
    var client = new phast.ResourceLoader.BundlerServiceClient(serviceUrl);
    return new phast.ResourceLoader.IndexedDBResourceCache(client);
};

<|endoftext|>


<commit_before>import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
});

export default Router;
<commit_msg>fixing lint<commit_after>import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
});

export default Router;
<|endoftext|>


<commit_before>var scenario = 'm';
var routingProfile = 'truck40t.xml';
var enableRestrictionZones = true;
var enableTruckAttributes = true;

var baseLayers;
var routingControl;

// initialize the map
var map = L.map('map', {
    contextmenu: true,
    contextmenuWidth: 200,
    contextmenuItems: [{
        text: 'Add Waypoint At Start',
        callback: function (ev) {
            if (routingControl._plan._waypoints[0].latLng) {
                routingControl.spliceWaypoints(0, 0, ev.latlng);
            } else {
                routingControl.spliceWaypoints(0, 1, ev.latlng);
            }
        }
    }, {
        text: 'Add Waypoint At End',
        callback: function (ev) {
            if (routingControl._plan._waypoints[routingControl._plan._waypoints.length - 1].latLng) {
                routingControl.spliceWaypoints(routingControl._plan._waypoints.length, 0, ev.latlng);
            } else {
                routingControl.spliceWaypoints(routingControl._plan._waypoints.length - 1, 1, ev.latlng);
            }
        }
    }]
});

// create a new pane for the overlay tiles
map.createPane('tileOverlayPane');
map.getPane('tileOverlayPane').style.zIndex = 500;
map.getPane('tileOverlayPane').style.pointerEvents = 'none';

// get the start and end coordinates for a scenario
var getPlan = function () {
    switch (scenario) {
        case 'm':
            {
                return [
                    L.latLng(48.099865415772754, 11.543884277343752),
                    L.latLng(48.167001359708934, 11.602249145507814)
                ];
            }
        case 'hh':
            {
                return [
                    L.latLng(53.55145062603612, 9.934816360473632),
                    L.latLng(53.52796226132062, 9.84975814819336)
                ];
            }
        case 'na':
            {
                return [
                    L.latLng(40.71454, -74.00711),
                    L.latLng(42.35867, -71.05672)
                ];
            }
        case 'au':
            {
                return [
                    L.latLng(-33.86959, 151.20694),
                    L.latLng(-35.3065, 149.12659)
                ];
            }
        default:
            { // 'eu'
                return [
                    L.latLng(48.8588, 2.3469),
                    L.latLng(52.3546, 4.9039)
                ];
            }
    }
};

// returns a layer group for xmap back- and foreground layers
var getXMapBaseLayers = function (style) {
    var bg = L.tileLayer('https://s0{s}-xserver2-europe-test.cloud.ptvgroup.com/services/rest/XMap/tile/{z}/{x}/{y}/{profile}-labels' +
        '?xtok={token}',
         {
            profile: 'silkysand',
            token: token,
            attribution: 'PTV, TOMTOM',
            maxZoom: 22,
            subdomains: '1234'
        });

    var fg = L.TileLayer.clickableTiles('https://s0{s}-xserver2-europe-test.cloud.ptvgroup.com/services/rest/XMap/tile/{z}/{x}/{y}/{profile}-background-transport' +
        '{vl1}{vl2}{vl3}/json?xtok={token}',
         {
            profile: 'silkysand',
            token: token,
            attribution: 'PTV, TOMTOM',
            maxZoom: 22,
            subdomains: '1234',
            pane: 'tileOverlayPane',
            zIndex: 1,
            isVirtualHost: true,
            vl1: '',
            vl2: '',
            vl3: ''
        });

    return L.layerGroup([bg, fg]);
}

routingControl = L.Routing.control({
    plan: L.Routing.plan(getPlan(), {
        routeWhileDragging: false,
        routeDragInterval: 3000,
        createMarker: function (i, wp) {
            return L.marker(wp.latLng, {
                draggable: true,
                icon: L.icon.glyph({
                    glyph: String.fromCharCode(65 + i)
                })
            });
        },
        geocoder: L.Control.Geocoder.ptv({
            serviceUrl: 'https://xserver2-europe-test.cloud.ptvgroup.com/services/rest/XLocate/locations/',
            token: token
        }),
        reverseWaypoints: true
    }),
    lineOptions: {
        styles: [
            // Shadow
            {
                color: 'black',
                opacity: 0.8,
                weight: 11
            },
            // Outline
            {
                color: 'green',
                opacity: 0.8,
                weight: 8
            },
            // Center
            {
                color: 'orange',
                opacity: 1,
                weight: 4
            }
        ]
    },
    router: L.Routing.ptv({
        serviceUrl: 'https://xserver2-europe-test.cloud.ptvgroup.com/services/rs/XRoute/',
        token: token,
        supportsHeadings: true,
        beforeSend: function (request) {
            request.storedProfile = routingProfile;
            request.requestProfile = {
                "featureLayerProfile": {
                    "themes": [{
                        "enabled": enableTruckAttributes,
                        "id": "PTV_TruckAttributes"
                    }, {

                        "enabled": enableRestrictionZones,
                        "id": "PTV_RestrictionZones"
                    }]
                }
            };
            return request;
        }
    }),
    collapsible: true,
    routeWhileDragging: false,
    routeDragInterval: 3000,
    formatter: new L.Routing.Formatter({
        roundingSensitivity: 1000
    })
}).addTo(map);

routingControl.on('routingerror', function (e) { });

L.Routing.errorControl(routingControl).addTo(map);
//	routingControl.hide();
//map.setView([49, 8.4], 16);

// update ui
$('#scenarioSelect').val(scenario);
$('#routingProfile').val(routingProfile);
$('#enableRestrictionZones').prop("checked", enableRestrictionZones);
$('#enableTruckAttributes').prop("checked", enableTruckAttributes);

// add side bar
var sidebar = L.control.sidebar('sidebar').addTo(map);
sidebar.open('home');

// add scale control
L.control.scale().addTo(map);

var baseLayers = {
    "PTV gravelpit": getXMapBaseLayers('gravelpit'),
    "PTV sandbox": getXMapBaseLayers('sandbox'),
    "PTV silkysand": getXMapBaseLayers('silkysand').addTo(map)
};

var truckAttributesLayer = L.virtualLayer('+PTV_TruckAttributes', 'vl1');
var restrictionZonesLayer = L.virtualLayer('+PTV_RestrictionZones', 'vl2');

if (enableTruckAttributes)
    map.addLayer(truckAttributesLayer);
if (enableRestrictionZones)
    map.addLayer(restrictionZonesLayer);

L.control.layers(baseLayers, {
    "Truck Attributes": truckAttributesLayer,
    "Restriction Zones": restrictionZonesLayer
}, {
        position: 'bottomleft',
        autoZIndex: false
    }).addTo(map);

var indSelf = false;

var _onLayerAdd = function (e) {
    if (indSelf) // event was triggered by panel
        return;

    if (e.layer === truckAttributesLayer) {
        enableTruckAttributes = true;
        $('#enableTruckAttributes').prop("checked", enableTruckAttributes);
    } else if (e.layer === restrictionZonesLayer) {
        enableRestrictionZones = true;
        $('#enableRestrictionZones').prop("checked", enableRestrictionZones);
    } else return;

    routingControl.route();
};

var _onLayerRemove = function (e) {
    if (indSelf) // event was triggered by panel
        return;

    if (e.layer === truckAttributesLayer) {
        enableTruckAttributes = false;
        $('#enableTruckAttributes').prop("checked", enableTruckAttributes);
    } else if (e.layer === restrictionZonesLayer) {
        enableRestrictionZones = false;
        $('#enableRestrictionZones').prop("checked", enableRestrictionZones);
    } else return;

    routingControl.route();
};

map.on('layeradd', _onLayerAdd, this)
map.on('layerremove', _onLayerRemove, this)

// update the map scenario
var updateScenario = function () {
    scenario = $('#scenarioSelect option:selected').val();
    updateParams(true);
};

// update the routing params
var updateParams = function (updateWayPoints) {
    routingProfile = $('#vehicleType').val();

    enableRestrictionZones = $('#enableRestrictionZones').is(':checked');
    enableTruckAttributes = $('#enableTruckAttributes').is(':checked');

    // sync panel->layers
    indSelf = true;

    if (enableTruckAttributes)
        map.addLayer(truckAttributesLayer);
    else
        map.removeLayer(truckAttributesLayer);

    if (enableRestrictionZones)
        map.addLayer(restrictionZonesLayer);
    else
        map.removeLayer(restrictionZonesLayer);

    indSelf = false;

    if (updateWayPoints)
        routingControl.setWaypoints(getPlan());
    routingControl._router.options.numberOfAlternatives = 0;
    routingControl.route();
};<commit_msg>updated sample<commit_after>var scenario = 'm';
var routingProfile = 'truck40t.xml';
var enableRestrictionZones = true;
var enableTruckAttributes = true;

var baseLayers;
var routingControl;

// initialize the map
var map = L.map('map', {
    contextmenu: true,
    contextmenuWidth: 200,
    contextmenuItems: [{
        text: 'Add Waypoint At Start',
        callback: function (ev) {
            if (routingControl._plan._waypoints[0].latLng) {
                routingControl.spliceWaypoints(0, 0, ev.latlng);
            } else {
                routingControl.spliceWaypoints(0, 1, ev.latlng);
            }
        }
    }, {
        text: 'Add Waypoint At End',
        callback: function (ev) {
            if (routingControl._plan._waypoints[routingControl._plan._waypoints.length - 1].latLng) {
                routingControl.spliceWaypoints(routingControl._plan._waypoints.length, 0, ev.latlng);
            } else {
                routingControl.spliceWaypoints(routingControl._plan._waypoints.length - 1, 1, ev.latlng);
            }
        }
    }]
});

// create a new pane for the overlay tiles
map.createPane('tileOverlayPane');
map.getPane('tileOverlayPane').style.zIndex = 500;
map.getPane('tileOverlayPane').style.pointerEvents = 'none';

// get the start and end coordinates for a scenario
var getPlan = function () {
    switch (scenario) {
        case 'm':
            {
                return [
                    L.latLng(48.10032397915225, 11.547317504882812),
                    L.latLng(48.167001359708934, 11.602249145507814)
                ];
            }
        case 'hh':
            {
                return [
                    L.latLng(53.55145062603612, 9.934816360473632),
                    L.latLng(53.52796226132062, 9.84975814819336)
                ];
            }
        case 'na':
            {
                return [
                    L.latLng(40.71454, -74.00711),
                    L.latLng(42.35867, -71.05672)
                ];
            }
        case 'au':
            {
                return [
                    L.latLng(-33.86959, 151.20694),
                    L.latLng(-35.3065, 149.12659)
                ];
            }
        default:
            { // 'eu'
                return [
                    L.latLng(48.8588, 2.3469),
                    L.latLng(52.3546, 4.9039)
                ];
            }
    }
};

// returns a layer group for xmap back- and foreground layers
var getXMapBaseLayers = function (style) {
    var bg = L.tileLayer('https://s0{s}-xserver2-europe-test.cloud.ptvgroup.com/services/rest/XMap/tile/{z}/{x}/{y}/{profile}-labels' +
        '?xtok={token}',
         {
            profile: 'silkysand',
            token: token,
            attribution: 'PTV, TOMTOM',
            maxZoom: 22,
            subdomains: '1234'
        });

    var fg = L.TileLayer.clickableTiles('https://s0{s}-xserver2-europe-test.cloud.ptvgroup.com/services/rest/XMap/tile/{z}/{x}/{y}/{profile}-background-transport' +
        '{vl1}{vl2}{vl3}/json?xtok={token}',
         {
            profile: 'silkysand',
            token: token,
            attribution: 'PTV, TOMTOM',
            maxZoom: 22,
            subdomains: '1234',
            pane: 'tileOverlayPane',
            zIndex: 1,
            isVirtualHost: true,
            vl1: '',
            vl2: '',
            vl3: ''
        });

    return L.layerGroup([bg, fg]);
}

routingControl = L.Routing.control({
    plan: L.Routing.plan(getPlan(), {
        routeWhileDragging: false,
        routeDragInterval: 3000,
        createMarker: function (i, wp) {
            return L.marker(wp.latLng, {
                draggable: true,
                icon: L.icon.glyph({
                    glyph: String.fromCharCode(65 + i)
                })
            });
        },
        geocoder: L.Control.Geocoder.ptv({
            serviceUrl: 'https://xserver2-europe-test.cloud.ptvgroup.com/services/rest/XLocate/locations/',
            token: token
        }),
        reverseWaypoints: true
    }),
    lineOptions: {
        styles: [
            // Shadow
            {
                color: 'black',
                opacity: 0.8,
                weight: 11
            },
            // Outline
            {
                color: 'green',
                opacity: 0.8,
                weight: 8
            },
            // Center
            {
                color: 'orange',
                opacity: 1,
                weight: 4
            }
        ]
    },
    router: L.Routing.ptv({
        serviceUrl: 'https://xserver2-europe-test.cloud.ptvgroup.com/services/rs/XRoute/',
        token: token,
        supportsHeadings: true,
        beforeSend: function (request) {
            request.storedProfile = routingProfile;
            request.requestProfile = {
                "featureLayerProfile": {
                    "themes": [{
                        "enabled": enableTruckAttributes,
                        "id": "PTV_TruckAttributes"
                    }, {

                        "enabled": enableRestrictionZones,
                        "id": "PTV_RestrictionZones"
                    }]
                }
            };
            return request;
        }
    }),
    collapsible: true,
    routeWhileDragging: false,
    routeDragInterval: 3000,
    formatter: new L.Routing.Formatter({
        roundingSensitivity: 1000
    })
}).addTo(map);

routingControl.on('routingerror', function (e) { });

L.Routing.errorControl(routingControl).addTo(map);
//	routingControl.hide();
//map.setView([49, 8.4], 16);

// update ui
$('#scenarioSelect').val(scenario);
$('#routingProfile').val(routingProfile);
$('#enableRestrictionZones').prop("checked", enableRestrictionZones);
$('#enableTruckAttributes').prop("checked", enableTruckAttributes);

// add side bar
var sidebar = L.control.sidebar('sidebar').addTo(map);
sidebar.open('home');

// add scale control
L.control.scale().addTo(map);

var baseLayers = {
    "PTV gravelpit": getXMapBaseLayers('gravelpit'),
    "PTV sandbox": getXMapBaseLayers('sandbox'),
    "PTV silkysand": getXMapBaseLayers('silkysand').addTo(map)
};

var truckAttributesLayer = L.virtualLayer('+PTV_TruckAttributes', 'vl1');
var restrictionZonesLayer = L.virtualLayer('+PTV_RestrictionZones', 'vl2');

if (enableTruckAttributes)
    map.addLayer(truckAttributesLayer);
if (enableRestrictionZones)
    map.addLayer(restrictionZonesLayer);

L.control.layers(baseLayers, {
    "Truck Attributes": truckAttributesLayer,
    "Restriction Zones": restrictionZonesLayer
}, {
        position: 'bottomleft',
        autoZIndex: false
    }).addTo(map);

var indSelf = false;

var _onLayerAdd = function (e) {
    if (indSelf) // event was triggered by panel
        return;

    if (e.layer === truckAttributesLayer) {
        enableTruckAttributes = true;
        $('#enableTruckAttributes').prop("checked", enableTruckAttributes);
    } else if (e.layer === restrictionZonesLayer) {
        enableRestrictionZones = true;
        $('#enableRestrictionZones').prop("checked", enableRestrictionZones);
    } else return;

    routingControl.route();
};

var _onLayerRemove = function (e) {
    if (indSelf) // event was triggered by panel
        return;

    if (e.layer === truckAttributesLayer) {
        enableTruckAttributes = false;
        $('#enableTruckAttributes').prop("checked", enableTruckAttributes);
    } else if (e.layer === restrictionZonesLayer) {
        enableRestrictionZones = false;
        $('#enableRestrictionZones').prop("checked", enableRestrictionZones);
    } else return;

    routingControl.route();
};

map.on('layeradd', _onLayerAdd, this)
map.on('layerremove', _onLayerRemove, this)

// update the map scenario
var updateScenario = function () {
    scenario = $('#scenarioSelect option:selected').val();
    updateParams(true);
};

// update the routing params
var updateParams = function (updateWayPoints) {
    routingProfile = $('#vehicleType').val();

    enableRestrictionZones = $('#enableRestrictionZones').is(':checked');
    enableTruckAttributes = $('#enableTruckAttributes').is(':checked');

    // sync panel->layers
    indSelf = true;

    if (enableTruckAttributes)
        map.addLayer(truckAttributesLayer);
    else
        map.removeLayer(truckAttributesLayer);

    if (enableRestrictionZones)
        map.addLayer(restrictionZonesLayer);
    else
        map.removeLayer(restrictionZonesLayer);

    indSelf = false;

    if (updateWayPoints)
        routingControl.setWaypoints(getPlan());
    routingControl._router.options.numberOfAlternatives = 0;
    routingControl.route();
};<|endoftext|>


<commit_before>import "./";
import "../vector/";
import "../constants/earth";

orb.transformations.fixedToTopocentric = function(x, L, B, h, a, e, nwu) {

  if ( !a ) a = orb.constants.earth.a;
  if ( !e ) e = orb.constants.earth.e;

  var xObserver = orb.transformations.geodeticToCartesian(L, B, h, a, e);

  var Δx = x.map(function(xi, i) {
    return xi - xObserver[i];
  });

  var rTopo;

  if ( nwu ) {

  rTopo = orb.v.mm(
      orb.v.r( pi/2 - B, 2),
      orb.v.r( L, 3)
    );

  } else {

    rTopo = orb.v.mm(
        orb.v.q(1), orb.v.mm(
          orb.v.r( pi/2 - B, 2),
          orb.v.r( L, 3)
        )
      );

  }

  return orb.v.mm( rTopo, Δx );

};
<commit_msg>[FIX] replaced pi with Math.PI<commit_after>import "./";
import "../vector/";
import "../constants/earth";

orb.transformations.fixedToTopocentric = function(x, L, B, h, a, e, nwu) {

  if ( !a ) a = orb.constants.earth.a;
  if ( !e ) e = orb.constants.earth.e;

  var xObserver = orb.transformations.geodeticToCartesian(L, B, h, a, e);

  var Δx = x.map(function(xi, i) {
    return xi - xObserver[i];
  });

  var rTopo;

  if ( nwu ) {

    rTopo = orb.v.mm(
        orb.v.r( Math.PI/2 - B, 2),
        orb.v.r( L, 3)
      );

  } else {

    rTopo = orb.v.mm(
        orb.v.q(1), orb.v.mm(
          orb.v.r( Math.PI/2 - B, 2),
          orb.v.r( L, 3)
        )
      );

  }

  return orb.v.mm( rTopo, Δx );

};
<|endoftext|>


<commit_before>// require jquery/min/2.2.0
// require jquery
// require ./autocomplete

var
    jQuery;

(function ($) {
    "use strict";

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $.extend({

        prototype: {

            abstractSelect: function (args) {
                var
                    self = this,
                    caption,
                    captionText,
                    listPanel,
                    list,
                    select,
                    wrapper,

                    build = function (collection) {
                        // wrapper = collection.parent(".esphinx.ui.select");
                        wrapper = collection.parent(CSS_CLASS_QUERY + ".select");
                        select = wrapper.find("select");
                        list = wrapper.find("ul.list");

                        var
                            options = select.find("option"),
                            captionText = wrapper
                                .find(".caption .text"),
                            li,
                            option;

                        options.each(function (tag) {
                            option = $(tag);
                            li = $("

");

                            li.attr("data-value", option.attr("value"));
                            li.text(option.text());
                            list.append(li);

                            if (option.attr("selected")) {
                                captionText.text(option.text());
                            }
                        });

                    },

                    toggleCaptionClass = function (collection) {
                        collection.toggleClass("arrow-expanded",
                            "arrow-retracted");
                    },

                    //select onclick
                    setActionToSelect = function (collection) {
                        var
                            value,
                            selected;

                        collection.find("li").on("click", function () {
                            // wrapper = collection.parent(".esphinx.ui.select");
                            wrapper = collection
                                .parent(CSS_CLASS_QUERY + ".select");
                            caption = wrapper.find(".caption");
                            value = $(this).data("value");
                            select = wrapper.find("select");
                            captionText = wrapper
                                .find(".caption .text");

                            // remove selection
                            select.find("option:checked")
                                .unselect();

                            selected = select
                                .find("option[value='" + value + "']")
                                .select();

                            captionText.text(selected.text());

                            // hide options
                            wrapper.find(".options-panel").hide();

                            toggleCaptionClass(caption);
                        });
                    },

                    buildOptionsWithSearch = function (collection) {
                        var
                            target,
                            optionsBox,
                            searchBox,
                            searchTextBox,
                            options,
                            foundsList;

                        collection.each(function (select) {
                            // optionsBox = $(select).parent(".esphinx.ui.select")
                            optionsBox = $(select)
                                .parent(CSS_CLASS_QUERY + ".select")
                                .find(".options-panel");

                            searchBox = $("

");
                            searchBox.addClass("search-box");
                            searchTextBox = $("<input></input>");
                            searchTextBox.attr("type", "text");
                            searchBox.append(searchTextBox);

                            optionsBox.prepend(searchBox);
                            options = optionsBox.find("ul.list li");

                            searchTextBox.autocomplete(options, args.search,
                                function (found) {
                                    // target
                                    target = this;
                                    optionsBox = target
                                        .parent(".options-panel");
                                    options = optionsBox
                                        .find("ul.list li");

                                    if (optionsBox
                                        .find("ul.list-built-found")
                                        .length) {
                                        foundsList = optionsBox
                                            .find(".list-built-found");
                                        foundsList.deflate();
                                    } else {
                                        foundsList = $("

")
                                            .addClass("list-built-found");
                                        optionsBox.append(foundsList);
                                    }

                                    if (target.value()) {
                                        options.parent().hide();
                                        found.each(function (li) {
                                            foundsList.append(li);
                                        });
                                        foundsList.show();

                                        setActionToSelect(foundsList);

                                    } else {
                                        options.parent().show();
                                        foundsList.hide();
                                    }
                            });

                        });

                    };

                // click out
                $(document).on("click", function (e) {
                    var
                        // wrapper = $(".esphinx.ui.select"),
                        wrapper = $(CSS_CLASS_QUERY + ".select"),
                        optionsBoxes = wrapper.find(".options-panel"),
                        captions = wrapper.find(".caption");

                    // if (!$(e.target).parent(".esphinx.ui.select").any()) {
                    if (!$(e.target).parent(CSS_CLASS_QUERY + ".select")
                        .any()) {
                        if (optionsBoxes.visible()) {
                            optionsBoxes.hide();
                            captions.removeClass("arrow-expanded");
                            captions.addClass("arrow-retracted");
                        }

                    }
                });

                $(this).each(function (select) {
                    select = $(select);
                    select.hide();
                    wrapper = $("

");
                    wrapper.addClass(CSS_CLASS + " select");
                    select.parent().append(wrapper);
                    wrapper.append(select);

                    caption = $("

");
                    captionText = $("

");
                    listPanel = $("

");

                    list = $("

");

                    caption.addClass("caption arrow-retracted");
                    captionText.addClass("text");
                    listPanel.addClass("options-panel");
                    list.addClass("list");

                    wrapper.append(caption);
                    caption.append(captionText);
                    wrapper.append(listPanel);
                    listPanel.append(list);

                    build(list);

                    // toggle
                    caption.on("click", function () {
                        // wrapper = $(this).parent(".esphinx.ui.select");
                        wrapper = $(this).parent(CSS_CLASS_QUERY + ".select");
                        wrapper.find(".options-panel").toggle();
                        toggleCaptionClass($(this));
                    });

                    setActionToSelect(list);
                });

                if (args) {
                    if (args.search) {
                        buildOptionsWithSearch(self);
                    }
                }

                return self;

            }

        }

    });

})(esPhinx);
<commit_msg>final code to select<commit_after>// require jquery/min/2.2.0
// require jquery
// require ./autocomplete

var
    jQuery;

(function ($) {
    "use strict";

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    $.extend({

        prototype: {

            abstractSelect: function (args) {
                var
                    self = this,
                    caption,
                    captionText,
                    listPanel,
                    list,
                    select,
                    wrapper,

                    build = function (collection) {
                        // wrapper = collection.parent(".esphinx.ui.select");
                        wrapper = collection.parent(CSS_CLASS_QUERY + ".select");
                        select = wrapper.find("select");
                        list = wrapper.find("ul.list");

                        var
                            options = select.find("option"),
                            captionText = wrapper
                                .find(".caption .text"),
                            li,
                            option;

                        options.each(function (tag) {
                            option = $(tag);
                            li = $("

");

                            li.attr("data-value", option.attr("value"));
                            li.text(option.text());
                            list.append(li);

                            if (option.attr("selected")) {
                                captionText.text(option.text());
                            }
                        });

                    },

                    toggleCaptionClass = function (collection) {
                        collection.toggleClass("arrow-expanded",
                            "arrow-retracted");
                    },

                    //select onclick
                    bindFoundsListEventListener = function (collection) {
                        var
                            value,
                            selected;

                        collection.find("li").on("click", function () {
                            // wrapper = collection.parent(".esphinx.ui.select");
                            wrapper = collection
                                .parent(CSS_CLASS_QUERY + ".select");
                            caption = wrapper.find(".caption");
                            value = $(this).data("value");
                            select = wrapper.find("select");
                            captionText = wrapper
                                .find(".caption .text");

                            // remove selection
                            select.find("option:checked")
                                .unselect();

                            selected = select
                                .find("option[value='" + value + "']")
                                .select();

                            captionText.text(selected.text());

                            // hide options
                            wrapper.find(".options-panel").hide();

                            toggleCaptionClass(caption);
                        });
                    },

                    buildOptionsWithSearch = function (collection) {
                        var
                            target,
                            optionsPanel,
                            searchBox,
                            searchTextBox,
                            options,
                            foundsList,
                            panel;

                        collection.each(function (select) {
                            optionsPanel = $(select)
                                .parent(CSS_CLASS_QUERY + ".select")
                                .find(".options-panel");

                            searchBox = $("

");
                            searchBox.addClass("search-box");
                            searchTextBox = $("<input></input>");
                            searchTextBox.attr("type", "text");
                            searchBox.append(searchTextBox);

                            optionsPanel.prepend(searchBox);
                            options = optionsPanel.find("ul.list li");

                            searchTextBox.autocomplete(options, args.search,
                                function (found) {
                                panel = $.ui.panels.autocomplete.new(this, found);
                                bindFoundsListEventListener(panel.foundsList);
                            });

                        });

                    };

                // click out
                $(document).on("click", function (e) {
                    var
                        // wrapper = $(".esphinx.ui.select"),
                        wrapper = $(CSS_CLASS_QUERY + ".select"),
                        optionsPaneles = wrapper.find(".options-panel"),
                        captions = wrapper.find(".caption");

                    // if (!$(e.target).parent(".esphinx.ui.select").any()) {
                    if (!$(e.target).parent(CSS_CLASS_QUERY + ".select")
                        .any()) {
                        if (optionsPaneles.visible()) {
                            optionsPaneles.hide();
                            captions.removeClass("arrow-expanded");
                            captions.addClass("arrow-retracted");
                        }

                    }
                });

                $(this).each(function (select) {
                    select = $(select);
                    select.hide();
                    wrapper = $("

");
                    wrapper.addClass(CSS_CLASS + " select");
                    select.parent().append(wrapper);
                    wrapper.append(select);

                    caption = $("

");
                    captionText = $("

");
                    listPanel = $("

");

                    list = $("

");

                    caption.addClass("caption arrow-retracted");
                    captionText.addClass("text");
                    listPanel.addClass("options-panel");
                    list.addClass("list");

                    wrapper.append(caption);
                    caption.append(captionText);
                    wrapper.append(listPanel);
                    listPanel.append(list);

                    build(list);

                    // toggle
                    caption.on("click", function () {
                        // wrapper = $(this).parent(".esphinx.ui.select");
                        wrapper = $(this).parent(CSS_CLASS_QUERY + ".select");
                        wrapper.find(".options-panel").toggle();
                        toggleCaptionClass($(this));
                    });

                    bindFoundsListEventListener(list);
                });

                if (args) {
                    if (args.search) {
                        buildOptionsWithSearch(self);
                    }
                }

                return self;

            }

        }

    });

})(esPhinx);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  function deep (d) {
    d.addEventListener('DOMContentLoaded', function () {
      var a = $.$('#skip-ad', d.document);
      if (a) {
        $.openLink(a.href);
      }
    });
  }

  $.register({
    rule: {
      host: /^coinurl\.com|cur\.lv$/,
    },
    ready: function () {
      var d = unsafeWindow.frames[0];
      if (d) {
        deep(d);
        return;
      }
      var o = new MutationObserver(function (mutations) {
        o.disconnect();
        var d = unsafeWindow.frames[0];
        d.addEventListener('DOMContentLoaded', function () {
          d = d.frames[0];
          deep(d);
        });
      });
      o.observe(document.body, {
        childList: true,
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Fix for coinurl<commit_after>(function () {
  'use strict';

  $.register({
    rule: {
      host: /^(?:(\w+)\.)?(coinurl\.com|cur\.lv)$/,
      path: /^\/[-\w]+$/
    },
    ready: function (m) {
      $.removeNodes('iframe');
      if (m.host[1] == null) {
        var mainFrame = 'http://cur.lv/redirect_curlv.php?code=' + escape(document.location.pathname.substring(1));
      } else {
        var mainFrame = 'http://cur.lv/redirect_curlv.php?zone=' + m.host[1] + '&name=' + escape(document.location.pathname.substring(1));
      }
      // Retrieve the main frame
      $.get(mainFrame, {},
        function(mainFrameContent) {
          try {
            // Convert it to HTML nodes
            var docMainFrame = $.toDOM(mainFrameContent);
          } catch (e) {
            throw new _.NoPicAdsError('main frame changed');
          }

          // Regex allowing to extract the link from a subframe
          var rExtractLink = /onclick="open_url\('([^']+)',\s*'go'\)/;

          // Iterate each frame
          var innerFrames = $.$$('frameset > frame', docMainFrame).each(
            function(currFrame) {

              // Fix the host of the frame
              var currFrameAddr = currFrame.src.replace(location.hostname,m.host[2]);

              // Get the content of the current frame
              $.get(currFrameAddr, {},
                function(currFrameContent) {

                  // Try to find the link in the current frame
                  var aRealLink = rExtractLink.exec(currFrameContent);

                  // Could not find it? Try to find it in the next frame
                  if (aRealLink == null || aRealLink[1] == null) {return;}

                  // Otherwise redirect to the link
                  var realLink = aRealLink[1];
                  $.openLink(realLink);
                }
              );
          });
        }
      );
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;<|endoftext|>


<commit_before>/* @flow */

import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import Colors from '../../Colors';
import Card from './Card';
import CardTitle from './CardTitle';
import DiscussionSummary from './DiscussionSummary';
import DiscussionFooter from './DiscussionFooter';
import TouchFeedback from './TouchFeedback';
import Modal from './Modal';
import Icon from './Icon';
import Share from '../../modules/Share';
import NavigationActions from '../../navigation-rfc/Navigation/NavigationActions';
import { convertRouteToURL } from '../../../lib/Route';
import { config } from '../../../core-client';
import { TAG_POST_HIDDEN } from '../../../lib/Constants';
import type { Thread } from '../../../lib/schemaTypes';

const {
	Clipboard,
	Linking,
	ToastAndroid,
	StyleSheet,
	TouchableOpacity,
	View,
} = ReactNative;

const styles = StyleSheet.create({
	item: {
		marginHorizontal: 16,
	},

	footer: {
		marginTop: 8,
		marginBottom: 12,
	},

	topArea: {
		flexDirection: 'row',
	},

	title: {
		flex: 1,
		marginTop: 16,
	},

	expand: {
		marginHorizontal: 16,
		marginVertical: 12,
		color: Colors.fadedBlack,
	},

	hidden: {
		opacity: 0.3,
	},
});

type Props = {
	thread: Thread;
	isUserAdmin: boolean;
	hideThread: Function;
	unhideThread: Function;
	banUser: Function;
	unbanUser: Function;
	onNavigation: Function;
}

export default class DiscussionItem extends Component<void, Props, void> {
	static propTypes = {
		thread: PropTypes.shape({
			id: PropTypes.string.isRequired,
			name: PropTypes.string.isRequired,
			body: PropTypes.string.isRequired,
			creator: PropTypes.string.isRequired,
			parents: PropTypes.arrayOf(PropTypes.string).isRequired,
		}).isRequired,
		onNavigation: PropTypes.func.isRequired,
		isUserAdmin: PropTypes.bool,
		hideThread: PropTypes.func.isRequired,
		unhideThread: PropTypes.func.isRequired,
		banUser: PropTypes.func.isRequired,
		unbanUser: PropTypes.func.isRequired,
	};

	shouldComponentUpdate(nextProps: Props): boolean {
		return !shallowEqual(this.props, nextProps);
	}

	_copyToClipboard: Function = text => {
		Clipboard.setString(text);
		ToastAndroid.show('Copied to clipboard', ToastAndroid.SHORT);
	};

	_handleShowMenu: Function = () => {
		const { thread } = this.props;
		const menu = {};

		menu['Copy title'] = () => this._copyToClipboard(thread.name);

		const { meta } = thread;

		if (meta && meta.type === 'photo') {
			menu['Open image in browser'] = () => Linking.openURL(meta.url);
			menu['Copy image link'] = () => this._copyToClipboard(meta.url);
		} else {
			menu['Copy summary'] = () => this._copyToClipboard(thread.body);
		}

		menu['Share discussion'] = () => {
			Share.shareItem('Share discussion', config.server.protocol + '//' + config.server.host + convertRouteToURL({
				name: 'chat',
				props: {
					room: thread.parents[0],
					thread: thread.id,
					title: thread.name,
				},
			}));
		};

		if (this.props.isUserAdmin) {
			if (thread.tags && thread.tags.indexOf(TAG_POST_HIDDEN) > -1) {
				menu['Unhide discussion'] = () => this.props.unhideThread();
			} else {
				menu['Hide discussion'] = () => this.props.hideThread();
			}
		}

		Modal.showActionSheetWithItems(menu);
	};

	_handlePress: Function = () => {
		const { thread } = this.props;

		this.props.onNavigation(new NavigationActions.Push({
			name: 'chat',
			props: {
				thread: thread.id,
				room: thread.parents[0],
			},
		}));
	};

	render() {
		const {
			thread,
		} = this.props;

		const hidden = thread.tags && thread.tags.indexOf(TAG_POST_HIDDEN) > -1;

		return (
			<Card {...this.props}>
				<TouchFeedback onPress={this._handlePress}>
					<View style={hidden ? styles.hidden : null}>
						<View style={styles.topArea}>
							<CardTitle style={[ styles.item, styles.title ]}>
								{this.props.thread.name}
							</CardTitle>

							<TouchableOpacity onPress={this._handleShowMenu}>
								<Icon
									name='expand-more'
									style={styles.expand}
									size={20}
								/>
							</TouchableOpacity>
						</View>

						<DiscussionSummary text={thread.body} meta={thread.meta} />
						<DiscussionFooter { ...this.props } style={[ styles.item, styles.footer ]} />
					</View>
				</TouchFeedback>
			</Card>
		);
	}
}
<commit_msg>fix(ui): and temporary fix for invalid threads<commit_after>/* @flow */

import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import Colors from '../../Colors';
import Card from './Card';
import CardTitle from './CardTitle';
import DiscussionSummary from './DiscussionSummary';
import DiscussionFooter from './DiscussionFooter';
import TouchFeedback from './TouchFeedback';
import Modal from './Modal';
import Icon from './Icon';
import Share from '../../modules/Share';
import NavigationActions from '../../navigation-rfc/Navigation/NavigationActions';
import { convertRouteToURL } from '../../../lib/Route';
import { config } from '../../../core-client';
import { TAG_POST_HIDDEN } from '../../../lib/Constants';
import type { Thread } from '../../../lib/schemaTypes';

const {
	Clipboard,
	Linking,
	ToastAndroid,
	StyleSheet,
	TouchableOpacity,
	View,
} = ReactNative;

const styles = StyleSheet.create({
	item: {
		marginHorizontal: 16,
	},

	footer: {
		marginTop: 8,
		marginBottom: 12,
	},

	topArea: {
		flexDirection: 'row',
	},

	title: {
		flex: 1,
		marginTop: 16,
	},

	expand: {
		marginHorizontal: 16,
		marginVertical: 12,
		color: Colors.fadedBlack,
	},

	hidden: {
		opacity: 0.3,
	},
});

type Props = {
	thread: Thread;
	isUserAdmin: boolean;
	hideThread: Function;
	unhideThread: Function;
	banUser: Function;
	unbanUser: Function;
	onNavigation: Function;
}

export default class DiscussionItem extends Component<void, Props, void> {
	static propTypes = {
		thread: PropTypes.shape({
			id: PropTypes.string.isRequired,
			name: PropTypes.string.isRequired,
			body: PropTypes.string.isRequired,
			creator: PropTypes.string.isRequired,
			parents: PropTypes.arrayOf(PropTypes.string).isRequired,
		}).isRequired,
		onNavigation: PropTypes.func.isRequired,
		isUserAdmin: PropTypes.bool,
		hideThread: PropTypes.func.isRequired,
		unhideThread: PropTypes.func.isRequired,
		banUser: PropTypes.func.isRequired,
		unbanUser: PropTypes.func.isRequired,
	};

	shouldComponentUpdate(nextProps: Props): boolean {
		return !shallowEqual(this.props, nextProps);
	}

	_copyToClipboard: Function = text => {
		Clipboard.setString(text);
		ToastAndroid.show('Copied to clipboard', ToastAndroid.SHORT);
	};

	_handleShowMenu: Function = () => {
		const { thread } = this.props;
		const menu = {};

		menu['Copy title'] = () => this._copyToClipboard(thread.name);

		const { meta } = thread;

		if (meta && meta.type === 'photo') {
			menu['Open image in browser'] = () => Linking.openURL(meta.url);
			menu['Copy image link'] = () => this._copyToClipboard(meta.url);
		} else {
			menu['Copy summary'] = () => this._copyToClipboard(thread.body);
		}

		menu['Share discussion'] = () => {
			Share.shareItem('Share discussion', config.server.protocol + '//' + config.server.host + convertRouteToURL({
				name: 'chat',
				props: {
					room: thread.parents[0],
					thread: thread.id,
					title: thread.name,
				},
			}));
		};

		if (this.props.isUserAdmin) {
			if (thread.tags && thread.tags.indexOf(TAG_POST_HIDDEN) > -1) {
				menu['Unhide discussion'] = () => this.props.unhideThread();
			} else {
				menu['Hide discussion'] = () => this.props.hideThread();
			}
		}

		Modal.showActionSheetWithItems(menu);
	};

	_handlePress: Function = () => {
		const { thread } = this.props;

		this.props.onNavigation(new NavigationActions.Push({
			name: 'chat',
			props: {
				thread: thread.id,
				room: thread.parents[0],
			},
		}));
	};

	render() {
		const {
			thread,
		} = this.props;

		// FIXME: temporary check to avoid crash
		if (!(thread && thread.body && thread.name)) {
			return null;
		}

		const hidden = thread.tags && thread.tags.indexOf(TAG_POST_HIDDEN) > -1;

		return (
			<Card {...this.props}>
				<TouchFeedback onPress={this._handlePress}>
					<View style={hidden ? styles.hidden : null}>
						<View style={styles.topArea}>
							<CardTitle style={[ styles.item, styles.title ]}>
								{this.props.thread.name}
							</CardTitle>

							<TouchableOpacity onPress={this._handleShowMenu}>
								<Icon
									name='expand-more'
									style={styles.expand}
									size={20}
								/>
							</TouchableOpacity>
						</View>

						<DiscussionSummary text={thread.body} meta={thread.meta} />
						<DiscussionFooter {...this.props} style={[ styles.item, styles.footer ]} />
					</View>
				</TouchFeedback>
			</Card>
		);
	}
}
<|endoftext|>


<commit_before>//组件信息
var info = {
    groupId: "${project.groupId}",
    artifactId: "${project.artifactId}",
    version: "${project.version}",
    website: "https://github.com/hs-web/hsweb-framework",
    author: "admin@hsweb.me",
    comment: "文件信息"
};

//版本更新信息
var versions = [
    // {
    //     version: "3.0.2",
    //     upgrade: function (context) {
    //         java.lang.System.out.println("更新到3.0.2了");
    //     }
    // }
];
var JDBCType = java.sql.JDBCType;
function install(context) {
    var database = context.database;
    database.createOrAlter("s_file_info")
        .addColumn().name("u_id").alias("id").comment("ID").jdbcType(java.sql.JDBCType.VARCHAR).length(32).primaryKey().commit()
        .addColumn().name("name").alias("name").comment("文件名称").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .addColumn().name("location").alias("location").comment("文件相对路径").jdbcType(java.sql.JDBCType.VARCHAR).length(1024).commit()
        .addColumn().name("type").alias("type").comment("类型").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .addColumn().name("md5").alias("md5").comment("md5校验值").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .addColumn().name("size").alias("size").comment("文件大小").jdbcType(java.sql.JDBCType.DECIMAL).length(32, 0).commit()
        .addColumn().name("status").alias("status").comment("状态").jdbcType(java.sql.JDBCType.DECIMAL).length(4, 0).commit()
        .addColumn().name("classified").alias("classified").comment("分类").jdbcType(java.sql.JDBCType.VARCHAR).length(32).commit()
        .addColumn().name("create_time").alias("create_time").comment("创建时间").jdbcType(java.sql.JDBCType.NUMERIC).length(32,0).commit()
        .addColumn().name("creator_id").alias("creatorId").comment("创建人").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .index().name("idx_file_md5").column("md5").commit()
        .index().name("idx_file_creator_id").column("creator_id").commit()

        .comment("文件信息").commit();
}
//设置依赖
dependency.setup(info)
    .onInstall(install)
    .onUpgrade(function (context) { //更新时执行
        var upgrader = context.upgrader;
        upgrader.filter(versions)
            .upgrade(function (newVer) {
                newVer.upgrade(context);
            });
    })
    .onUninstall(function (context) { //卸载时执行

    });<commit_msg>md5 varchar(128)<commit_after>//组件信息
var info = {
    groupId: "${project.groupId}",
    artifactId: "${project.artifactId}",
    version: "${project.version}",
    website: "https://github.com/hs-web/hsweb-framework",
    author: "admin@hsweb.me",
    comment: "文件信息"
};

//版本更新信息
var versions = [
    // {
    //     version: "3.0.2",
    //     upgrade: function (context) {
    //         java.lang.System.out.println("更新到3.0.2了");
    //     }
    // }
];
var JDBCType = java.sql.JDBCType;
function install(context) {
    var database = context.database;
    database.createOrAlter("s_file_info")
        .addColumn().name("u_id").alias("id").comment("ID").jdbcType(java.sql.JDBCType.VARCHAR).length(32).primaryKey().commit()
        .addColumn().name("name").alias("name").comment("文件名称").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .addColumn().name("location").alias("location").comment("文件相对路径").jdbcType(java.sql.JDBCType.VARCHAR).length(1024).commit()
        .addColumn().name("type").alias("type").comment("类型").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .addColumn().name("md5").alias("md5").comment("md5校验值").jdbcType(java.sql.JDBCType.VARCHAR).length(128).commit()
        .addColumn().name("size").alias("size").comment("文件大小").jdbcType(java.sql.JDBCType.DECIMAL).length(32, 0).commit()
        .addColumn().name("status").alias("status").comment("状态").jdbcType(java.sql.JDBCType.DECIMAL).length(4, 0).commit()
        .addColumn().name("classified").alias("classified").comment("分类").jdbcType(java.sql.JDBCType.VARCHAR).length(32).commit()
        .addColumn().name("create_time").alias("create_time").comment("创建时间").jdbcType(java.sql.JDBCType.NUMERIC).length(32,0).commit()
        .addColumn().name("creator_id").alias("creatorId").comment("创建人").jdbcType(java.sql.JDBCType.VARCHAR).length(256).commit()
        .index().name("idx_file_md5").column("md5").commit()
        .index().name("idx_file_creator_id").column("creator_id").commit()

        .comment("文件信息").commit();
}
//设置依赖
dependency.setup(info)
    .onInstall(install)
    .onUpgrade(function (context) { //更新时执行
        var upgrader = context.upgrader;
        upgrader.filter(versions)
            .upgrade(function (newVer) {
                newVer.upgrade(context);
            });
    })
    .onUninstall(function (context) { //卸载时执行

    });<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2021  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.18.0');
		this.setClientTag('node:21-03-04');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2021  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.18.0');
		this.setClientTag('node:21-03-05');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>const { setWorldConstructor, Given, When, Then } = require('cucumber')
const path = require('path')
const ks = require('node-key-sender')
const Application = require('spectron').Application
const $ = require('cheerio')
const jetpack = require('fs-jetpack')
const { git, clone } = require('../../app/lib/git')

const appPath = path.join(__dirname, '../../app')
const homeDir = path.join(__dirname, '../../test/fixtures/home')
const pluginDir = path.join(homeDir, '.zazu/plugins')
const calcProfile = path.join(homeDir, '.calculator.zazurc.json')
const fallbackProfile = path.join(homeDir, '.fallback.zazurc.json')
const homeProfile = path.join(homeDir, '.zazurc.json')

class World {
  profile (name) {
    this.profileType = name
    if (this.profileType === 'calculator') {
      jetpack.copy(calcProfile, homeProfile, { overwrite: true })
    } else if (this.profileType === 'fallback') {
      jetpack.copy(fallbackProfile, homeProfile, { overwrite: true })
    }
    this.app = new Application({
      path: require('electron'),
      args: [appPath],
      env: {
        NODE_ENV: 'test',
        ZAZU_HOME: homeDir,
      },
    })
    return Promise.resolve()
  }

  open () {
    return this.app.start().then(() => {
      const time = this.profileType === 'calculator' ? 50 * 1000 : 5 * 1000
      return wait(time) // give it time to load plugins
    })
  }

  isWindowVisible () {
    return this.app.browserWindow.isVisible()
  }

  hasResults () {
    return this.app.client.isExisting('.results')
  }

  accessibility () {
    return this.app.client.auditAccessibility()
  }

  updatePlugins () {
    return this.app.webContents.send('updatePlugins').then(() => {
      return wait(10 * 1000) // give it time to update the plugin
    })
  }

  getQuery () {
    return this.app.client.getValue('input')
  }

  type (input) {
    this.app.client.setValue('input', input)
  }

  showWindow () {
    return Promise.resolve(this.hitHotkey('space', 'shift'))
  }

  hideWindow () {
    return Promise.resolve(this.hitHotkey('space', 'shift'))
  }

  hitHotkey (key, modifier) {
    if (modifier) {
      return ks.sendCombination([modifier, key])
    }
    return ks.sendKey(key)
  }

  close () {
    if (this.app) {
      return this.app.stop()
    }
    return Promise.resolve()
  }

  clickActiveResult () {
    return this.app.client.click('li.active')
  }

  getActiveHeader () {
    return this.app.client.getText('li.active h2')
  }

  getResults () {
    return this.app.client.getText('.results')
  }

  getResultItems () {
    return this.app.client.getHTML('.results').then(results => {
      return $(results).find('li')
    })
  }

  readClipboard () {
    return this.app.electron.clipboard.readText()
  }
}

const wait = time => {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

const eventually = (func, expectedValue) => {
  const assert = actualValue => {
    if (actualValue !== expectedValue) {
      throw new Error('Values didnt match')
    }
  }
  return new Promise((resolve, reject) => {
    let iterations = 0
    const retry = () => {
      iterations++
      if (iterations >= 50) {
        reject(new Error('Forever is a long time'))
      } else {
        func()
          .then(assert)
          .then(resolve)
          .catch(() => {
            return wait(100).then(retry)
          })
      }
    }
    retry()
  })
}

setWorldConstructor(World)

Given('I have {string} as a plugin', function (plugin) {
  if (plugin === 'tinytacoteam/zazu-fixture') {
    return this.profile('default')
  } else if (plugin === 'tinytacoteam/zazu-calculator') {
    return this.profile('calculator')
  }
  return Promise.reject(new Error('Profile not found'))
})

Given('the app is launched', { timeout: 120 * 1000 }, function () {
  return this.open()
})

Given('I have {string} installed before packagist support', function (plugin) {
  const fallbackDir = path.join(pluginDir, plugin)
  return clone(plugin, fallbackDir)
    .then(() => {
      return git(['reset', '--hard', '16e4e50'], { cwd: fallbackDir })
    })
    .then(() => {
      return this.profile('fallback')
    })
})

Given('I update the plugins', { timeout: 15 * 1000 }, function () {
  return this.updatePlugins()
})

When('I toggle it open', function () {
  return this.showWindow()
})

When('I toggle it closed', function () {
  return this.hideWindow()
})

// assumes modifier is first
When('I hit the hotkey {string}', function (hotkey) {
  var keys = hotkey.split('+')
  return this.hitHotkey(keys[1], keys[0]).then(() => {
    return wait(100)
  })
})

When('I hit the key {string}', function (hotkey) {
  return this.hitHotkey(hotkey).then(() => {
    return wait(100)
  })
})

When('I eventually click on the active result', function () {
  return eventually(() => this.hasResults(), true)
    .then(() => {
      return wait(100)
    })
    .then(() => {
      return this.clickActiveResult()
    })
})

Then('my clipboard contains {string}', function (expected, callback) {
  this.readClipboard().then(actual => {
    if (actual === expected) {
      callback()
    } else {
      callback(new Error('Expected "' + expected + '" to be in your clipbaord but found "' + actual + '"'))
    }
  })
})

Then('the search window is not visible', function () {
  return eventually(() => this.isWindowVisible(), false)
})

Then('the search window is visible', function () {
  return eventually(() => this.isWindowVisible(), true)
})

Then('I have {int} result(s)', function (expected) {
  return eventually(() => {
    return this.getResultItems().then(items => items.length)
  }, parseInt(expected, 10))
})

Then('the input is empty', function () {
  return eventually(() => {
    return this.getQuery()
  }, '')
})

Then('the input is {string}', function (expected) {
  return eventually(() => {
    return this.getQuery()
  }, expected)
})

When('I type in {string}', function (input) {
  this.type(input)
  return eventually(() => {
    return this.getQuery()
  }, input)
})

Then('I have no results', function () {
  return eventually(() => this.hasResults(), false)
})

Then('the active result contains {string}', function (header) {
  return eventually(() => this.hasResults(), true)
    .then(() => {
      return wait(100)
    })
    .then(() => {
      return eventually(() => this.getActiveHeader(), header)
    })
})

Then('I have no accessibility warnings', function () {
  return this.accessibility().then(response => {
    if (response.results.length !== 0) {
      throw new Error('You have accessibility issues')
    }
  })
})

Then('the results contain {string}', function (subset, callback) {
  this.getResults().then(resultText => {
    if (resultText.match(subset)) {
      callback()
    } else {
      callback(new Error('Expected results to contain "' + subset + '"'))
    }
  })
})
<commit_msg>refactor: no need to manually add promise<commit_after>const { setWorldConstructor, Given, When, Then } = require('cucumber')
const path = require('path')
const ks = require('node-key-sender')
const Application = require('spectron').Application
const $ = require('cheerio')
const jetpack = require('fs-jetpack')
const { git, clone } = require('../../app/lib/git')

const appPath = path.join(__dirname, '../../app')
const homeDir = path.join(__dirname, '../../test/fixtures/home')
const pluginDir = path.join(homeDir, '.zazu/plugins')
const calcProfile = path.join(homeDir, '.calculator.zazurc.json')
const fallbackProfile = path.join(homeDir, '.fallback.zazurc.json')
const homeProfile = path.join(homeDir, '.zazurc.json')

class World {
  profile (name) {
    this.profileType = name
    if (this.profileType === 'calculator') {
      jetpack.copy(calcProfile, homeProfile, { overwrite: true })
    } else if (this.profileType === 'fallback') {
      jetpack.copy(fallbackProfile, homeProfile, { overwrite: true })
    }
    this.app = new Application({
      path: require('electron'),
      args: [appPath],
      env: {
        NODE_ENV: 'test',
        ZAZU_HOME: homeDir,
      },
    })
    return Promise.resolve()
  }

  open () {
    return this.app.start().then(() => {
      const time = this.profileType === 'calculator' ? 50 * 1000 : 5 * 1000
      return wait(time) // give it time to load plugins
    })
  }

  isWindowVisible () {
    return this.app.browserWindow.isVisible()
  }

  hasResults () {
    return this.app.client.isExisting('.results')
  }

  accessibility () {
    return this.app.client.auditAccessibility()
  }

  updatePlugins () {
    return this.app.webContents.send('updatePlugins').then(() => {
      return wait(10 * 1000) // give it time to update the plugin
    })
  }

  getQuery () {
    return this.app.client.getValue('input')
  }

  type (input) {
    this.app.client.setValue('input', input)
  }

  showWindow () {
    return this.hitHotkey('space', 'shift')
  }

  hideWindow () {
    return this.hitHotkey('space', 'shift')
  }

  hitHotkey (key, modifier) {
    if (modifier) {
      return ks.sendCombination([modifier, key])
    }
    return ks.sendKey(key)
  }

  close () {
    if (this.app) {
      return this.app.stop()
    }
    return Promise.resolve()
  }

  clickActiveResult () {
    return this.app.client.click('li.active')
  }

  getActiveHeader () {
    return this.app.client.getText('li.active h2')
  }

  getResults () {
    return this.app.client.getText('.results')
  }

  getResultItems () {
    return this.app.client.getHTML('.results').then(results => {
      return $(results).find('li')
    })
  }

  readClipboard () {
    return this.app.electron.clipboard.readText()
  }
}

const wait = time => {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

const eventually = (func, expectedValue) => {
  const assert = actualValue => {
    if (actualValue !== expectedValue) {
      throw new Error('Values didnt match')
    }
  }
  return new Promise((resolve, reject) => {
    let iterations = 0
    const retry = () => {
      iterations++
      if (iterations >= 50) {
        reject(new Error('Forever is a long time'))
      } else {
        func()
          .then(assert)
          .then(resolve)
          .catch(() => {
            return wait(100).then(retry)
          })
      }
    }
    retry()
  })
}

setWorldConstructor(World)

Given('I have {string} as a plugin', function (plugin) {
  if (plugin === 'tinytacoteam/zazu-fixture') {
    return this.profile('default')
  } else if (plugin === 'tinytacoteam/zazu-calculator') {
    return this.profile('calculator')
  }
  return Promise.reject(new Error('Profile not found'))
})

Given('the app is launched', { timeout: 120 * 1000 }, function () {
  return this.open()
})

Given('I have {string} installed before packagist support', function (plugin) {
  const fallbackDir = path.join(pluginDir, plugin)
  return clone(plugin, fallbackDir)
    .then(() => {
      return git(['reset', '--hard', '16e4e50'], { cwd: fallbackDir })
    })
    .then(() => {
      return this.profile('fallback')
    })
})

Given('I update the plugins', { timeout: 15 * 1000 }, function () {
  return this.updatePlugins()
})

When('I toggle it open', function () {
  return this.showWindow()
})

When('I toggle it closed', function () {
  return this.hideWindow()
})

// assumes modifier is first
When('I hit the hotkey {string}', function (hotkey) {
  var keys = hotkey.split('+')
  return this.hitHotkey(keys[1], keys[0]).then(() => {
    return wait(100)
  })
})

When('I hit the key {string}', function (hotkey) {
  return this.hitHotkey(hotkey).then(() => {
    return wait(100)
  })
})

When('I eventually click on the active result', function () {
  return eventually(() => this.hasResults(), true)
    .then(() => {
      return wait(100)
    })
    .then(() => {
      return this.clickActiveResult()
    })
})

Then('my clipboard contains {string}', function (expected, callback) {
  this.readClipboard().then(actual => {
    if (actual === expected) {
      callback()
    } else {
      callback(new Error('Expected "' + expected + '" to be in your clipbaord but found "' + actual + '"'))
    }
  })
})

Then('the search window is not visible', function () {
  return eventually(() => this.isWindowVisible(), false)
})

Then('the search window is visible', function () {
  return eventually(() => this.isWindowVisible(), true)
})

Then('I have {int} result(s)', function (expected) {
  return eventually(() => {
    return this.getResultItems().then(items => items.length)
  }, parseInt(expected, 10))
})

Then('the input is empty', function () {
  return eventually(() => {
    return this.getQuery()
  }, '')
})

Then('the input is {string}', function (expected) {
  return eventually(() => {
    return this.getQuery()
  }, expected)
})

When('I type in {string}', function (input) {
  this.type(input)
  return eventually(() => {
    return this.getQuery()
  }, input)
})

Then('I have no results', function () {
  return eventually(() => this.hasResults(), false)
})

Then('the active result contains {string}', function (header) {
  return eventually(() => this.hasResults(), true)
    .then(() => {
      return wait(100)
    })
    .then(() => {
      return eventually(() => this.getActiveHeader(), header)
    })
})

Then('I have no accessibility warnings', function () {
  return this.accessibility().then(response => {
    if (response.results.length !== 0) {
      throw new Error('You have accessibility issues')
    }
  })
})

Then('the results contain {string}', function (subset, callback) {
  this.getResults().then(resultText => {
    if (resultText.match(subset)) {
      callback()
    } else {
      callback(new Error('Expected results to contain "' + subset + '"'))
    }
  })
})
<|endoftext|>