<commit_before>//----------------------------------------------------------------------
// AdalJS v0.0.4
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
'use strict';

if (typeof module !== 'undefined' && module.exports) {
    var window, localStorage, angular, document, AuthenticationContext;
    module.exports.inject = function (windowInj, localStorageInj, documentInj, MathInj, angularInj, adalInj) {
        window = windowInj;
        localStorage = localStorageInj;
        document = documentInj;
        Math = MathInj; // jshint ignore:line
        angular = angularInj;
        AuthenticationContext = adalInj;
    };
}

(function () {
    // ============= Angular modules- Start =============
    if (angular) {

        var AdalModule = angular.module('AdalAngular', []);

        AdalModule.provider('adalAuthenticationService', function () {
            var _adal = null;
            var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' };

            var updateDataFromCache = function (resource) {
                // only cache lookup here to not interrupt with events
                var token = _adal.getCachedToken(resource);
                _oauthData.isAuthenticated = token !== null && token.length > 0;
                var user = _adal.getCachedUser() || { userName: '' };
                _oauthData.userName = user.userName;
                _oauthData.profile = user.profile;
                _oauthData.loginError = _adal.getLoginError();
            };

            this.init = function (configOptions, httpProvider) {
                if (configOptions) {
                    // redirect and logout_redirect are set to current location by default
                    var existingHash = window.location.hash;
                    var pathDefault = window.location.href;
                    if (existingHash) {
                        pathDefault = pathDefault.replace(existingHash, '');
                    }
                    configOptions.redirectUri = configOptions.redirectUri || pathDefault;
                    configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;

                    if (httpProvider && httpProvider.interceptors) {
                        httpProvider.interceptors.push('ProtectedResourceInterceptor');
                    }

                    // create instance with given config
                    _adal = new AuthenticationContext(configOptions);
                } else {
                    throw new Error('You must set configOptions, when calling init');
                }

                // loginresource is used to set authenticated status
                updateDataFromCache(_adal.config.loginResource);
            };

            // special function that exposes methods in Angular controller
            // $rootScope, $window, $q, $location, $timeout are injected by Angular
            this.$get = ['$rootScope', '$window', '$q', '$location', '$timeout', function ($rootScope, $window, $q, $location, $timeout) {

                var locationChangeHandler = function () {
                    var hash = $window.location.hash;

                    if (_adal.isCallback(hash)) {
                        // callback can come from login or iframe request

                        var requestInfo = _adal.getRequestInfo(hash);
                        _adal.saveTokenFromHash(requestInfo);
                        $window.location.hash = '';

                        if (requestInfo.requestType !== _adal.REQUEST_TYPE.LOGIN) {
                            _adal.callback = $window.parent.AuthenticationContext().callback;
                        }

                        // Return to callback if it is send from iframe
                        if (requestInfo.stateMatch) {
                            if (typeof _adal.callback === 'function') {
                                // Call within the same context without full page redirect keeps the callback
                                if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
                                    // Idtoken or Accestoken can be renewed
                                    if (requestInfo.parameters['access_token']) {
                                        _adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']);
                                        return;
                                    } else if (requestInfo.parameters['id_token']) {
                                        _adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']);
                                        return;
                                    }
                                }
                            } else {
                                // normal full login redirect happened on the page
                                updateDataFromCache(_adal.config.loginResource);
                                if (_oauthData.userName) {
                                    //IDtoken is added as token for the app
                                    $timeout(function () {
                                        updateDataFromCache(_adal.config.loginResource);
                                        $rootScope.userInfo = _oauthData;
                                        // redirect to login requested page
                                        var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.START_PAGE);
                                        if (loginStartPage) {
                                            $location.path(loginStartPage);
                                        }
                                    }, 1);
                                    $rootScope.$broadcast('adal:loginSuccess');
                                } else {
                                    $rootScope.$broadcast('adal:loginFailure', _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION));
                                }
                            }
                        }
                    } else {
                        // No callback. App resumes after closing or moving to new page.
                        // Check token and username
                        updateDataFromCache(_adal.config.loginResource);
                        if (!_adal._renewActive && !_oauthData.isAuthenticated && _oauthData.userName) {
                            if (!_adal._getItem(_adal.CONSTANTS.STORAGE.FAILED_RENEW)) {
                                _adal.acquireToken(_adal.config.loginResource, function (error, tokenOut) {
                                    if (error) {
                                        $rootScope.$broadcast('adal:loginFailure', 'auto renew failure');
                                    } else {
                                        if (tokenOut) {
                                            _oauthData.isAuthenticated = true;
                                        }
                                    }
                                });
                            }
                        }
                    }

                    $timeout(function () {
                        updateDataFromCache(_adal.config.loginResource);
                        $rootScope.userInfo = _oauthData;
                    }, 1);
                };

                var routeChangeHandler = function (e, nextRoute) {
                    if (nextRoute.$$route && nextRoute.$$route.requireADLogin) {
                        if (!_oauthData.isAuthenticated) {
                            console.log('Route change event for:' + nextRoute.$$route.originalPath);
                            if (_adal.config && _adal.config.localLoginUrl) {
                                $location.path(_adal.config.localLoginUrl);
                            } else {
                                // directly start login flow
                                _adal._saveItem(_adal.CONSTANTS.STORAGE.START_PAGE, nextRoute.$$route.originalPath);
                                console.log('Start login at:' + window.location.href);
                                $rootScope.$broadcast('adal:loginRedirect');
                                _adal.login();
                            }
                        }
                    }
                };

                // Route change event tracking to receive fragment and also auto renew tokens
                $rootScope.$on('$routeChangeStart', routeChangeHandler);

                $rootScope.$on('$locationChangeStart', locationChangeHandler);

                updateDataFromCache(_adal.config.loginResource);
                $rootScope.userInfo = _oauthData;

                return {
                    // public methods will be here that are accessible from Controller
                    config: _adal.config,
                    login: function () {
                        _adal.login();
                    },
                    loginInProgress: function () {
                        return _adal.loginInProgress();
                    },
                    logOut: function () {
                        _adal.logOut();
                        //call signout related method
                    },
                    getCachedToken: function (resource) {
                        return _adal.getCachedToken(resource);
                    },
                    userInfo: _oauthData,
                    acquireToken: function (resource) {
                        // automated token request call
                        var deferred = $q.defer();
                        _adal.acquireToken(resource, function (error, tokenOut) {
                            if (error) {
                                _adal._logstatus('err :' + error);
                                deferred.reject(error);
                            } else {
                                deferred.resolve(tokenOut);
                            }
                        });

                        return deferred.promise;
                    },
                    getUser: function () {
                        var deferred = $q.defer();
                        _adal.getUser(function (error, user) {
                            if (error) {
                                _adal._logstatus('err :' + error);
                                deferred.reject(error);
                            } else {
                                deferred.resolve(user);
                            }
                        });

                        return deferred.promise;
                    },
                    getResourceForEndpoint: function (endpoint) {
                        return _adal.getResourceForEndpoint(endpoint);
                    },
                    clearCache: function () {
                        _adal.clearCache();
                    },
                    clearCacheForResource: function (resource) {
                        _adal.clearCacheForResource(resource);
                    }
                };
            }];
        });

        // Interceptor for http if needed
        AdalModule.factory('ProtectedResourceInterceptor', ['adalAuthenticationService', '$q', '$rootScope', function (authService, $q, $rootScope) {

            return {
                request: function (config) {
                    if (config) {

                        // This interceptor needs to load service, but dependeny definition causes circular reference error.
                        // Loading with injector is suggested at github. https://github.com/angular/angular.js/issues/2367

                        config.headers = config.headers || {};

                        var resource = authService.getResourceForEndpoint(config.url);
                        var tokenStored = authService.getCachedToken(resource);
                        if (tokenStored) {
                            // check endpoint mapping if provided
                            config.headers.Authorization = 'Bearer ' + tokenStored;
                            return config;
                        } else {
                            // Cancel request if login is starting
                            if (authService.loginInProgress()) {
                                return $q.reject();
                            } else if (authService.config && resource !== authService.config.clientId) {
                                // external endpoints
                                // delayed request to return after iframe completes
                                var delayedRequest = $q.defer();
                                authService.acquireToken(resource).then(function (token) {
                                    config.headers.Authorization = 'Bearer ' + token;
                                    delayedRequest.resolve(config);
                                }, function (err) {
                                    delayedRequest.reject(err);
                                });

                                return delayedRequest.promise;
                            }
                        }

                        return config;
                    }
                },
                responseError: function (rejection) {
                    if (rejection && rejection.status === 401) {
                        var resource = authService.getResourceForEndpoint(rejection.config.url);
                        authService.clearCacheForResource(resource);
                        $rootScope.$broadcast('adal:notAuthorized', rejection, resource);
                    }

                    return $q.reject(rejection);
                }
            };
        }]);
    } else {
        console.log('Angular.JS is not included');
    }
}());
<commit_msg>refresh token for external endpoints<commit_after>//----------------------------------------------------------------------
// AdalJS v0.0.4
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
'use strict';

if (typeof module !== 'undefined' && module.exports) {
    var window, localStorage, angular, document, AuthenticationContext;
    module.exports.inject = function (windowInj, localStorageInj, documentInj, MathInj, angularInj, adalInj) {
        window = windowInj;
        localStorage = localStorageInj;
        document = documentInj;
        Math = MathInj; // jshint ignore:line
        angular = angularInj;
        AuthenticationContext = adalInj;
    };
}

(function () {
    // ============= Angular modules- Start =============
    if (angular) {

        var AdalModule = angular.module('AdalAngular', []);

        AdalModule.provider('adalAuthenticationService', function () {
            var _adal = null;
            var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' };

            var updateDataFromCache = function (resource) {
                // only cache lookup here to not interrupt with events
                var token = _adal.getCachedToken(resource);
                _oauthData.isAuthenticated = token !== null && token.length > 0;
                var user = _adal.getCachedUser() || { userName: '' };
                _oauthData.userName = user.userName;
                _oauthData.profile = user.profile;
                _oauthData.loginError = _adal.getLoginError();
            };

            this.init = function (configOptions, httpProvider) {
                if (configOptions) {
                    // redirect and logout_redirect are set to current location by default
                    var existingHash = window.location.hash;
                    var pathDefault = window.location.href;
                    if (existingHash) {
                        pathDefault = pathDefault.replace(existingHash, '');
                    }
                    configOptions.redirectUri = configOptions.redirectUri || pathDefault;
                    configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;

                    if (httpProvider && httpProvider.interceptors) {
                        httpProvider.interceptors.push('ProtectedResourceInterceptor');
                    }

                    // create instance with given config
                    _adal = new AuthenticationContext(configOptions);
                } else {
                    throw new Error('You must set configOptions, when calling init');
                }

                // loginresource is used to set authenticated status
                updateDataFromCache(_adal.config.loginResource);
            };

            // special function that exposes methods in Angular controller
            // $rootScope, $window, $q, $location, $timeout are injected by Angular
            this.$get = ['$rootScope', '$window', '$q', '$location', '$timeout', function ($rootScope, $window, $q, $location, $timeout) {

                var locationChangeHandler = function () {
                    var hash = $window.location.hash;

                    if (_adal.isCallback(hash)) {
                        // callback can come from login or iframe request

                        var requestInfo = _adal.getRequestInfo(hash);
                        _adal.saveTokenFromHash(requestInfo);
                        $window.location.hash = '';

                        if (requestInfo.requestType !== _adal.REQUEST_TYPE.LOGIN) {
                            _adal.callback = $window.parent.AuthenticationContext().callback;
                        }

                        // Return to callback if it is send from iframe
                        if (requestInfo.stateMatch) {
                            if (typeof _adal.callback === 'function') {
                                // Call within the same context without full page redirect keeps the callback
                                if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
                                    // Idtoken or Accestoken can be renewed
                                    if (requestInfo.parameters['access_token']) {
                                        _adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']);
                                        return;
                                    } else if (requestInfo.parameters['id_token']) {
                                        _adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']);
                                        return;
                                    }
                                }
                            } else {
                                // normal full login redirect happened on the page
                                updateDataFromCache(_adal.config.loginResource);
                                if (_oauthData.userName) {
                                    //IDtoken is added as token for the app
                                    $timeout(function () {
                                        updateDataFromCache(_adal.config.loginResource);
                                        $rootScope.userInfo = _oauthData;
                                        // redirect to login requested page
                                        var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.START_PAGE);
                                        if (loginStartPage) {
                                            $location.path(loginStartPage);
                                        }
                                    }, 1);
                                    $rootScope.$broadcast('adal:loginSuccess');
                                } else {
                                    $rootScope.$broadcast('adal:loginFailure', _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION));
                                }
                            }
                        }
                    } else {
                        // No callback. App resumes after closing or moving to new page.
                        // Check token and username
                        updateDataFromCache(_adal.config.loginResource);
                        if (!_adal._renewActive && !_oauthData.isAuthenticated && _oauthData.userName) {
                            if (!_adal._getItem(_adal.CONSTANTS.STORAGE.FAILED_RENEW)) {
                                _adal.acquireToken(_adal.config.loginResource, function (error, tokenOut) {
                                    if (error) {
                                        $rootScope.$broadcast('adal:loginFailure', 'auto renew failure');
                                    } else {
                                        if (tokenOut) {
                                            _oauthData.isAuthenticated = true;
                                        }
                                    }
                                });
                            }
                        }
                    }

                    $timeout(function () {
                        updateDataFromCache(_adal.config.loginResource);
                        $rootScope.userInfo = _oauthData;
                    }, 1);
                };

                var routeChangeHandler = function (e, nextRoute) {
                    if (nextRoute.$$route && nextRoute.$$route.requireADLogin) {
                        if (!_oauthData.isAuthenticated) {
                            console.log('Route change event for:' + nextRoute.$$route.originalPath);
                            if (_adal.config && _adal.config.localLoginUrl) {
                                $location.path(_adal.config.localLoginUrl);
                            } else {
                                // directly start login flow
                                _adal._saveItem(_adal.CONSTANTS.STORAGE.START_PAGE, nextRoute.$$route.originalPath);
                                console.log('Start login at:' + window.location.href);
                                $rootScope.$broadcast('adal:loginRedirect');
                                _adal.login();
                            }
                        }
                    }
                };

                // Route change event tracking to receive fragment and also auto renew tokens
                $rootScope.$on('$routeChangeStart', routeChangeHandler);

                $rootScope.$on('$locationChangeStart', locationChangeHandler);

                updateDataFromCache(_adal.config.loginResource);
                $rootScope.userInfo = _oauthData;

                return {
                    // public methods will be here that are accessible from Controller
                    config: _adal.config,
                    login: function () {
                        _adal.login();
                    },
                    loginInProgress: function () {
                        return _adal.loginInProgress();
                    },
                    logOut: function () {
                        _adal.logOut();
                        //call signout related method
                    },
                    getCachedToken: function (resource) {
                        return _adal.getCachedToken(resource);
                    },
                    userInfo: _oauthData,
                    acquireToken: function (resource) {
                        // automated token request call
                        var deferred = $q.defer();
                        _adal.acquireToken(resource, function (error, tokenOut) {
                            if (error) {
                                _adal._logstatus('err :' + error);
                                deferred.reject(error);
                            } else {
                                deferred.resolve(tokenOut);
                            }
                        });

                        return deferred.promise;
                    },
                    getUser: function () {
                        var deferred = $q.defer();
                        _adal.getUser(function (error, user) {
                            if (error) {
                                _adal._logstatus('err :' + error);
                                deferred.reject(error);
                            } else {
                                deferred.resolve(user);
                            }
                        });

                        return deferred.promise;
                    },
                    getResourceForEndpoint: function (endpoint) {
                        return _adal.getResourceForEndpoint(endpoint);
                    },
                    clearCache: function () {
                        _adal.clearCache();
                    },
                    clearCacheForResource: function (resource) {
                        _adal.clearCacheForResource(resource);
                    }
                };
            }];
        });

        // Interceptor for http if needed
        AdalModule.factory('ProtectedResourceInterceptor', ['adalAuthenticationService', '$q', '$rootScope', function (authService, $q, $rootScope) {

            return {
                request: function (config) {
                    if (config) {

                        // This interceptor needs to load service, but dependeny definition causes circular reference error.
                        // Loading with injector is suggested at github. https://github.com/angular/angular.js/issues/2367

                        config.headers = config.headers || {};

                        var resource = authService.getResourceForEndpoint(config.url);
                        var tokenStored = authService.getCachedToken(resource);
                        var isEndpoint = false;
                        if (tokenStored) {
                            // check endpoint mapping if provided
                            config.headers.Authorization = 'Bearer ' + tokenStored;
                            return config;
                        } else {

                            for (var endpointUrl in authService.config.endpoints) {
                                if (config.url.indexOf(endpointUrl) > -1) {
                                    isEndpoint = true;
                                }
                            }

                            // Cancel request if login is starting
                            if (authService.loginInProgress()) {
                                return $q.reject();
                            } else if (authService.config && isEndpoint) {
                                // external endpoints
                                // delayed request to return after iframe completes
                                var delayedRequest = $q.defer();
                                authService.acquireToken(resource).then(function (token) {
                                    config.headers.Authorization = 'Bearer ' + token;
                                    delayedRequest.resolve(config);
                                }, function (err) {
                                    delayedRequest.reject(err);
                                });

                                return delayedRequest.promise;
                            }
                        }

                        return config;
                    }
                },
                responseError: function (rejection) {
                    if (rejection && rejection.status === 401) {
                        var resource = authService.getResourceForEndpoint(rejection.config.url);
                        authService.clearCacheForResource(resource);
                        $rootScope.$broadcast('adal:notAuthorized', rejection, resource);
                    }

                    return $q.reject(rejection);
                }
            };
        }]);
    } else {
        console.log('Angular.JS is not included');
    }
}());
<|endoftext|>


<commit_before>var socket = io.connect(host + '/stats');
socket
	.on('top10', function (data) {
		var $toplist;
		$toplist = $('
');
		_.each(data, function(entry) {
			$toplist.append('
' + _.escape(entry.username) + ' ' + entry.score + '
');
		});
		$('#top10')
			.html('')
			.append($toplist);
	})
	.on('playerRefresh', function(data) {
		if (data.length === 0) {
			$('#playerList')
				.html('
No players :(
');
			return;
		}
		var $playerList;
		$playerList = $('
');
		_.each(data, function(player) {
			$playerList.append('
' + _.escape(player) + '
');
		});
		$('#playerList')
			.html('')
			.append($playerList);
	});
<commit_msg>Formatting score number<commit_after>var socket = io.connect(host + '/stats');
socket
	.on('top10', function (data) {
		var $toplist;
		$toplist = $('
');
		_.each(data, function(entry) {
			$toplist.append('
' + _.escape(entry.username) + ' ' + Number(entry.score).toLocaleString() + '
');
		});
		$('#top10')
			.html('')
			.append($toplist);
	})
	.on('playerRefresh', function(data) {
		if (data.length === 0) {
			$('#playerList')
				.html('
No players :(
');
			return;
		}
		var $playerList;
		$playerList = $('
');
		_.each(data, function(player) {
			$playerList.append('
' + _.escape(player) + '
');
		});
		$('#playerList')
			.html('')
			.append($playerList);
	});
<|endoftext|>


<commit_before>import { Drink, DrinkDao } from '../database/drinkDao';

const dao = new DrinkDao();

export default class DrinkService {

    static find(req, res, next) {
        dao.find((err, drinks) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drinks);
        });
    }

    static create(req, res, next) {
        let drink = new Drink();
        drink.name = req.body.name;
        drink.price = req.body.price;
        dao.save(drink, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }

    static update(req, res, next) {
        let drink = new Drink();
        drink.name = req.body.name;
        drink._id = req.body._id;
        drink.price = req.body.price;

        console.log(drink);

        dao.update(drink, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }

    static remove(req, res, next) {
        dao.remove(req.params.id, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }
}<commit_msg>Removing console.log<commit_after>import { Drink, DrinkDao } from '../database/drinkDao';

const dao = new DrinkDao();

export default class DrinkService {

    static find(req, res, next) {
        dao.find((err, drinks) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drinks);
        });
    }

    static create(req, res, next) {
        let drink = new Drink();
        drink.name = req.body.name;
        drink.price = req.body.price;
        dao.save(drink, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }

    static update(req, res, next) {
        let drink = new Drink();
        drink.name = req.body.name;
        drink._id = req.body._id;
        drink.price = req.body.price;
        dao.update(drink, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }

    static remove(req, res, next) {
        dao.remove(req.params.id, (err, drink) => {
            if (err) {
                return next(err);
            }
            res.status(200).json(drink);
        });
    }
}<|endoftext|>


<commit_before>/**
 * Externs for Twitter Bootstrap
 *
 * @externs
 */

/**
 * @param {string=} opt_action
 * @return {!jQuery}
 */
jQuery.prototype.alert = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.alert = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!jQuery}
 */
jQuery.prototype.dropdown = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.dropdown = function(opt_action) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {jQuery}
 */
jQuery.prototype.modal = function(opt_options) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {angular.JQLite}
 */
angular.JQLite.prototype.modal = function(opt_options) {};

/**
 * @param {string} action
 * @return {!jQuery}
 */
jQuery.prototype.tab = function(action) {};

/**
 * @param {string} action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.tab = function(action) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {jQuery}
 */
jQuery.prototype.tooltip = function(opt_options) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {angular.JQLite}
 */
angular.JQLite.prototype.tooltip = function(opt_options) {};
<commit_msg>More options for tooltips<commit_after>/**
 * Externs for Twitter Bootstrap
 *
 * @externs
 */

/**
 * @param {string=} opt_action
 * @return {!jQuery}
 */
jQuery.prototype.alert = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.alert = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!jQuery}
 */
jQuery.prototype.dropdown = function(opt_action) {};

/**
 * @param {string=} opt_action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.dropdown = function(opt_action) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {jQuery}
 */
jQuery.prototype.modal = function(opt_options) {};

/**
 * @param {(string|Object.<string,*>)=} opt_options
 * @return {angular.JQLite}
 */
angular.JQLite.prototype.modal = function(opt_options) {};

/**
 * @param {string} action
 * @return {!jQuery}
 */
jQuery.prototype.tab = function(action) {};

/**
 * @param {string} action
 * @return {!angular.JQLite}
 */
angular.JQLite.prototype.tab = function(action) {};

/**
 * @typedef {{
   * animation: (boolean|undefined),
   * container: (string|boolean|undefined),
   * delay: (number|Object.<string,*>|undefined),
   * html: (boolean|undefined),
   * placement: (string|function(Element, Element)|undefined),
   * selector: (string|undefined),
   * template: (string|undefined),
   * title: (string|function()|undefined),
   * trigger: (string|undefined),
   * viewport: (string|Object.<string,*>|function(Element)|undefined)
 * }}
 */
var TooltipOptions;

/**
 * @param {(string|TooltipOptions)=} opt_options
 * @return {jQuery}
 */
jQuery.prototype.tooltip = function(opt_options) {};

/**
 * @param {(string|TooltipOptions)=} opt_options
 * @return {angular.JQLite}
 */
angular.JQLite.prototype.tooltip = function(opt_options) {};
<|endoftext|>


<commit_before>var ExifReader = require('../../js/ExifReader.js').ExifReader;
var path = require('path');
var fs = require('fs');

// If you don't want to use a wrapper like jDataView, you can wrap Node.js's
// Buffer with the mandatory parts from the DataView interface.
var DataView = (function() {
	function DataView(_data) {
		this._data = _data;
		this.byteLength = this._data.length;
	}
	DataView.prototype.getUint8 = function(offset) {
		return this._data.readUInt8(offset);
	};
	DataView.prototype.getUint16 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readUInt16LE(offset);
		} else {
			return this._data.readUInt16BE(offset);
		}
	};
	DataView.prototype.getUint32 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readUInt32LE(offset);
		} else {
			return this._data.readUInt32BE(offset);
		}
	};
	DataView.prototype.getInt32 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readInt32LE(offset);
		} else {
			return this._data.readInt32BE(offset);
		}
	};
	return DataView;
})();

if (process.argv.length < 3) {
	console.log('Usage: node ' + path.basename(__filename) + ' <filename>');
	return;
}
var path = process.argv[2];

fs.readFile(path, function (err, data) {
	if (err) {
		console.log('Error reading file.');
		return;
	}

	try {
		var exif = new ExifReader();

		// Parse the Exif tags.
		exif.load(data);
		// Or, with jDataView you would use this:
		//exif.loadView(new jDataView(data));

		// Output the tags.
		var tags = exif.getAllTags();
		for (name in tags)
			console.log(name + ': ' + tags[name].description);
	}
	catch (error) {
		console.log(error);
	}
});
<commit_msg>Fix grammar error in description<commit_after>var ExifReader = require('../../js/ExifReader.js').ExifReader;
var path = require('path');
var fs = require('fs');

// If you don't want to use a wrapper like jDataView, you can wrap Node.js'
// Buffer with the mandatory parts from the DataView interface.
var DataView = (function() {
	function DataView(_data) {
		this._data = _data;
		this.byteLength = this._data.length;
	}
	DataView.prototype.getUint8 = function(offset) {
		return this._data.readUInt8(offset);
	};
	DataView.prototype.getUint16 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readUInt16LE(offset);
		} else {
			return this._data.readUInt16BE(offset);
		}
	};
	DataView.prototype.getUint32 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readUInt32LE(offset);
		} else {
			return this._data.readUInt32BE(offset);
		}
	};
	DataView.prototype.getInt32 = function(offset, littleEndian) {
		if ((littleEndian != null) && littleEndian) {
			return this._data.readInt32LE(offset);
		} else {
			return this._data.readInt32BE(offset);
		}
	};
	return DataView;
})();

if (process.argv.length < 3) {
	console.log('Usage: node ' + path.basename(__filename) + ' <filename>');
	return;
}
var path = process.argv[2];

fs.readFile(path, function (err, data) {
	if (err) {
		console.log('Error reading file.');
		return;
	}

	try {
		var exif = new ExifReader();

		// Parse the Exif tags.
		exif.load(data);
		// Or, with jDataView you would use this:
		//exif.loadView(new jDataView(data));

		// Output the tags.
		var tags = exif.getAllTags();
		for (name in tags)
			console.log(name + ': ' + tags[name].description);
	}
	catch (error) {
		console.log(error);
	}
});
<|endoftext|>


<commit_before>/*
   this page is for /communities
 */
import React from 'react'
import { Provider } from 'mobx-react'
import R from 'ramda'

import { ROUTE } from '@constant'
import {
  getJwtToken,
  makeGQClient,
  queryStringToJSON,
  nilOrEmpty,
  getSubPath,
  ssrAmbulance,
  parseTheme,
} from '@utils'

import AnalysisService from '@services/Analysis'
import initRootStore from '@stores/init'

import GlobalLayout from '@containers/GlobalLayout'
import ThemeWrapper from '@containers/ThemeWrapper'
import MultiLanguage from '@containers/MultiLanguage'
import Sidebar from '@containers/Sidebar'
import Preview from '@containers/Preview'
import Doraemon from '@containers/Doraemon'
import Route from '@containers/Route'
import Header from '@containers/Header'
import CommunitiesBanner from '@containers/CommunitiesBanner'
import CommunitiesContent from '@containers/CommunitiesContent'
import Footer from '@containers/Footer'

import { P } from '@schemas'

/* import PostsThreadSchema from '@containers/PostsThread/schema' */

// try to fix safari bug
// see https://github.com/yahoo/react-intl/issues/422
global.Intl = require('intl')

async function fetchData(props, opt) {
  const { realname } = R.merge({ realname: true }, opt)

  const token = realname ? getJwtToken(props) : null
  const gqClient = makeGQClient(token)
  const userHasLogin = nilOrEmpty(token) === false
  const subPath = getSubPath(props)
  const category = subPath !== '' ? subPath : 'pl'

  const { asPath } = props

  const filter = { ...queryStringToJSON(asPath, { pagi: 'number' }) }

  const sessionState = gqClient.request(P.sessionState)
  const pagedCommunities = gqClient.request(P.pagedCommunities, {
    filter: { ...filter, category },
    userHasLogin,
  })
  const pagedCategories = gqClient.request(P.pagedCategories, { filter })

  const subscribedCommunities = gqClient.request(P.subscribedCommunities, {
    filter: {
      page: 1,
      size: 30,
    },
  })

  return {
    category,
    ...(await sessionState),
    ...(await pagedCategories),
    ...(await pagedCommunities),
    ...(await subscribedCommunities),
  }
}

export default class CommunitiesPage extends React.Component {
  static async getInitialProps(props) {
    let resp
    try {
      resp = await fetchData(props)
    } catch ({ response: { errors } }) {
      if (ssrAmbulance.hasLoginError(errors)) {
        resp = await fetchData(props, { realname: false })
      }
    }

    const {
      category,
      sessionState,
      pagedCategories,
      pagedCommunities,
      subscribedCommunities,
    } = resp

    return {
      langSetup: {},
      theme: {
        curTheme: parseTheme(sessionState),
      },
      route: {
        mainPath: ROUTE.COMMUNITIES,
        subPath: category,
      },
      account: {
        user: sessionState.user || {},
        isValidSession: sessionState.isValid,
        userSubscribedCommunities: subscribedCommunities,
      },
      communitiesBanner: {
        pagedCategories,
        activeTab: category,
      },
      communitiesContent: {
        pagedCommunities,
      },
    }
  }

  constructor(props) {
    super(props)
    this.store = initRootStore({ ...props })
  }

  render() {
    return (
      <Provider store={this.store}>
        <AnalysisService>
          <ThemeWrapper>
            <Route />
            <MultiLanguage>
              <Sidebar />
              <Preview />
              <Doraemon />
              <GlobalLayout>
                <Header />
                <CommunitiesBanner />
                <CommunitiesContent />
                <Footer />
              </GlobalLayout>
            </MultiLanguage>
          </ThemeWrapper>
        </AnalysisService>
      </Provider>
    )
  }
}
<commit_msg>fix(router): remove getSubPath function<commit_after>/*
   this page is for /communities
 */
import React from 'react'
import { Provider } from 'mobx-react'
import R from 'ramda'

import { ROUTE } from '@constant'
import {
  parseURL,
  getJwtToken,
  makeGQClient,
  queryStringToJSON,
  nilOrEmpty,
  ssrAmbulance,
  parseTheme,
} from '@utils'

import AnalysisService from '@services/Analysis'
import initRootStore from '@stores/init'

import GlobalLayout from '@containers/GlobalLayout'
import ThemeWrapper from '@containers/ThemeWrapper'
import MultiLanguage from '@containers/MultiLanguage'
import Sidebar from '@containers/Sidebar'
import Preview from '@containers/Preview'
import Doraemon from '@containers/Doraemon'
import Route from '@containers/Route'
import Header from '@containers/Header'
import CommunitiesBanner from '@containers/CommunitiesBanner'
import CommunitiesContent from '@containers/CommunitiesContent'
import Footer from '@containers/Footer'

import { P } from '@schemas'

/* import PostsThreadSchema from '@containers/PostsThread/schema' */

// try to fix safari bug
// see https://github.com/yahoo/react-intl/issues/422
global.Intl = require('intl')

async function fetchData(props, opt) {
  const { realname } = R.merge({ realname: true }, opt)

  const token = realname ? getJwtToken(props) : null
  const gqClient = makeGQClient(token)
  const userHasLogin = nilOrEmpty(token) === false
  const { subPath } = parseURL(props)
  const category = subPath !== '' ? subPath : 'pl'

  const { asPath } = props

  const filter = { ...queryStringToJSON(asPath, { pagi: 'number' }) }

  const sessionState = gqClient.request(P.sessionState)
  const pagedCommunities = gqClient.request(P.pagedCommunities, {
    filter: { ...filter, category },
    userHasLogin,
  })
  const pagedCategories = gqClient.request(P.pagedCategories, { filter })

  const subscribedCommunities = gqClient.request(P.subscribedCommunities, {
    filter: {
      page: 1,
      size: 30,
    },
  })

  return {
    category,
    ...(await sessionState),
    ...(await pagedCategories),
    ...(await pagedCommunities),
    ...(await subscribedCommunities),
  }
}

export default class CommunitiesPage extends React.Component {
  static async getInitialProps(props) {
    let resp
    try {
      resp = await fetchData(props)
    } catch ({ response: { errors } }) {
      if (ssrAmbulance.hasLoginError(errors)) {
        resp = await fetchData(props, { realname: false })
      }
    }

    const {
      category,
      sessionState,
      pagedCategories,
      pagedCommunities,
      subscribedCommunities,
    } = resp

    return {
      langSetup: {},
      theme: {
        curTheme: parseTheme(sessionState),
      },
      route: {
        mainPath: ROUTE.COMMUNITIES,
        subPath: category,
      },
      account: {
        user: sessionState.user || {},
        isValidSession: sessionState.isValid,
        userSubscribedCommunities: subscribedCommunities,
      },
      communitiesBanner: {
        pagedCategories,
        activeTab: category,
      },
      communitiesContent: {
        pagedCommunities,
      },
    }
  }

  constructor(props) {
    super(props)
    this.store = initRootStore({ ...props })
  }

  render() {
    return (
      <Provider store={this.store}>
        <AnalysisService>
          <ThemeWrapper>
            <Route />
            <MultiLanguage>
              <Sidebar />
              <Preview />
              <Doraemon />
              <GlobalLayout>
                <Header />
                <CommunitiesBanner />
                <CommunitiesContent />
                <Footer />
              </GlobalLayout>
            </MultiLanguage>
          </ThemeWrapper>
        </AnalysisService>
      </Provider>
    )
  }
}
<|endoftext|>


<commit_before>define('synth/grid',
  ['synth/tiles', 'synth/utility', 'synth/notes'],
  function(Tile, Utility, Notes) {
    var _grid = [],
        _tileSize = 12,
        _width = 840,
        _height = 600,
        _gridWidth = _width / _tileSize,
        _gridHeight = _height / _tileSize,
        _cachedImage,
        _tiles = {};

    function getTile(x, y) {
      return _grid[x][y];
    }

    function setTile(x, y, tile) {
      _grid[x][y] = tile;

      var ctx = _cachedImage.getContext('2d')
      if(tile.tileType !== 'empty') {
        ctx.fillStyle = $('#note-' + Notes.getNote() + '-button').css('background-color');
        ctx.fillRect(x*_tileSize, y*_tileSize, _tileSize, _tileSize);
      }
      ctx.rect(x*_tileSize, y*_tileSize, _tileSize, _tileSize);
      ctx.stroke();

      if(["up", "down", "left", "right"].indexOf(tile.tileType) > -1) {
        var im = _tiles[tile.tileType];
        ctx.drawImage(im, x*_tileSize, y*_tileSize);
      }
    }

    function render(ctx) {
      for(var x=0; x<_gridWidth; ++x) {
        ctx.beginPath();
        ctx.moveTo(x*_tileSize, 0);
        ctx.lineTo(x*_tileSize, _height);
        ctx.stroke();
      }

      for(var y=0; y<_gridWidth; ++y) {
        ctx.beginPath();
        ctx.moveTo(0, y*_tileSize);
        ctx.lineTo(_width, y*_tileSize);
        ctx.stroke();
      }
    }

    return {
      init: function() {
        _tiles.up = Utility.loadImage("assets/tiles/up.png");
        _tiles.down = Utility.loadImage("assets/tiles/down.png");
        _tiles.left = Utility.loadImage("assets/tiles/left.png");
        _tiles.right = Utility.loadImage("assets/tiles/right.png");

        for(var i=0; i<_gridWidth; ++i) {
          _grid.push([]);
          for(var j=0; j<_gridHeight; ++j) {
            _grid[i].push({
              type: "empty",
              note: null
            });
          }
        }
        // TODO: Render image as rows, callback when done
        _cachedImage = Utility.renderToCanvas(_width, _height, render);
      },

      getTileSize: function() {
        return _tileSize;
      },

      getTileByPosition: function(x, y) {
        // TODO: Fix me, boundary case
        return getTile(Math.floor(x / _tileSize), Math.floor(y / _tileSize));
      },

      setTileByPosition: function(x, y, tile) {
        // TODO: Fix me, boundary case
        setTile(Math.floor(x / _tileSize), Math.floor(y / _tileSize), tile);
      },

      update: function(goo, time) {
        goo.ctx.drawImage(_cachedImage, 0, 0);
      }
    }
})
<commit_msg>Removed some TODOs that were TODONE<commit_after>define('synth/grid',
  ['synth/tiles', 'synth/utility', 'synth/notes'],
  function(Tile, Utility, Notes) {
    var _grid = [],
        _tileSize = 12,
        _width = 840,
        _height = 600,
        _gridWidth = _width / _tileSize,
        _gridHeight = _height / _tileSize,
        _cachedImage,
        _tiles = {};

    function getTile(x, y) {
      return _grid[x][y];
    }

    function setTile(x, y, tile) {
      _grid[x][y] = tile;

      var ctx = _cachedImage.getContext('2d')
      if(tile.tileType !== 'empty') {
        ctx.fillStyle = $('#note-' + Notes.getNote() + '-button').css('background-color');
        ctx.fillRect(x*_tileSize, y*_tileSize, _tileSize, _tileSize);
      }
      ctx.rect(x*_tileSize, y*_tileSize, _tileSize, _tileSize);
      ctx.stroke();

      if(["up", "down", "left", "right"].indexOf(tile.tileType) > -1) {
        var im = _tiles[tile.tileType];
        ctx.drawImage(im, x*_tileSize, y*_tileSize);
      }
    }

    function render(ctx) {
      for(var x=0; x<_gridWidth; ++x) {
        ctx.beginPath();
        ctx.moveTo(x*_tileSize, 0);
        ctx.lineTo(x*_tileSize, _height);
        ctx.stroke();
      }

      for(var y=0; y<_gridWidth; ++y) {
        ctx.beginPath();
        ctx.moveTo(0, y*_tileSize);
        ctx.lineTo(_width, y*_tileSize);
        ctx.stroke();
      }
    }

    return {
      init: function() {
        _tiles.up = Utility.loadImage("assets/tiles/up.png");
        _tiles.down = Utility.loadImage("assets/tiles/down.png");
        _tiles.left = Utility.loadImage("assets/tiles/left.png");
        _tiles.right = Utility.loadImage("assets/tiles/right.png");

        for(var i=0; i<_gridWidth; ++i) {
          _grid.push([]);
          for(var j=0; j<_gridHeight; ++j) {
            _grid[i].push({
              type: "empty",
              note: null
            });
          }
        }
        _cachedImage = Utility.renderToCanvas(_width, _height, render);
      },

      getTileSize: function() {
        return _tileSize;
      },

      getTileByPosition: function(x, y) {
        return getTile(Math.floor(x / _tileSize), Math.floor(y / _tileSize));
      },

      setTileByPosition: function(x, y, tile) {
        setTile(Math.floor(x / _tileSize), Math.floor(y / _tileSize), tile);
      },

      update: function(goo, time) {
        goo.ctx.drawImage(_cachedImage, 0, 0);
      }
    }
});
<|endoftext|>


<commit_before>var events = require('events');
var fs = require('fs');
var util = require('util');

var ffi = require('ffi');
var ref = require('ref');

var REGISTERS_START = 0x01c20000;
var REGISTERS_SIZE  = 0x61000;

var PROT_READ = 1;
var PROT_WRITE = 2;
var MAP_SHARED = 1;

var libc = ffi.Library(null, {
  'mmap': [ 'pointer', [ 'pointer', 'int', 'int', 'int', 'int', 'int' ] ],
  'munmap': [ 'int', [ 'pointer', 'int' ]],
  'memcpy': [ 'pointer', [ 'pointer', 'pointer', 'int' ] ]
});

var PIO = 0x01C20800;

var PORTS = {
  B: {
    CFG: [PIO + 0x24, PIO + 0x28, PIO + 0x2c, PIO + 0x30],
    DAT: PIO + 0x34,
    DRV: [PIO + 0x38, PIO + 0x3c],
    PUL: [PIO + 0x40, PIO + 0x44]
  },
  C: {
    CFG: [PIO + 0x48, PIO + 0x4c, PIO + 0x50, PIO + 0x54],
    DAT: PIO + 0x58,
    DRV: [PIO + 0x5c, PIO + 0x60],
    PUL: [PIO + 0x64, PIO + 0x68]
  },
  D: {
    CFG: [PIO + 0x6c, PIO + 0x70, PIO + 0x74, PIO + 0x78],
    DAT: PIO + 0x7c,
    DRV: [PIO + 0x80, PIO + 0x84],
    PUL: [PIO + 0x88, PIO + 0x8c]
  },
  E: {
    CFG: [PIO + 0x90, PIO + 0x94, PIO + 0x98, PIO + 0x9c],
    DAT: PIO + 0xa0,
    DRV: [PIO + 0xa4, PIO + 0xa8],
    PUL: [PIO + 0xac, PIO + 0xb0]
  },
  F: {
    CFG: [PIO + 0xb4, PIO + 0xb8, PIO + 0xbc, PIO + 0xc0],
    DAT: PIO + 0xc4,
    DRV: [PIO + 0xc8, PIO + 0xcc],
    PUL: [PIO + 0xd0, PIO + 0xd4]
  },
};

var PIN_DATA = require('./allwinner-r8.json');

function AllwinnerR8() {
  this._fd = -1;
  this._registers = null;

  this._reads = {};
}

util.inherits(AllwinnerR8, events.EventEmitter);

AllwinnerR8.prototype.open = function(callback) {
  fs.open('/dev/mem', 'rs+', function(err, fd) {
    if (err) {
      callback(err);
    }

    this._fd = fd;

    var registers = libc.mmap(null, REGISTERS_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, this._fd, REGISTERS_START);

    this._registers = ref.reinterpret(registers, REGISTERS_SIZE, 0);

    callback();
  }.bind(this));
};

AllwinnerR8.prototype.pinMode = function(pin, mode) {
  if (pin === 'LRADC') {
    // TODO
  } else {
    var pinData = PIN_DATA[pin];
    var port = pinData.port;
    var register = pinData.register;
    var index = pinData.index;
    var pullIndex = register * 8 + index;

    var cfgReg = PORTS[port].CFG[register];
    var pullReg = PORTS[port].PUL[register][(pullIndex < 16) ? 0 : 1];

    var cfgVal = this._readRegister(cfgReg);
    cfgVal = (cfgVal & ~(0x07 << (index * 4))) | (mode << (index * 4));
    this._writeRegister(cfgReg, cfgVal);

    // TODO: set pull-up register
  }
};

AllwinnerR8.prototype.pwmWrite = function(pin, value) {
  // TODO
};

AllwinnerR8.prototype.analogRead = function(pin) {
  this._reads[pin] = true;
};

AllwinnerR8.prototype.digitalWrite = function(pin, value) {
  var pinData = PIN_DATA[pin];
  var port = pinData.port;
  var register = pinData.register;
  var index = pinData.index;

  var datReg = PORTS[port].DAT;
  var datVal = this._readRegister(datReg);
  var pinMask = 1 << (register * 8 + index);

  if (value) {
    datVal |= pinMask;
  } else {
    datVal &= ~pinMask;
  }

  // TODO: set pull-up register if input mode

  this._writeRegister(datReg, datVal);
};

AllwinnerR8.prototype.digitalRead = function(pin) {
  this._reads[pin] = true;
};

AllwinnerR8.prototype.tick = function() {
  Object.keys(this._reads).forEach(function(pin) {
    if (pin === 'LRADC') {
      // TODO
    } else {
      var pinData = PIN_DATA[pin];
      var port = pinData.port;
      var register = pinData.register;
      var index = pinData.index;

      var datReg = PORTS[port].DAT;
      var datVal = this._readRegister(datReg);
      var pinMask = 1 << (register * 8 + index);

      this.emit('digital-read', pin, (datVal & pinMask) ? 1 : 0);
    }
  }.bind(this));
};

AllwinnerR8.prototype.close = function(callback) {
  if (this._registers) {
    libc.munmap(this._registers, REGISTERS_SIZE);
  }

  fs.close(this._fd, callback);
};

AllwinnerR8.prototype._readRegister = function(register) {
  var registerOffset = register - REGISTERS_START;
  var buffer = new Buffer(4);

  if (this._registers) {
    libc.memcpy(buffer, this._registers.slice(registerOffset, registerOffset + buffer.length), buffer.length);
  } else {
    buffer.writeUInt32LE(0, 0);
  }

  return buffer.readInt32LE(0);
};

AllwinnerR8.prototype._writeRegister = function(register, value) {
  var registerOffset = register - REGISTERS_START;
  var buffer = new Buffer(4);

  buffer.writeInt32LE(value, 0);

  if (this._registers) {
    libc.memcpy(this._registers.slice(registerOffset, registerOffset + buffer.length), buffer, buffer.length);
  }
};

module.exports = AllwinnerR8;
<commit_msg>Add PWM and LRADC support with some cleanup<commit_after>var events = require('events');
var fs = require('fs');
var util = require('util');

var ffi = require('ffi');
var ref = require('ref');

var REGISTERS_START = 0x01c20000;
var REGISTERS_SIZE  = 0x61000;

var PROT_READ = 1;
var PROT_WRITE = 2;
var MAP_SHARED = 1;

var libc = ffi.Library(null, {
  'mmap': [ 'pointer', [ 'pointer', 'int', 'int', 'int', 'int', 'int' ] ],
  'munmap': [ 'int', [ 'pointer', 'int' ]],
  'memcpy': [ 'pointer', [ 'pointer', 'pointer', 'int' ] ]
});

var PIO = 0x01C20800;

var PORTS = {
  B: {
    CFG: [PIO + 0x24, PIO + 0x28, PIO + 0x2c, PIO + 0x30],
    DAT: PIO + 0x34,
    DRV: [PIO + 0x38, PIO + 0x3c],
    PUL: [PIO + 0x40, PIO + 0x44]
  },
  C: {
    CFG: [PIO + 0x48, PIO + 0x4c, PIO + 0x50, PIO + 0x54],
    DAT: PIO + 0x58,
    DRV: [PIO + 0x5c, PIO + 0x60],
    PUL: [PIO + 0x64, PIO + 0x68]
  },
  D: {
    CFG: [PIO + 0x6c, PIO + 0x70, PIO + 0x74, PIO + 0x78],
    DAT: PIO + 0x7c,
    DRV: [PIO + 0x80, PIO + 0x84],
    PUL: [PIO + 0x88, PIO + 0x8c]
  },
  E: {
    CFG: [PIO + 0x90, PIO + 0x94, PIO + 0x98, PIO + 0x9c],
    DAT: PIO + 0xa0,
    DRV: [PIO + 0xa4, PIO + 0xa8],
    PUL: [PIO + 0xac, PIO + 0xb0]
  },
  F: {
    CFG: [PIO + 0xb4, PIO + 0xb8, PIO + 0xbc, PIO + 0xc0],
    DAT: PIO + 0xc4,
    DRV: [PIO + 0xc8, PIO + 0xcc],
    PUL: [PIO + 0xd0, PIO + 0xd4]
  },
};

var PIN_DATA = require('./allwinner-r8.json');

var PWM = 0x01C20C00;
var PWM_CTRL = PWM + 0x0200;
var PWM_CH0_PERIOD = PWM + 0x0204;

var LRADC = 0x01C22800;
var LRADC_CTRL = LRADC + 0x00;
var LRADC_DATA0 = LRADC + 0x0c;

function AllwinnerR8() {
  this._fd = -1;
  this._registers = null;

  this._reads = {};
}

util.inherits(AllwinnerR8, events.EventEmitter);

AllwinnerR8.prototype.open = function(callback) {
  fs.open('/dev/mem', 'rs+', function(err, fd) {
    if (err) {
      callback(err);
    }

    this._fd = fd;

    var registers = libc.mmap(null, REGISTERS_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, this._fd, REGISTERS_START);

    this._registers = ref.reinterpret(registers, REGISTERS_SIZE, 0);

    callback();
  }.bind(this));
};

AllwinnerR8.prototype.pinMode = function(pin, mode) {
  if (pin === 'LRADC') {
    var lradcCtrlVal = 0x01;

    this._writeRegister(LRADC_CTRL, lradcCtrlVal);
  } else {
    var pinData = PIN_DATA[pin];
    var port = pinData.port;
    var register = pinData.register;
    var index = pinData.index;

    if (mode === 3) {
      mode = 2;
    }

    var cfgReg = PORTS[port].CFG[register];
    var cfgVal = this._readRegister(cfgReg);

    cfgVal = (cfgVal & ~(0x07 << (index * 4))) | (mode << (index * 4));
    this._writeRegister(cfgReg, cfgVal);
  }

  if (pin === 'PWM0' && mode === 2) {
    var pwmCtrlVal = (1 << 6) | (1 << 4);
    var pwmPeriodVal = (0xff << 16) | 0;

    this._writeRegister(PWM_CH0_PERIOD, pwmPeriodVal);
    this._writeRegister(PWM_CTRL, pwmCtrlVal);
  }
};

AllwinnerR8.prototype.pwmWrite = function(pin, value) {
  if (pin === 'PWM0') {
    var pwmPeriodVal = (0xff << 16) | Math.round(value);

    this._writeRegister(PWM_CH0_PERIOD, pwmPeriodVal);
  }
};

AllwinnerR8.prototype.analogRead = function(pin) {
  this._reads[pin] = true;
};

AllwinnerR8.prototype.digitalWrite = function(pin, value) {
  var pinData = PIN_DATA[pin];
  var port = pinData.port;
  var register = pinData.register;
  var index = pinData.index;

  var datReg = PORTS[port].DAT;
  var datVal = this._readRegister(datReg);
  var pinMask = 1 << (register * 8 + index);

  if (value) {
    datVal |= pinMask;
  } else {
    datVal &= ~pinMask;
  }

  this._writeRegister(datReg, datVal);
};

AllwinnerR8.prototype.digitalRead = function(pin) {
  this._reads[pin] = true;
};

AllwinnerR8.prototype.tick = function() {
  Object.keys(this._reads).forEach(function(pin) {
    if (pin === 'LRADC') {
      var adcVal = this._readRegister(LRADC_DATA0);

      this.emit('analog-read', pin, adcVal);
    } else {
      var pinData = PIN_DATA[pin];
      var port = pinData.port;
      var register = pinData.register;
      var index = pinData.index;

      var datReg = PORTS[port].DAT;
      var datVal = this._readRegister(datReg);
      var pinMask = 1 << (register * 8 + index);

      this.emit('digital-read', pin, (datVal & pinMask) ? 1 : 0);
    }
  }.bind(this));
};

AllwinnerR8.prototype.close = function(callback) {
  if (this._registers) {
    libc.munmap(this._registers, REGISTERS_SIZE);
  }

  fs.close(this._fd, callback);
};

AllwinnerR8.prototype._readRegister = function(register) {
  var registerOffset = register - REGISTERS_START;
  var buffer = new Buffer(4);

  if (this._registers) {
    libc.memcpy(buffer, this._registers.slice(registerOffset, registerOffset + buffer.length), buffer.length);
  } else {
    buffer.writeUInt32LE(0, 0);
  }

  return buffer.readInt32LE(0);
};

AllwinnerR8.prototype._writeRegister = function(register, value) {
  var registerOffset = register - REGISTERS_START;
  var buffer = new Buffer(4);

  buffer.writeInt32LE(value, 0);

  if (this._registers) {
    libc.memcpy(this._registers.slice(registerOffset, registerOffset + buffer.length), buffer, buffer.length);
  }
};

module.exports = AllwinnerR8;
<|endoftext|>


<commit_before>'use strict'

const actions = function (api, reply, page, component, action = null, payload = {}) {
  let macroId = `c_${component.id}`
  const configuration = JSON.parse(component.configuration)
  let actions = []
  let firstAction = null
  switch (component.type) {
    case 1:
      // 1: Scenario play
      actions = configuration.map((item) => {
        return {id: item.scenario, action: 'play', delay: item.delay * 60000}
      })
      firstAction = actions.shift()

      api.callScenarioAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 2:
      // 2: Scenario activation
      firstAction = {
        id: configuration.scenario,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.scenario,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }

      api.callScenarioAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 3:
      // 3: Domotic switch
      firstAction = {
        id: configuration.domotic,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.domotic,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }

      api.callDomoticAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 4:
      // 4: Heat mode
      firstAction = {
        id: configuration.heat,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.heat,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }
      api.callHeatingAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 5:
      // 5: Alarm level
      firstAction = {
        action: action
      }

      api.callAlarmLevelAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      })
      break

    case 8:
      // 8: Multiple scenarii switch
      const [actionIdx, actionVerb] = action.split('-')

      // Map them to steps to play against API
      let steps = configuration.scenarii.map((scenario, idx) => {
        // eslint-disable-next-line eqeqeq
        if (idx == actionIdx) {
          return {
            id: scenario.id,
            action: (configuration.allow_none && actionVerb === 'off') ? 'off' : 'on'
          }
        }
        return {id: scenario.id, action: 'off'}
      })

      // Sort OFFs first, ON after.
      steps = steps.sort((a, b) => {
        return ((a === 'off') ? 1 : 2) - ((b === 'off') ? 1 : 2)
      })

      console.log(steps, '######')
      // TODO !0

      break

    default:
      // Action not (yet) supported
      reply({}).code(418)
  }
}

// exports
export default actions
<commit_msg>call action server side for component 8<commit_after>'use strict'

const actions = function (api, reply, page, component, action = null, payload = {}) {
  let macroId = `c_${component.id}`
  const configuration = JSON.parse(component.configuration)
  let actions = []
  let firstAction = null
  switch (component.type) {
    case 1:
      // 1: Scenario play
      actions = configuration.map((item) => {
        return {id: item.scenario, action: 'play', delay: item.delay * 60000}
      })
      firstAction = actions.shift()

      api.callScenarioAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 2:
      // 2: Scenario activation
      firstAction = {
        id: configuration.scenario,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.scenario,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }

      api.callScenarioAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 3:
      // 3: Domotic switch
      firstAction = {
        id: configuration.domotic,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.domotic,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }

      api.callDomoticAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 4:
      // 4: Heat mode
      firstAction = {
        id: configuration.heat,
        action: action,
        delay: configuration.delay * 60000
      }
      if (configuration.reset_delay > 0 && configuration.reset_action) {
        actions.push({
          id: configuration.heat,
          action: configuration.reset_action,
          delay: configuration.reset_delay * 60000
        })
      }
      api.callHeatingAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions)
      break

    case 5:
      // 5: Alarm level
      firstAction = {
        action: action
      }

      api.callAlarmLevelAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      })
      break

    case 8:
      // 8: Multiple scenarii switch
      const [actionIdx, actionVerb] = action.split('-')

      // Map them to steps to play against API
      let steps = configuration.scenarii.map((scenario, idx) => {
        // eslint-disable-next-line eqeqeq
        if (idx == actionIdx) {
          return {
            id: scenario.id,
            action: (configuration.allow_none && actionVerb === 'off') ? 'off' : 'on'
          }
        }
        return {id: scenario.id, action: 'off'}
      })

      // Sort OFFs first, ON after.
      steps = steps.sort((a, b) => {
        return ((a === 'off') ? 1 : 2) - ((b === 'off') ? 1 : 2)
      })

      firstAction = steps.shift()
      api.callScenarioAction(firstAction, (err, data) => {
        if (err) {
          console.log(err)
          reply(err).code(500)
        }
        reply(data)
      }, macroId, ...actions) // FIXME !0: to test
      break

    default:
      // Action not (yet) supported
      reply({}).code(418)
  }
}

// exports
export default actions
<|endoftext|>


<commit_before>var events = require('./binlog_event');
var rowsEvents = require('./rows_event');

var CodeEvent = [
  'UNKNOWN_EVENT',
  'START_EVENT_V3',
  'QUERY_EVENT',
  'STOP_EVENT',
  'ROTATE_EVENT',
  'INTVAR_EVENT',
  'LOAD_EVENT',
  'SLAVE_EVENT',
  'CREATE_FILE_EVENT',
  'APPEND_BLOCK_EVENT',
  'EXEC_LOAD_EVENT',
  'DELETE_FILE_EVENT',
  'NEW_LOAD_EVENT',
  'RAND_EVENT',
  'USER_VAR_EVENT',
  'FORMAT_DESCRIPTION_EVENT',
  'XID_EVENT',
  'BEGIN_LOAD_QUERY_EVENT',
  'EXECUTE_LOAD_QUERY_EVENT',
  'TABLE_MAP_EVENT',
  'PRE_GA_DELETE_ROWS_EVENT',
  'PRE_GA_UPDATE_ROWS_EVENT',
  'PRE_GA_WRITE_ROWS_EVENT',
  'WRITE_ROWS_EVENT_V1',
  'UPDATE_ROWS_EVENT_V1',
  'DELETE_ROWS_EVENT_V1',
  'INCIDENT_EVENT',
  'HEARTBEAT_LOG_EVENT',
  'IGNORABLE_LOG_EVENT',
  'ROWS_QUERY_LOG_EVENT',
  'WRITE_ROWS_EVENT_V2',
  'UPDATE_ROWS_EVENT_V2',
  'DELETE_ROWS_EVENT_V2',
  'GTID_LOG_EVENT',
  'ANONYMOUS_GTID_LOG_EVENT',
  'PREVIOUS_GTIDS_LOG_EVENT'
];

var EventClass = {
  UNKNOWN_EVENT: events.Unknown,
  QUERY_EVENT: events.Query,
  ROTATE_EVENT: events.Rotate,
  FORMAT_DESCRIPTION_EVENT: events.Format,
  XID_EVENT: events.Xid,

  TABLE_MAP_EVENT: events.TableMap,
  DELETE_ROWS_EVENT_V1: rowsEvents.DeleteRows,
  UPDATE_ROWS_EVENT_V1: rowsEvents.UpdateRows,
  WRITE_ROWS_EVENT_V1: rowsEvents.WriteRows,
  WRITE_ROWS_EVENT_V2: rowsEvents.WriteRows,
  UPDATE_ROWS_EVENT_V2: rowsEvents.UpdateRows,
  DELETE_ROWS_EVENT_V2: rowsEvents.DeleteRows
};

function getEventName (code) {
  return CodeEvent[code] || 'UNKNOWN_EVENT';
}

function getEventClass (code) {
  return EventClass[getEventName(code)] || events.Unknown;
}

module.exports = {
  getEventName: getEventName,
  getEventClass: getEventClass
};<commit_msg>Fix spacing<commit_after>var events = require('./binlog_event');
var rowsEvents = require('./rows_event');

var CodeEvent = [
  'UNKNOWN_EVENT',
  'START_EVENT_V3',
  'QUERY_EVENT',
  'STOP_EVENT',
  'ROTATE_EVENT',
  'INTVAR_EVENT',
  'LOAD_EVENT',
  'SLAVE_EVENT',
  'CREATE_FILE_EVENT',
  'APPEND_BLOCK_EVENT',
  'EXEC_LOAD_EVENT',
  'DELETE_FILE_EVENT',
  'NEW_LOAD_EVENT',
  'RAND_EVENT',
  'USER_VAR_EVENT',
  'FORMAT_DESCRIPTION_EVENT',
  'XID_EVENT',
  'BEGIN_LOAD_QUERY_EVENT',
  'EXECUTE_LOAD_QUERY_EVENT',
  'TABLE_MAP_EVENT',
  'PRE_GA_DELETE_ROWS_EVENT',
  'PRE_GA_UPDATE_ROWS_EVENT',
  'PRE_GA_WRITE_ROWS_EVENT',
  'WRITE_ROWS_EVENT_V1',
  'UPDATE_ROWS_EVENT_V1',
  'DELETE_ROWS_EVENT_V1',
  'INCIDENT_EVENT',
  'HEARTBEAT_LOG_EVENT',
  'IGNORABLE_LOG_EVENT',
  'ROWS_QUERY_LOG_EVENT',
  'WRITE_ROWS_EVENT_V2',
  'UPDATE_ROWS_EVENT_V2',
  'DELETE_ROWS_EVENT_V2',
  'GTID_LOG_EVENT',
  'ANONYMOUS_GTID_LOG_EVENT',
  'PREVIOUS_GTIDS_LOG_EVENT'
];

var EventClass = {
  UNKNOWN_EVENT: events.Unknown,
  QUERY_EVENT: events.Query,
  ROTATE_EVENT: events.Rotate,
  FORMAT_DESCRIPTION_EVENT: events.Format,
  XID_EVENT: events.Xid,

  TABLE_MAP_EVENT: events.TableMap,
  DELETE_ROWS_EVENT_V1: rowsEvents.DeleteRows,
  UPDATE_ROWS_EVENT_V1: rowsEvents.UpdateRows,
  WRITE_ROWS_EVENT_V1: rowsEvents.WriteRows,
  WRITE_ROWS_EVENT_V2: rowsEvents.WriteRows,
  UPDATE_ROWS_EVENT_V2: rowsEvents.UpdateRows,
  DELETE_ROWS_EVENT_V2: rowsEvents.DeleteRows
};

function getEventName(code) {
  return CodeEvent[code] || 'UNKNOWN_EVENT';
}

function getEventClass(code) {
  return EventClass[getEventName(code)] || events.Unknown;
}

module.exports = {
  getEventName: getEventName,
  getEventClass: getEventClass
};<|endoftext|>


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

    /**
     * Check if we are in Neos back-end
     * @type {boolean}
     */
    let IS_NEOS_BE = false;

    /**
     * Pb.Site app
     */
    const App = {
        /**
         * Called on page load, to initialise all necessary components
         */
        init: function () {
            // init zurb foundation
            $(document).foundation();

            // prevent some default events when in Neos back-end
            this.preventDefaultsWhenInNeosBackend();
        },

        /**
         * Initialise some localStorage variables,
         * so Neos is by default pre-configured (e.g. Structure panel is opened)
         */
        initNeosLocalStorage: function () {
            if (Modernizr.localstorage) {
                // Open the 'Structure' panel by default
                if (null === localStorage.getItem('contextStructureMode')) {
                    localStorage.setItem('contextStructureMode', false);
                }
            }
        },

        /**
         * Prevent some default events when in Neos back-end
         */
        preventDefaultsWhenInNeosBackend: function () {
            if (false === IS_NEOS_BE) {
                return;
            }

            // By default, after click on LABEL, focus is moved to related INPUT field.
            // Prevent that default action while in edit mode (@see TS-113)
            $('label').children('.neos-inline-editable').click(function (e) {
                e.preventDefault();
            });
        }
    };

    /**
     * Invoked when page finished loading (via AJAX) in Neos back-end.
     */
    document.addEventListener('Neos.PageLoaded', function () {
        App.init();
    });
    /**
     * Invoked when new content element has been added and rendered on page
     * (but w/o full page reload).
     */
    document.addEventListener('Neos.NodeCreated', function (e) {
        var createdNodeType = $(e.detail.element).data('node-_nodeType');
        // console.log('Neos.NodeCreated:', createdNodeType);

        switch (createdNodeType) {
            // Some JavaScript components need to be fully re-initialised after inserting
            case 'M12.Foundation:Accordion':
            case 'M12.Foundation:Orbit':
            case 'M12.Foundation:Tabs':
                App.init();
                break;

            // Some components are altered with extra nodes being created before/after the inserted node.
            // E.g. when inserting RevealModal, extra button (to trigger that modal) is created before.
            // To support such a case, we need fully reload the page, otherwise the extra node
            // is not rendered (because Neos doesn't know about it).
            // @see M12.Foundation.assistanceChildNodes in Settings.yaml
            //
            // Update for Neos 2.0-RC1 (2015/08/03):
            // After inserting node types listed below (and couple of others
            // - seems like all of them where we add some extra child nodes
            // which are not defined in NodeTypes) the page is reloaded anyway
            // due to early exit and warning `Node could not be found in rendered collection.`
            // generated from NodeActions.js in _insertNode() function.
            // Commenting out for now as it works perfectly fine (for now).
            // The only remaining issue is that the structure tree is not reloaded
            // so the newly inserted nodes are not visible there. Hopefully it's sth
            // which will be fixed in Neos soon.
            //
            //case 'M12.Foundation:Dropdown':
            //case 'M12.Foundation:DropdownContent':
            //case 'M12.Foundation:RevealModal':
            //	console.log('doing full page reload');
            //	Typo3Neos.Content.reloadPage();
            //	break;
        }
    });

    /**
     * Document ready: initialise all necessary components
     */
    $(document).ready(function () {
        // detect if we are in Neos back-end
        IS_NEOS_BE = typeof T3 !== 'undefined' || typeof Typo3Neos !== 'undefined';

        App.initNeosLocalStorage();
        App.init();
    });
})();
<commit_msg>Improve JS code for Slick carousel<commit_after>(function () {
    'use strict';

    /**
     * Check if we are in Neos back-end
     * @type {boolean}
     */
    let IS_NEOS_BE = false;

    /**
     * Pb.Site app
     */
    const App = {
        /**
         * Called on page load, to initialise all necessary components
         */
        initFundation: function () {
            // init zurb foundation
            $(document).foundation();

            // prevent some default events when in Neos back-end
            this.preventDefaultsWhenInNeosBackend();
        },

        /**
         * Init Slick Carousel
         */
        initSlickCarousel: function () {
            var slickEl = $('.m12-slickcarousel-slick');

            $(slickEl).on('init', (event, slick) => {
                // Support non-standard 'nextOnClick' option:
                if (slick.slickGetOption('nextOnClick')) {
                    $(slick.$slider).on('click', () => slick.slickNext());
                }
            });

            // Initialise Slick
            $(slickEl).slick();
        },

        /**
         * Initialise some localStorage variables,
         * so Neos is by default pre-configured (e.g. Structure panel is opened)
         */
        initNeosLocalStorage: function () {
            if (Modernizr.localstorage) {
                // Open the 'Structure' panel by default
                if (null === localStorage.getItem('contextStructureMode')) {
                    localStorage.setItem('contextStructureMode', false);
                }
            }
        },

        /**
         * Prevent some default events when in Neos back-end
         */
        preventDefaultsWhenInNeosBackend: function () {
            if (false === IS_NEOS_BE) {
                return;
            }

            // By default, after click on LABEL, focus is moved to related INPUT field.
            // Prevent that default action while in edit mode (@see TS-113)
            $('label')
                .children('.neos-inline-editable')
                .click(e => e.preventDefault());
        }
    };

    /**
     * Invoked when page finished loading (via AJAX) in Neos back-end.
     */
    document.addEventListener('Neos.PageLoaded', function () {
        // console.log('Neos.PageLoaded');
        App.initFundation();
        App.initSlickCarousel();
    });
    /**
     * Invoked when new content element has been added and rendered on page
     * (but w/o full page reload).
     */
    document.addEventListener('Neos.NodeCreated', function (e) {
        const createdNodeType = $(e.detail.element).data('node-_nodeType');
        const parentNodeType =  $(e.detail.element).data('node-__parent-node-type');
        // console.log('Neos.NodeCreated:', parentNodeType, '>', createdNodeType);

        // When certain node type is inserted...
        switch (createdNodeType) {
            // Some JavaScript components need to be fully re-initialised after inserting
            case 'M12.Foundation:Accordion':
            case 'M12.Foundation:Tabs':
                App.initFundation();
                break;
        }

        // When node is inserted inside certain parent node type...
        switch (parentNodeType) {
            case 'M12.SlickCarousel:Slick':
                App.initSlickCarousel();
                break;
        }
    });

    /**
     * Document ready: initialise all necessary components
     */
    $(document).ready(function () {
        // detect if we are in Neos back-end
        IS_NEOS_BE = typeof T3 !== 'undefined' || typeof Typo3Neos !== 'undefined';

        App.initNeosLocalStorage();
        App.initFundation();
        App.initSlickCarousel();
    });
})();
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var slackBot = require('slack-bot')(process.env.URL);

router.post('/', function(req, res) {
  // Cheap security
  if (req.query.secret !== process.env.SECRET) {
    res.sendStatus(404).end();
    return;
  }

  var alertMessage = req.query.alert || 'Some alert message';
  var type = req.query.type;

  switch(type) {
    case 'boxerror':
      alertMessage = 'Box Error';
      break;
    case 'elevatedclientalerts':
      alertMessage = 'Elevated Client Alerts';
      break;
    case 'elevatedserveralerts':
      alertMessage = 'Elevated Server Alerts';
      break;
    case 'jobfailed':
      alertMessage = 'Job Failed';
      break;
    case 'memoryquotaexceeded':
      alertMessage = 'Memory Quota Exceeded';
      break;
    case 'requesttimeouts':
      alertMessage = 'Request Timeouts';
      break;
    case 'slowrequests':
      alertMessage = 'Slow Requests';
      break;
  }

  slackBot.send({
    channel: '#alerts',
    username: 'Loggly',
    icon_emoji: ':loggly:',
    attachments: [{
      fallback: 'Alert',
      color: 'danger',
      text: 'Alert',
      fields: [{
        title: 'Type',
        value: alertMessage
      }]
    }]
  }, function() {
    res.sendStatus(201).end();
  });
});

module.exports = router;
<commit_msg>Add new loggly alert and default to type instead of default message<commit_after>var express = require('express');
var router = express.Router();
var slackBot = require('slack-bot')(process.env.URL);

router.post('/', function(req, res) {
  // Cheap security
  if (req.query.secret !== process.env.SECRET) {
    res.sendStatus(404).end();
    return;
  }

  var alertMessage = req.query.alert || req.query.type || 'Some alert message';
  var type = req.query.type;

  switch(type) {
    case 'boxerror':
      alertMessage = 'Box Error';
      break;
    case 'elevatedclientalerts':
      alertMessage = 'Elevated Client Alerts';
      break;
    case 'elevatedserveralerts':
      alertMessage = 'Elevated Server Alerts';
      break;
    case 'jobfailed':
      alertMessage = 'Job Failed';
      break;
    case 'memoryquotaexceeded':
      alertMessage = 'Memory Quota Exceeded';
      break;
    case 'requesttimeouts':
      alertMessage = 'Request Timeouts';
      break;
    case 'slowrequests':
      alertMessage = 'Slow Requests';
      break;
    case 'increased403s':
      alertMessage = 'Increased 403s';
      break;
  }

  slackBot.send({
    channel: '#alerts',
    username: 'Loggly',
    icon_emoji: ':loggly:',
    attachments: [{
      fallback: 'Alert',
      color: 'danger',
      text: 'Alert',
      fields: [{
        title: 'Type',
        value: alertMessage
      }]
    }]
  }, function() {
    res.sendStatus(201).end();
  });
});

module.exports = router;
<|endoftext|>