<commit_before>(function(root,factory) {

    if (typeof define != "undefined" && define.amd) define("jsyg-rotatable",["jsyg"],factory);
    else if (typeof JSYG != "undefined") {
        if (JSYG.Matrix && JSYG.StdConstruct) factory(JSYG);
        else throw new Error("Dependency is missing");
    }
    else throw new Error("JSYG is needed");

})(this,function(JSYG) {

    "use strict";

    /**
     * paliers pour "aimanter" la rotation
     */
    function Steps(list,strength) {
        /**
         * Tableau des paliers en degrés
         */
        this.list = list || [];
        /**
         * Force de l'aimantation en degrés
         */
        this.strength = JSYG.isNumeric(strength) ? strength : 3;
    };

    /**
     * nécessite le module Rotatable
     * Rotation de l'élément. Fonctionne bien avec les éléments SVG. Les r�actions sont un peu bizarres avec les éléments HTML, à �viter.

     * @param arg argument JSYG faisant référénce à l'élément
     * @param opt optionnel, objet définissant les options. Si défini, la rotation est activ�e
     * @returns {Rotatable}
     */
    function Rotatable(arg,opt) {

        /**
         * Paliers "aimantés" lors de la rotation, en degrés
         */
        this.steps = new Steps();

        if (arg) {

            this.setNode(arg);
            this.field = this.node;

            if (opt) this.enable(opt);
        }
        else if (opt) this.set(opt);
    };

    Rotatable.prototype = new JSYG.StdConstruct();

    Rotatable.prototype.constructor = Rotatable;
    /**
     * Champ(s) sur le(s)quel(s) on clique pour déclencher la rotation. Par défaut l'élément lui-même.
     */
    Rotatable.prototype.field = null;
    /**
     * Evenement pour déclencher la rotation
     */
    Rotatable.prototype.event = 'mousedown';
    /**
     * Restriction à un bouton de la souris (1 bouton gauche, 2 bouton du milieu, 3 bouton droit)
     */
    Rotatable.prototype.eventWhich = 1;
    /**
     * Classe appliquée à l'élément pendant la rotation
     */
    Rotatable.prototype.className = false;
    /**
     * Fonction(s) à exécuter quand on pr�pare un d�placement (mousedown sur le contr�le)
     */
    Rotatable.prototype.onstart=null;
    /**
     * Fonction(s) à exécuter quand on commence la rotation
     */
    Rotatable.prototype.ondragstart=null;
    /**
     * Fonction(s) à exécuter pendant la rotation
     */
    Rotatable.prototype.ondrag=null;
    /**
     * Fonction(s) à exécuter à la fin de la rotation
     */
    Rotatable.prototype.ondragend=null;
    /**
     * Fonction(s) à exécuter au relâchement du bouton souris (qu'il y ait eu rotation ou non)
     */
    Rotatable.prototype.onend=null;
    /**
     * Indique si la rotation est activ�e ou non
     */
    Rotatable.prototype.enabled = false;
    /**
     * Curseur à utiliser pendant la rotation
     */
    Rotatable.prototype.cursor = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACqUlEQVRIia2UsU8UQRTGZ97su73dvWOzu3d73Ibl+AOgxEZ7Q6UklhYWlMaGioLEyguFoTJYEQuNsSFiJ0b+ACxsjZAYqcAEK/E4IPfZ7Oi6uwd7hJdMtfO933zzvR0hShSS8jxvZnd39zYAlNGVKt08juNZwzAObduO8K+619K80+nM12q1vmEYmJqa2rQsa2VnZ+ddCnQ1R4kQRNQnIkgp/1umafbGxsZWS4OyGwEgDMP7RNQXQqBoEREcxzlg5huXQpKPjEzV6/V5y7L6zAxmfub7/pbjOCfM/BdUrVZ/hWF4M5G4Q09v2/bnIAgeZiEAkA3Z87wnSqkBEWknP4e6AADXdZcMwwAzo16vP09vBIBKpTLjeZ6bBZumOdDX1el0NnKA1OkPiAhKKTQajddZQFGYSU7LSikQESqVylnOBQDMzc3dk1JCKQVmPr00sAzYNM19pZQ+3GIO0Gw2uzqwIAg+lWme1tdqtTUighACYRhu5ABEtKIBzPx0VMDk5OQjKaWequ0LAUKIlVEBvu8vpPR5gGVZXSEEpJRwXXcrudr8PBc0B4Dx8fE17aDdbr/PAeI4vqufAMuyTkYJWQghHcf5pp8Tz/OWcoAkqJ7+aTzP65YFTExMLBiGgWSKznq93tfCf8H3/VWlFKSUYOZBdu7Pz8/fHB8fvwXwKq2TUm6mRvRDIrlVeJeO4xwIIaCUgmmag0ajsZwGTU9PnyJTURTZrVbrY7Va/b2+vn5nqHMAYOZZpdSRnmkiAjPvB0HwYm9v74tt233DMA6FEDNZUKq+DwUk9FnLso6klNDB6SdEPwlE9KPsIBRCAKDdbr9k5jPtJr2klAO9fSRAESgMw8VWq7UhpdyWUvaZeRBF0eMrObgIBADNZrMXx/GDa2leBEszy2j+AL5S5bW3LnfHAAAAAElFTkSuQmCC) 12 12, auto';

    /**
     * Débute la rotation (fonction déclenché sur mousedown)
     * @param e évènement Event
     * @returns {Rotatable}
     */
    Rotatable.prototype.start = function(e) {

        e.preventDefault();

        var that = this,
        jNode = new JSYG(this.node),
        cursor = this.cursor;

        if (cursor) {
            new JSYG(this.field).each(function() {
                var field = new JSYG(this);
                field.data('cursorInit',field.css('cursor'));
                field.css('cursor',cursor);
            });
        }

        if (that.className) jNode.classAdd(that.className);

        var mtxInit = jNode.getMtx(),
        mtxScreenInit = (function() {
            var mtx = jNode.getMtx('screen');
            if (!jNode.isSVG()) {
                var dim = jNode.getDim('page');
                mtx = new JSYG.Matrix().translate(dim.x,dim.y).multiply(mtx);
            }
            return mtx;
        })(),
        scaleX = mtxInit.scaleX(),
        scaleY = mtxInit.scaleY(),
        dec = jNode.getShift(),
        screenDec = dec.mtx(mtxScreenInit),
        angleInit = mtxScreenInit.rotate(),
        angleMouseInit = Math.atan2(e.clientX-screenDec.x,e.clientY-screenDec.y) * 180 / Math.PI,

        hasChanged = false,
        triggerDragStart = false;

        function mousemoveFct(e) {

            if (!triggerDragStart) {
                that.trigger('dragstart',that.node,e);
                triggerDragStart = true;
            }

            var newAngle = angleInit + angleMouseInit - Math.atan2(e.clientX-screenDec.x,e.clientY-screenDec.y) * 180 / Math.PI;

            if (that.steps.list.length > 0) {
                that.steps.list.forEach(function(step) {
                    if (Math.abs(newAngle-step) < that.steps.strength || Math.abs(Math.abs(newAngle-step)-360) < that.steps.strength) {newAngle = step;}
                });
            }

            var mtx = mtxInit.translate(dec.x,dec.y)
                .scaleNonUniform(1/scaleX,1/scaleY)
                .rotate(-angleInit).rotate(newAngle)
                .scaleNonUniform(scaleX,scaleY)
                .translate(-dec.x,-dec.y);

            jNode.setMtx(mtx);

            hasChanged = true;
            that.trigger('drag',that.node,e);
        }

        function remove(e) {

            if (that.className) jNode.classRemove(that.className);

            new JSYG(that.field).each(function() {
                var field = new JSYG(this);
                field.css('cursor',field.data('cursorInit'));
            });

            new JSYG(this).off({
                'mousemove':mousemoveFct,
                'mouseup':remove
            });

            if (hasChanged) {
                if (that.type!=='transform' && that.shape === 'noAttribute') jNode.mtx2attrs();
                that.trigger('dragend',that.node,e);
            }
            that.trigger('end',that.node,e);
        };

        new JSYG(document).on({
            'mousemove':mousemoveFct,
            'mouseup':remove
        });

        this.trigger('start',that.node,e);

        return this;
    };

    /**
     * Activation de la rotation
     * @param opt optionnel, objet définissant les options
     * @returns {Rotatable}
     */
    Rotatable.prototype.enable = function(opt) {

        this.disable();

        if (opt) this.set(opt);

        var that = this,
        evt = opt && opt.evt;

        function start(e) {
            if (that.eventWhich && e.which != that.eventWhich) return;
            that.start(e);
        }

        new JSYG(this.field).each(function() {
            var field = new JSYG(this);
            field.on(that.event,start);
        });

        this.disable = function() {
            new JSYG(this.field).each(function() {
                var field = new JSYG(this);
                field.off(that.event,start);
            });
            this.enabled = false;
            return this;
        };

        this.enabled = true;

        if (evt) { this.start(evt); }

        return this;
    };

    /**
     * D�sactivation de la rotation
     * @returns {Rotatable}
     */
    Rotatable.prototype.disable = function() { return this; };

    JSYG.Rotatable = Rotatable;

    var plugin = JSYG.bindPlugin(Rotatable);
    /**
     * nécessite le module Rotatable

     * Rotation de l'élément par drag&drop souris.

     * Fonctionne bien avec les éléments SVG. Les réactions sont un peu bizarres avec les éléments HTML, à éviter.

     * @returns {JSYG}
     * @see Rotatable pour une utilisation détaillée
     * @example
new JSYG('#myShape').draggable();
     *
     * //utilisation avancée
     * new JSYG('#myShape').draggable({
     * 	steps : {
     * 		list : [0,90,180,270]
     *	},
     *	event:'ctrl-left-mousedown',
     *	ondragend:function() {
     *		alert("Rotation de l'élément : "+ new JSYG(this).rotate() + "�");
     *	}
     *});
     */
    JSYG.prototype.rotatable = function() { return plugin.apply(this,arguments); };

    return Rotatable;

});<commit_msg>accents<commit_after>(function(root,factory) {

    if (typeof define != "undefined" && define.amd) define("jsyg-rotatable",["jsyg"],factory);
    else if (typeof JSYG != "undefined") {
        if (JSYG.Matrix && JSYG.StdConstruct) factory(JSYG);
        else throw new Error("Dependency is missing");
    }
    else throw new Error("JSYG is needed");

})(this,function(JSYG) {

    "use strict";

    /**
     * paliers pour "aimanter" la rotation
     */
    function Steps(list,strength) {
        /**
         * Tableau des paliers en degrés
         */
        this.list = list || [];
        /**
         * Force de l'aimantation en degrés
         */
        this.strength = JSYG.isNumeric(strength) ? strength : 3;
    };

    /**
     * nécessite le module Rotatable
     * Rotation de l'élément. Fonctionne bien avec les éléments SVG. Les réactions sont un peu bizarres avec les éléments HTML, à éviter.

     * @param arg argument JSYG faisant référénce à l'élément
     * @param opt optionnel, objet définissant les options. Si défini, la rotation est activée
     * @returns {Rotatable}
     */
    function Rotatable(arg,opt) {

        /**
         * Paliers "aimantés" lors de la rotation, en degrés
         */
        this.steps = new Steps();

        if (arg) {

            this.setNode(arg);
            this.field = this.node;

            if (opt) this.enable(opt);
        }
        else if (opt) this.set(opt);
    };

    Rotatable.prototype = new JSYG.StdConstruct();

    Rotatable.prototype.constructor = Rotatable;
    /**
     * Champ(s) sur le(s)quel(s) on clique pour déclencher la rotation. Par défaut l'élément lui-même.
     */
    Rotatable.prototype.field = null;
    /**
     * Evenement pour déclencher la rotation
     */
    Rotatable.prototype.event = 'mousedown';
    /**
     * Restriction à un bouton de la souris (1 bouton gauche, 2 bouton du milieu, 3 bouton droit)
     */
    Rotatable.prototype.eventWhich = 1;
    /**
     * Classe appliquée à l'élément pendant la rotation
     */
    Rotatable.prototype.className = false;
    /**
     * Fonction(s) à exécuter quand on prépare un déplacement (mousedown sur le controle)
     */
    Rotatable.prototype.onstart=null;
    /**
     * Fonction(s) à exécuter quand on commence la rotation
     */
    Rotatable.prototype.ondragstart=null;
    /**
     * Fonction(s) à exécuter pendant la rotation
     */
    Rotatable.prototype.ondrag=null;
    /**
     * Fonction(s) à exécuter à la fin de la rotation
     */
    Rotatable.prototype.ondragend=null;
    /**
     * Fonction(s) à exécuter au relâchement du bouton souris (qu'il y ait eu rotation ou non)
     */
    Rotatable.prototype.onend=null;
    /**
     * Indique si la rotation est activée ou non
     */
    Rotatable.prototype.enabled = false;
    /**
     * Curseur à utiliser pendant la rotation
     */
    Rotatable.prototype.cursor = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACqUlEQVRIia2UsU8UQRTGZ97su73dvWOzu3d73Ibl+AOgxEZ7Q6UklhYWlMaGioLEyguFoTJYEQuNsSFiJ0b+ACxsjZAYqcAEK/E4IPfZ7Oi6uwd7hJdMtfO933zzvR0hShSS8jxvZnd39zYAlNGVKt08juNZwzAObduO8K+619K80+nM12q1vmEYmJqa2rQsa2VnZ+ddCnQ1R4kQRNQnIkgp/1umafbGxsZWS4OyGwEgDMP7RNQXQqBoEREcxzlg5huXQpKPjEzV6/V5y7L6zAxmfub7/pbjOCfM/BdUrVZ/hWF4M5G4Q09v2/bnIAgeZiEAkA3Z87wnSqkBEWknP4e6AADXdZcMwwAzo16vP09vBIBKpTLjeZ6bBZumOdDX1el0NnKA1OkPiAhKKTQajddZQFGYSU7LSikQESqVylnOBQDMzc3dk1JCKQVmPr00sAzYNM19pZQ+3GIO0Gw2uzqwIAg+lWme1tdqtTUighACYRhu5ABEtKIBzPx0VMDk5OQjKaWequ0LAUKIlVEBvu8vpPR5gGVZXSEEpJRwXXcrudr8PBc0B4Dx8fE17aDdbr/PAeI4vqufAMuyTkYJWQghHcf5pp8Tz/OWcoAkqJ7+aTzP65YFTExMLBiGgWSKznq93tfCf8H3/VWlFKSUYOZBdu7Pz8/fHB8fvwXwKq2TUm6mRvRDIrlVeJeO4xwIIaCUgmmag0ajsZwGTU9PnyJTURTZrVbrY7Va/b2+vn5nqHMAYOZZpdSRnmkiAjPvB0HwYm9v74tt233DMA6FEDNZUKq+DwUk9FnLso6klNDB6SdEPwlE9KPsIBRCAKDdbr9k5jPtJr2klAO9fSRAESgMw8VWq7UhpdyWUvaZeRBF0eMrObgIBADNZrMXx/GDa2leBEszy2j+AL5S5bW3LnfHAAAAAElFTkSuQmCC) 12 12, auto';

    /**
     * Débute la rotation (fonction déclenché sur mousedown)
     * @param e évènement Event
     * @returns {Rotatable}
     */
    Rotatable.prototype.start = function(e) {

        e.preventDefault();

        var that = this,
        jNode = new JSYG(this.node),
        cursor = this.cursor;

        if (cursor) {
            new JSYG(this.field).each(function() {
                var field = new JSYG(this);
                field.data('cursorInit',field.css('cursor'));
                field.css('cursor',cursor);
            });
        }

        if (that.className) jNode.classAdd(that.className);

        var mtxInit = jNode.getMtx(),
        mtxScreenInit = (function() {
            var mtx = jNode.getMtx('screen');
            if (!jNode.isSVG()) {
                var dim = jNode.getDim('page');
                mtx = new JSYG.Matrix().translate(dim.x,dim.y).multiply(mtx);
            }
            return mtx;
        })(),
        scaleX = mtxInit.scaleX(),
        scaleY = mtxInit.scaleY(),
        dec = jNode.getShift(),
        screenDec = dec.mtx(mtxScreenInit),
        angleInit = mtxScreenInit.rotate(),
        angleMouseInit = Math.atan2(e.clientX-screenDec.x,e.clientY-screenDec.y) * 180 / Math.PI,

        hasChanged = false,
        triggerDragStart = false;

        function mousemoveFct(e) {

            if (!triggerDragStart) {
                that.trigger('dragstart',that.node,e);
                triggerDragStart = true;
            }

            var newAngle = angleInit + angleMouseInit - Math.atan2(e.clientX-screenDec.x,e.clientY-screenDec.y) * 180 / Math.PI;

            if (that.steps.list.length > 0) {
                that.steps.list.forEach(function(step) {
                    if (Math.abs(newAngle-step) < that.steps.strength || Math.abs(Math.abs(newAngle-step)-360) < that.steps.strength) {newAngle = step;}
                });
            }

            var mtx = mtxInit.translate(dec.x,dec.y)
                .scaleNonUniform(1/scaleX,1/scaleY)
                .rotate(-angleInit).rotate(newAngle)
                .scaleNonUniform(scaleX,scaleY)
                .translate(-dec.x,-dec.y);

            jNode.setMtx(mtx);

            hasChanged = true;
            that.trigger('drag',that.node,e);
        }

        function remove(e) {

            if (that.className) jNode.classRemove(that.className);

            new JSYG(that.field).each(function() {
                var field = new JSYG(this);
                field.css('cursor',field.data('cursorInit'));
            });

            new JSYG(this).off({
                'mousemove':mousemoveFct,
                'mouseup':remove
            });

            if (hasChanged) {
                if (that.type!=='transform' && that.shape === 'noAttribute') jNode.mtx2attrs();
                that.trigger('dragend',that.node,e);
            }
            that.trigger('end',that.node,e);
        };

        new JSYG(document).on({
            'mousemove':mousemoveFct,
            'mouseup':remove
        });

        this.trigger('start',that.node,e);

        return this;
    };

    /**
     * Activation de la rotation
     * @param opt optionnel, objet définissant les options
     * @returns {Rotatable}
     */
    Rotatable.prototype.enable = function(opt) {

        this.disable();

        if (opt) this.set(opt);

        var that = this,
        evt = opt && opt.evt;

        function start(e) {
            if (that.eventWhich && e.which != that.eventWhich) return;
            that.start(e);
        }

        new JSYG(this.field).each(function() {
            var field = new JSYG(this);
            field.on(that.event,start);
        });

        this.disable = function() {
            new JSYG(this.field).each(function() {
                var field = new JSYG(this);
                field.off(that.event,start);
            });
            this.enabled = false;
            return this;
        };

        this.enabled = true;

        if (evt) { this.start(evt); }

        return this;
    };

    /**
     * Désactivation de la rotation
     * @returns {Rotatable}
     */
    Rotatable.prototype.disable = function() { return this; };

    JSYG.Rotatable = Rotatable;

    var plugin = JSYG.bindPlugin(Rotatable);
    /**
     * nécessite le module Rotatable

     * Rotation de l'élément par drag&drop souris.

     * Fonctionne bien avec les éléments SVG. Les réactions sont un peu bizarres avec les éléments HTML, à éviter.

     * @returns {JSYG}
     * @see Rotatable pour une utilisation détaillée
     * @example
new JSYG('#myShape').draggable();
     *
     * //utilisation avancée
     * new JSYG('#myShape').draggable({
     * 	steps : {
     * 		list : [0,90,180,270]
     *	},
     *	event:'ctrl-left-mousedown',
     *	ondragend:function() {
     *		alert("Rotation de l'élément : "+ new JSYG(this).rotate() + "°");
     *	}
     *});
     */
    JSYG.prototype.rotatable = function() { return plugin.apply(this,arguments); };

    return Rotatable;

});<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import passport from './core/passport';
import schema from './data/schema';
import Router from './routes';
import assets from './assets';
import { port, auth, analytics } from './config';

//config and test
import {connect, disconnect, SUCCESS, FAIL, getUser, setUser} from './servers/config'
import {home, test_login} from './servers/test/testController';
//apis
import {addTestApi, addAdministerApi} from './router_background'
import {addLanguageAPI, addLoginAPI, addOtherAPI, addUserAPI, addRepoAPI} from './router'
//circle
import {setATimer} from './servers/logic/HandleRecommendLogic'

var session = require('express-session');
connect();

const server = global.server = express();
const ret_success = 'success';

var log4js = require('log4js');
log4js.configure({
  appenders: [
    { type: 'console' }, //控制台输出
    {
      type: 'file', //文件输出
      filename: 'logs/access_net.log',
      maxLogSize: 1024,
      backups: 4,
      category: 'normal'
    }
  ]
});
var logger2 = log4js.getLogger('normal');
logger2.setLevel('INFO');

process.on('uncaughtException', function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack);
});

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.use(cookieParser());
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
//server.use(log4js.connectLogger(logger2, {level:log4js.levels.INFO, format:':method :url'}));
server.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {maxAge: 3600000}
}));

//
// Authentication
// -----------------------------------------------------------------------------
server.use(expressJwt({
  secret: auth.jwt.secret,
  credentialsRequired: false,
  /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
  getToken: req => req.cookies.id_token,
  /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
server.use(passport.initialize());

server.get('/login/facebook',
  passport.authenticate('facebook', {scope: ['email', 'user_location'], session: false})
);
server.get('/login/facebook/return',
  passport.authenticate('facebook', {failureRedirect: '/login', session: false}),
  (req, res) => {
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    const token = jwt.sign(req.user, auth.jwt.secret, {expiresIn});
    res.cookie('id_token', token, {maxAge: 1000 * expiresIn, httpOnly: true});
    res.redirect('/');
  }
);

//
// Register API middleware
// ------------------------------------------------------------------------------
server.use('/graphql', expressGraphQL(req => ({
  schema,
  graphiql: true,
  rootValue: {request: req},
  pretty: process.env.NODE_ENV !== 'production',
})));

// ---------------------------------------------------------------------------------------------------------------my part

//test
//server.get('/api/test', (req, res) => {
//  res.send({res:1});
//});

//test login
//server.get('/api/test_login', test_login);

addAdministerApi(server);
addOtherAPI(server);
addLanguageAPI(server);
addLoginAPI(server);
addRepoAPI(server);
addUserAPI(server);
addTestApi(server);
addAdministerApi(server);
//circle();
setATimer();

//
// Register server-side rendering middleware
// ---------------------------------------------------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const template = require('./views/index.jade');
    const data = {title: '', description: '', css: '', body: '', entry: assets.main.js};

    if (process.env.NODE_ENV === 'production') {
      data.trackingId = analytics.google.trackingId;
    }

    const css = [];
    const context = {
      insertCss: styles => css.push(styles._getCss()),
      onSetTitle: value => (data.title = value),
      onSetMeta: (key, value) => (data[key] = value),
      onPageNotFound: () => (statusCode = 404),
    };

    await Router.dispatch({path: req.path, query: req.query, context}, (state, component) => {
      data.body = ReactDOM.renderToString(component);
      data.css = css.join('');
    });

    res.status(statusCode);
    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');

server.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  console.log(pe.render(err)); // eslint-disable-line no-console
  const template = require('./views/error.jade');
  const statusCode = err.status || 500;
  res.status(statusCode);
  res.send(template({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
  }));
});

//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
  /* eslint-disable no-console */
  console.log(`The server is running at http://localhost:${port}/`);
});
<commit_msg>fix a bug<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import passport from './core/passport';
import schema from './data/schema';
import Router from './routes';
import assets from './assets';
import { port, auth, analytics } from './config';

//config and test
import {connect, disconnect, SUCCESS, FAIL, getUser, setUser} from './servers/config'
import {home, test_login} from './servers/test/testController';
//apis
import {addTestApi, addAdministerApi} from './router_background'
import {addLanguageAPI, addLoginAPI, addOtherAPI, addUserAPI, addRepoAPI} from './router'
//circle
import {setATimer} from './servers/logic/HandleRecommendLogic'

var session = require('express-session');
connect();

const server = global.server = express();
const ret_success = 'success';

//var log4js = require('log4js');
//log4js.configure({
//  appenders: [
//    { type: 'console' }, //控制台输出
//    {
//      type: 'file', //文件输出
//      filename: 'logs/access_net.log',
//      maxLogSize: 1024,
//      backups: 4,
//      category: 'normal'
//    }
//  ]
//});
//var logger2 = log4js.getLogger('normal');
//logger2.setLevel('INFO');

process.on('uncaughtException', function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack);
});

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.use(cookieParser());
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
//server.use(log4js.connectLogger(logger2, {level:log4js.levels.INFO, format:':method :url'}));
server.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {maxAge: 3600000}
}));

//
// Authentication
// -----------------------------------------------------------------------------
server.use(expressJwt({
  secret: auth.jwt.secret,
  credentialsRequired: false,
  /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
  getToken: req => req.cookies.id_token,
  /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
server.use(passport.initialize());

server.get('/login/facebook',
  passport.authenticate('facebook', {scope: ['email', 'user_location'], session: false})
);
server.get('/login/facebook/return',
  passport.authenticate('facebook', {failureRedirect: '/login', session: false}),
  (req, res) => {
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    const token = jwt.sign(req.user, auth.jwt.secret, {expiresIn});
    res.cookie('id_token', token, {maxAge: 1000 * expiresIn, httpOnly: true});
    res.redirect('/');
  }
);

//
// Register API middleware
// ------------------------------------------------------------------------------
server.use('/graphql', expressGraphQL(req => ({
  schema,
  graphiql: true,
  rootValue: {request: req},
  pretty: process.env.NODE_ENV !== 'production',
})));

// ---------------------------------------------------------------------------------------------------------------my part

//test
//server.get('/api/test', (req, res) => {
//  res.send({res:1});
//});

//test login
//server.get('/api/test_login', test_login);

addAdministerApi(server);
addOtherAPI(server);
addLanguageAPI(server);
addLoginAPI(server);
addRepoAPI(server);
addUserAPI(server);
addTestApi(server);
addAdministerApi(server);
//circle();
setATimer();

//
// Register server-side rendering middleware
// ---------------------------------------------------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const template = require('./views/index.jade');
    const data = {title: '', description: '', css: '', body: '', entry: assets.main.js};

    if (process.env.NODE_ENV === 'production') {
      data.trackingId = analytics.google.trackingId;
    }

    const css = [];
    const context = {
      insertCss: styles => css.push(styles._getCss()),
      onSetTitle: value => (data.title = value),
      onSetMeta: (key, value) => (data[key] = value),
      onPageNotFound: () => (statusCode = 404),
    };

    await Router.dispatch({path: req.path, query: req.query, context}, (state, component) => {
      data.body = ReactDOM.renderToString(component);
      data.css = css.join('');
    });

    res.status(statusCode);
    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');

server.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  console.log(pe.render(err)); // eslint-disable-line no-console
  const template = require('./views/error.jade');
  const statusCode = err.status || 500;
  res.status(statusCode);
  res.send(template({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
  }));
});

//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
  /* eslint-disable no-console */
  console.log(`The server is running at http://localhost:${port}/`);
});
<|endoftext|>


<commit_before>export { Base, To };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as FloatValue from "../FloatValue.js";

/**
 * A base class for extracting and keeping weights. It composes of a Float32Array and a shape. It can
 * be used as CNN (depthwise, pointwise and bias) filter weights.
 *
 * @member {number} elementOffsetBegin
 *   The beginning position (i.e. array index) to extract from inputWeightsArray. If this value is negative, the extraction will
 * fail (i.e. ( bInitOk == false ) ).
 *
 * @member {number} elementOffsetEnd
 *   The ending position (i.e. array index) after extracting from inputWeightsArray. It is not inclusive and can be used as the
 * beginning position of next (another) extraction. It is meaningful only if ( bInitOk == true ).
 *
 * @member {number} elementExtractedCount
 *   How many weights (i.e. elements) will be extracted from inputWeightsArray. It should be a non-negative integer value.
 *
 *     - If too many elements need to be extracted (exceeds the inputWeightsArray.length) or elementExtractedCount is NaN or
 *         elementExtractedCount is negative, the extraction will fail (i.e. ( bInitOk == false ) ).
 *
 * @member {boolean} bInitOk
 *   If .init() success, it will be true.
 */
class Base extends Recyclable.Root {

  /**
   * Used as default Weights.Base provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Weights.Base.Pool", Base, Base.setAsConstructor );

  /**
   * Just record the begin and length without checking them. Please call extract() to finish extracting.
   */
  constructor() {
    super();
    Base.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    Base.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    // Do nothing.
  }

  /** @override */
  disposeResources() {
    this.bInitOk = undefined;
    this.elementOffsetEnd = undefined;
    this.elementExtractedCount = undefined;
    this.elementOffsetBegin = undefined;
    super.disposeResources();
  }

  /**
   * Determine .elementOffsetEnd according to the inputWeightArray.lnegth, .elementOffsetBegin and .elementExtractedCount.
   *
   * @param {number[]|Float32Array} inputWeightArray
   *   The underlying weights source array to be extracted from. It will not be kept by this object.
   *
   * @return {boolean} Return false, if extraction failed.
   */
  init( inputWeightArray, elementOffsetBegin, elementExtractedCount ) {
    this.elementOffsetBegin = elementOffsetBegin;
    this.elementExtractedCount = elementExtractedCount;
    this.bInitOk = false;

    if ( Number.isNaN( this.elementExtractedCount ) )
      return false;  // Failed, if NaN.

    if ( this.elementExtractedCount < 0 )
      return false;  // Failed, if negative.

    this.elementOffsetEnd = this.elementOffsetBegin + this.elementExtractedCount;
    if ( this.elementOffsetEnd > inputWeightArray.length )
      return false;  // Failed, if out of array index range.

    this.bInitOk = true;
    return true;     // Success.
  }

//!!! (2021/12/98 Remarked) Using bounds [ -2^24, +2^24 ] seems enough.
//   /**
//    * Confirm:
//    *   - Every element is not NaN. (If it is, become 0.)
//    *   - The smallest non-zero Math.abs( element ) is 2^(-24). (i.e. If ( -2^(-24) < element < +2^(-24) ), become 0.)
//    *   - The largest Math.abs( element ) is 2^(+24).
//    *
//    * This is mainly for ensuring PointDepthPoint's output is legal float32:
//    *   - PointDepthPoint is composed of 3 convolutions: pointwise1-depthwise-pointwise2.
//    *   - Suppose every convolution has 4096 (= 2^12) input channels. (The bias is viewed as the last (i.e. 4095th) channels.)
//    *   - Suppose depthwise uses 4x4 (= 2^4) filter for every channel.
//    *   - Suppose every convolution does not have activation function (so that its result is unbounded).
//    *   - If every Math.abs( pointwise1Input ) is restected to 0 or between [ 2^(-24), 2^24 ].
//    *   - If every Math.abs( weight ) of pointwise1, depthwise, pointwise2 is restected to 0 or between [ 2^(-24), 2^24 ].
//    *   - The Math.abs( pointwise1Result ) will be restriced to 0 or between [ 2^(-(24+24)), 2^(24+24+12) ] = [ 2^(-48), 2^60 ].
//    *   - The Math.abs( depthwiseResult  ) will be restriced to 0 or between [ 2^(-(48+24)), 2^(60+24+4)  ] = [ 2^(-72), 2^88 ].
//    *   - The Math.abs( pointwise2Result ) will be restriced to 0 or between [ 2^(-(72+24)), 2^(88+24+12) ] = [ 2^(-96), 2^124 ].
//    *   - So the result is still legal float32 because Math.abs( float32 ) could be either 0 or between [ 2^(-126), 2^126 ].
//    *
//    * The 2^24 as input element should be enough for most situation:
//    *   - Color image: The R, G, B, A channels are 8 bits (2^8) individually.
//    *   - Sound track: 8 bits (2^8), or 16 bits (2^16), or 20 bits (2^20), or 24 bits (2^24). But not 32 bits (2^32)
//    *   - Unicode character code point: 21 bits (2^21).
//    *
//    *
//    *

//    *              -2^(+24)       -2^(-24)                      +2^(-24)       +2^(+24)
//    *            NEGATIVE_MIN   NEGATIVE_MAX        0         POSITIVE_MIN   POSITIVE_MAX
//    *   --------------|--------------|--------------|--------------|--------------|--------------
//    *
//    * Restricted to:
//    *                 |--------------|00000000000000000000000000000|--------------|
//    *

//    *
//    *
//    * @param {Float32Array} source
//    *   The source Float32Array.
//    *
//    * @return {Float32Array}
//    *   Return a copy of source. Every element (float32):
//    *     - If ( Number.isNaN( element ) == true ), let it become 0.
//    *     - If ( element != 0 ), Math.abs( element ) will be restricted between [ 2^(-24), 2^24 ].
//    *     - ( Math.sign( element ) * Math.abs( element ) ) will be restricted between [ -2^(24), 2^24 ].
//    */
//   static Float32Array_CloneLegal( sourceArray ) {
//     const POSITIVE_MIN = Math.pow( 2, -24 );
//     const POSITIVE_MAX = Math.pow( 2, +24 );
//     const NEGATIVE_MIN = - POSITIVE_MAX; // - Math.pow( 2, +24 )
//     const NEGATIVE_MAX = - POSITIVE_MIN; // - Math.pow( 2, -24 )
//
//     let resultArray = new Float32Array( sourceArray.length );
//     for ( let i = 0; i < sourceArray.length; ++i ) {
//       let element = sourceArray[ i ];
//
//       let restricted;
//       if ( Number.isNaN( element ) ) {
//         restricted = 0;
//
//       } else if ( element >= POSITIVE_MIN ) {
//         if ( element > POSITIVE_MAX )
//           restricted = POSITIVE_MAX;
//         else
//           restricted = element;
//
//       } else if ( element <= NEGATIVE_MAX ) {
//         if ( element < NEGATIVE_MIN )
//           restricted = NEGATIVE_MIN;
//         else
//           restricted = element;
//
//       } else { // ( NEGATIVE_MAX < element < POSITIVE_MIN ) (Note: Zero is inside.)
//         restricted = 0;
//       }
//
//       resultArray[ i ] = restricted;
//     }
//     return resultArray;
//   }

}

//!!! ...unfinished... (2022/01/10)
/*
 * When ( x < 0.0000001 ), the tf.tanh( x ) will be 0.
 * That is, the precision of tf.tanh() may be 0.0000001 (= 1e-7 ).
 *
 * Consider the ActivationEscaping inputDomainLinear of tanh() is [ -0.005, +0.005 ] simultaneously. The value bounds of result
 * after filter-bias (no matter pointwise or depthwise) should be compatible with [ -0.005, +0.005 ] with precision 0.0000001 (= 1e-7 ).
 *
 * For example,
 *   - [ -0.005, +0.005 ] with precision 0.0000001 (= 1e-7 ).
 *   - [ -0.5, +0.5 ] with precision 0.00001 (= 1e-5 ).
 *   - [ -5, +5 ] with precision 0.0001 (= 1e-4 ).
 *   - [ -50, +50 ] with precision 0.001 (= 1e-3 ).
 *   - [ -500, +500 ] with precision 0.01 (= 1e-2 ).
 *   - [ -5000, +5000 ] with precision 0.1 (= 1e-1 ).
 *   - [ -50000, +50000 ] with precision 1 (= 1e+0 ).
 *   - [ -5e+4, +5e+4 ] with precision 1 (= 1e+0 ).
 *   - [ 0, +100000 ] with precision 1 (= 1e+0 ).
 *   - [ 0, +1e+5 ] with precision 1 (= 1e+0 ).
 *
 *
 *
 *
 *
 * For this reason, the Weights.Base.ValueBounds may be more less than [ -( 2 ** 24 ), +( 2 ** 24 ) ].
 * Perhaps, [ -1, +1 ] is better.?
 *
 */

/**
 * This is mainly for ensuring Block's output is legal float32:
 *   - Block is composed of 3 convolutions: pointwise1-depthwise-pointwise2.
 *   - Suppose every convolution has 4096 (= 2^12) input channels. (The bias is viewed as the last (i.e. 4095th) channels.)
 *   - Suppose depthwise uses 4x4 (= 2^4) filter for every channel.
 *   - Suppose every convolution does not have activation function (so that its result is unbounded).
 *   - If every element of pointwise1Input is bounds to [ -2^24, +2^24 ].
 *   - If every element of weights of pointwise1, depthwise, pointwise2 is bounds to [ -2^24, +2^24 ].
 *   - Every element of pointwise1Result will be bounds to [ -2^(24+24+12), +2^(24+24+12) ] = [ -2^60,  +2^60  ].
 *   - Every element of depthwiseResult  will be bounds to [ -2^(60+24+4),  +2^(60+24+4)  ] = [ -2^88,  +2^88  ].
 *   - Every element of pointwise2Result will be bounds to [ -2^(88+24+12), +2^(88+24+12) ] = [ -2^124, +2^124 ].
 *   - So the result is still legal float32 (which could represent floating-point value between [ -2^126, +2^126 ]).
 *
 * The 2^24 as input element should be enough for most situation:
 *   - Color image: The R, G, B, A channels are 8 bits (2^8) individually.
 *   - Sound track: 8 bits (2^8), or 16 bits (2^16), or 20 bits (2^20), or 24 bits (2^24). But not 32 bits (2^32)
 *   - Unicode character code point: 21 bits (2^21).
 */
Base.ValueBounds = new FloatValue.Bounds( -( 2 ** 24 ), +( 2 ** 24 ) );

/**
 * Provides static methods for converting weight to parameter.
 */
class To {

  /** @return {number} Return the absolute value of the trucated value (i.e. integer). */
  static IntegerZeroPositive( v ) {
    return Math.abs( Math.trunc( v ) );
  }

  /**
   * @param {any[]} lookUpArray
   *   The value will be converted into an integer between [ 0, lookUpArray.length ). Use it as array index.
   * Return lookUpArray[ index ].
   *
   * @return {any}
   *   Convert number value into an integer between [ 0, lookUpArray.length ). Use it as array index. Return
   * the looked up element value.
   */
  static ArrayElement( value, lookUpArray ) {
    let i = To.IntegerZeroPositive( value ) % lookUpArray.length;
    return lookUpArray[ i ];
  }

}

<commit_msg>Update Weights_Base.js<commit_after>export { Base, Root, To };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as FloatValue from "../FloatValue.js";

/**
 * A base class for extracting and keeping weights. It composes of a Float32Array and a shape. It can
 * be used as CNN (depthwise, pointwise and bias) filter weights.
 *
 * @member {number} elementOffsetBegin
 *   The beginning position (i.e. array index) to extract from inputWeightsArray. If this value is negative, the extraction will
 * fail (i.e. ( bInitOk == false ) ).
 *
 * @member {number} elementOffsetEnd
 *   The ending position (i.e. array index) after extracting from inputWeightsArray. It is not inclusive and can be used as the
 * beginning position of next (another) extraction. It is meaningful only if ( bInitOk == true ).
 *
 * @member {number} elementExtractedCount
 *   How many weights (i.e. elements) will be extracted from inputWeightsArray. It should be a non-negative integer value.
 *
 *     - If too many elements need to be extracted (exceeds the inputWeightsArray.length) or elementExtractedCount is NaN or
 *         elementExtractedCount is negative, the extraction will fail (i.e. ( bInitOk == false ) ).
 *
 * @member {boolean} bInitOk
 *   If .init() success, it will be true.
 */
let Base = ( ParentClass = Object ) => class Base extends Recyclable.Base( ParentClass ) {

  /**
   * Used as default Weights.Base provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Weights.Base.Pool", Base, Base.setAsConstructor );

  /**
   * Just record the begin and length without checking them. Please call extract() to finish extracting.
   */
  constructor() {
    super();
    Base.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    Base.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    // Do nothing.
  }

  /** @override */
  disposeResources() {
    this.bInitOk = undefined;
    this.elementOffsetEnd = undefined;
    this.elementExtractedCount = undefined;
    this.elementOffsetBegin = undefined;
    super.disposeResources();
  }

  /**
   * Determine .elementOffsetEnd according to the inputWeightArray.lnegth, .elementOffsetBegin and .elementExtractedCount.
   *
   * @param {number[]|Float32Array} inputWeightArray
   *   The underlying weights source array to be extracted from. It will not be kept by this object.
   *
   * @return {boolean} Return false, if extraction failed.
   */
  init( inputWeightArray, elementOffsetBegin, elementExtractedCount ) {
    this.elementOffsetBegin = elementOffsetBegin;
    this.elementExtractedCount = elementExtractedCount;
    this.bInitOk = false;

    if ( Number.isNaN( this.elementExtractedCount ) )
      return false;  // Failed, if NaN.

    if ( this.elementExtractedCount < 0 )
      return false;  // Failed, if negative.

    this.elementOffsetEnd = this.elementOffsetBegin + this.elementExtractedCount;
    if ( this.elementOffsetEnd > inputWeightArray.length )
      return false;  // Failed, if out of array index range.

    this.bInitOk = true;
    return true;     // Success.
  }

//!!! (2021/12/98 Remarked) Using bounds [ -2^24, +2^24 ] seems enough.
//   /**
//    * Confirm:
//    *   - Every element is not NaN. (If it is, become 0.)
//    *   - The smallest non-zero Math.abs( element ) is 2^(-24). (i.e. If ( -2^(-24) < element < +2^(-24) ), become 0.)
//    *   - The largest Math.abs( element ) is 2^(+24).
//    *
//    * This is mainly for ensuring PointDepthPoint's output is legal float32:
//    *   - PointDepthPoint is composed of 3 convolutions: pointwise1-depthwise-pointwise2.
//    *   - Suppose every convolution has 4096 (= 2^12) input channels. (The bias is viewed as the last (i.e. 4095th) channels.)
//    *   - Suppose depthwise uses 4x4 (= 2^4) filter for every channel.
//    *   - Suppose every convolution does not have activation function (so that its result is unbounded).
//    *   - If every Math.abs( pointwise1Input ) is restected to 0 or between [ 2^(-24), 2^24 ].
//    *   - If every Math.abs( weight ) of pointwise1, depthwise, pointwise2 is restected to 0 or between [ 2^(-24), 2^24 ].
//    *   - The Math.abs( pointwise1Result ) will be restriced to 0 or between [ 2^(-(24+24)), 2^(24+24+12) ] = [ 2^(-48), 2^60 ].
//    *   - The Math.abs( depthwiseResult  ) will be restriced to 0 or between [ 2^(-(48+24)), 2^(60+24+4)  ] = [ 2^(-72), 2^88 ].
//    *   - The Math.abs( pointwise2Result ) will be restriced to 0 or between [ 2^(-(72+24)), 2^(88+24+12) ] = [ 2^(-96), 2^124 ].
//    *   - So the result is still legal float32 because Math.abs( float32 ) could be either 0 or between [ 2^(-126), 2^126 ].
//    *
//    * The 2^24 as input element should be enough for most situation:
//    *   - Color image: The R, G, B, A channels are 8 bits (2^8) individually.
//    *   - Sound track: 8 bits (2^8), or 16 bits (2^16), or 20 bits (2^20), or 24 bits (2^24). But not 32 bits (2^32)
//    *   - Unicode character code point: 21 bits (2^21).
//    *
//    *
//    *

//    *              -2^(+24)       -2^(-24)                      +2^(-24)       +2^(+24)
//    *            NEGATIVE_MIN   NEGATIVE_MAX        0         POSITIVE_MIN   POSITIVE_MAX
//    *   --------------|--------------|--------------|--------------|--------------|--------------
//    *
//    * Restricted to:
//    *                 |--------------|00000000000000000000000000000|--------------|
//    *

//    *
//    *
//    * @param {Float32Array} source
//    *   The source Float32Array.
//    *
//    * @return {Float32Array}
//    *   Return a copy of source. Every element (float32):
//    *     - If ( Number.isNaN( element ) == true ), let it become 0.
//    *     - If ( element != 0 ), Math.abs( element ) will be restricted between [ 2^(-24), 2^24 ].
//    *     - ( Math.sign( element ) * Math.abs( element ) ) will be restricted between [ -2^(24), 2^24 ].
//    */
//   static Float32Array_CloneLegal( sourceArray ) {
//     const POSITIVE_MIN = Math.pow( 2, -24 );
//     const POSITIVE_MAX = Math.pow( 2, +24 );
//     const NEGATIVE_MIN = - POSITIVE_MAX; // - Math.pow( 2, +24 )
//     const NEGATIVE_MAX = - POSITIVE_MIN; // - Math.pow( 2, -24 )
//
//     let resultArray = new Float32Array( sourceArray.length );
//     for ( let i = 0; i < sourceArray.length; ++i ) {
//       let element = sourceArray[ i ];
//
//       let restricted;
//       if ( Number.isNaN( element ) ) {
//         restricted = 0;
//
//       } else if ( element >= POSITIVE_MIN ) {
//         if ( element > POSITIVE_MAX )
//           restricted = POSITIVE_MAX;
//         else
//           restricted = element;
//
//       } else if ( element <= NEGATIVE_MAX ) {
//         if ( element < NEGATIVE_MIN )
//           restricted = NEGATIVE_MIN;
//         else
//           restricted = element;
//
//       } else { // ( NEGATIVE_MAX < element < POSITIVE_MIN ) (Note: Zero is inside.)
//         restricted = 0;
//       }
//
//       resultArray[ i ] = restricted;
//     }
//     return resultArray;
//   }

}

/**
 * Almost the same as Weights.Base class except its parent class is fixed to Object. In other words, caller can not
 * specify the parent class of Weights.Root (so it is named "Root" which can not have parent class).
 */
class Root extends Base() {

  /**
   * Used as default Weights.Root provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Weights.Root.Pool", Base, Base.setAsConstructor );

}

//!!! ...unfinished... (2022/01/10)
/*
 * When ( x < 0.0000001 ), the tf.tanh( x ) will be 0.
 * That is, the precision of tf.tanh() may be 0.0000001 (= 1e-7 ).
 *
 * Consider the ActivationEscaping inputDomainLinear of tanh() is [ -0.005, +0.005 ] simultaneously. The value bounds of result
 * after filter-bias (no matter pointwise or depthwise) should be compatible with [ -0.005, +0.005 ] with precision 0.0000001 (= 1e-7 ).
 *
 * For example,
 *   - [ -0.005, +0.005 ] with precision 0.0000001 (= 1e-7 ).
 *   - [ -0.5, +0.5 ] with precision 0.00001 (= 1e-5 ).
 *   - [ -5, +5 ] with precision 0.0001 (= 1e-4 ).
 *   - [ -50, +50 ] with precision 0.001 (= 1e-3 ).
 *   - [ -500, +500 ] with precision 0.01 (= 1e-2 ).
 *   - [ -5000, +5000 ] with precision 0.1 (= 1e-1 ).
 *   - [ -50000, +50000 ] with precision 1 (= 1e+0 ).
 *   - [ -5e+4, +5e+4 ] with precision 1 (= 1e+0 ).
 *   - [ 0, +100000 ] with precision 1 (= 1e+0 ).
 *   - [ 0, +1e+5 ] with precision 1 (= 1e+0 ).
 *
 *
 *
 *
 *
 * For this reason, the Weights.Base.ValueBounds may be more less than [ -( 2 ** 24 ), +( 2 ** 24 ) ].
 * Perhaps, [ -1, +1 ] is better.?
 *
 */

/**
 * This is mainly for ensuring Block's output is legal float32:
 *   - Block is composed of 3 convolutions: pointwise1-depthwise-pointwise2.
 *   - Suppose every convolution has 4096 (= 2^12) input channels. (The bias is viewed as the last (i.e. 4095th) channels.)
 *   - Suppose depthwise uses 4x4 (= 2^4) filter for every channel.
 *   - Suppose every convolution does not have activation function (so that its result is unbounded).
 *   - If every element of pointwise1Input is bounds to [ -2^24, +2^24 ].
 *   - If every element of weights of pointwise1, depthwise, pointwise2 is bounds to [ -2^24, +2^24 ].
 *   - Every element of pointwise1Result will be bounds to [ -2^(24+24+12), +2^(24+24+12) ] = [ -2^60,  +2^60  ].
 *   - Every element of depthwiseResult  will be bounds to [ -2^(60+24+4),  +2^(60+24+4)  ] = [ -2^88,  +2^88  ].
 *   - Every element of pointwise2Result will be bounds to [ -2^(88+24+12), +2^(88+24+12) ] = [ -2^124, +2^124 ].
 *   - So the result is still legal float32 (which could represent floating-point value between [ -2^126, +2^126 ]).
 *
 * The 2^24 as input element should be enough for most situation:
 *   - Color image: The R, G, B, A channels are 8 bits (2^8) individually.
 *   - Sound track: 8 bits (2^8), or 16 bits (2^16), or 20 bits (2^20), or 24 bits (2^24). But not 32 bits (2^32)
 *   - Unicode character code point: 21 bits (2^21).
 */
Base.ValueBounds = new FloatValue.Bounds( -( 2 ** 24 ), +( 2 ** 24 ) );

/**
 * Provides static methods for converting weight to parameter.
 */
class To {

  /** @return {number} Return the absolute value of the trucated value (i.e. integer). */
  static IntegerZeroPositive( v ) {
    return Math.abs( Math.trunc( v ) );
  }

  /**
   * @param {any[]} lookUpArray
   *   The value will be converted into an integer between [ 0, lookUpArray.length ). Use it as array index.
   * Return lookUpArray[ index ].
   *
   * @return {any}
   *   Convert number value into an integer between [ 0, lookUpArray.length ). Use it as array index. Return
   * the looked up element value.
   */
  static ArrayElement( value, lookUpArray ) {
    let i = To.IntegerZeroPositive( value ) % lookUpArray.length;
    return lookUpArray[ i ];
  }

}

<|endoftext|>


<commit_before>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            $(this).append("GNOME Shell Extensions cannot automatically detect any errors.");
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                messages.addError("This extension is not compatible with your version of GNOME.");
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            $.each(extensions, function(uuid, extension) {
                function reinstall() {
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                    // If the user clicks "Install" we need to show that we
                    // installed it by reattaching the element, but we can't do
                    // that here -- the user might click "Cancel".
                    $elem.data('uninstalled', true);

                    message.slideUp();
                }

                function uninstall() {
                    dbusProxy.UninstallExtension(uuid).done(function(result) {
                        if (result) {
                            $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                            // Construct a dummy
 node as we need something
                            // to stuff everything else in...
                            var messageHTML = $("
You uninstalled
").
                                append($('').text(extension.name)).
                                append(". ").
                                append($('', {'href': '#'}).text("Undo?")).html();

                            var message = messages.addInfo(messageHTML);
                            message.find('a').click(reinstall);
                            $elem.data('undo-uninstall-message', message);
                        }
                    });
                }

                var $elem = $('
', {'class': 'extension'}).
                    append($('
', {'class': 'switch'})).
                    append($('', {'class': 'icon'})).
                    append($('
', {'class': 'extension-name'}).text(extension.name)).
                    append($('', {'class': 'author'})).
                    append($('
', {'class': 'description'}).text(extension.description));

                $.ajax({
                    url: "/ajax/detail/",
                    dataType: "json",
                    data: { uuid: uuid },
                    type: "GET",
                }).done(function(result) {
                    $elem.
                        find('span.author').html(" by "+result.creator+"").end().
                        find('h3').html($('', {'href': result.link}).text(extension.name)).end().
                        find('img.icon').attr('src', result.icon).end().
                        append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                        data('pk', result.pk);
                });

                // The DOM element's CSS styles won't be fully
                // computed, so the switch will be incorrectly
                // positioned -- wait a bit before adding them.
                setTimeout(function() {
                    addExtensionSwitch(uuid, extension, $elem);
                }, 0);

                $container.append($elem);
            });
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea[name=error]');
        var $hidden = $form.find('input:hidden[name=has_errors]');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            if (errors && errors.length) {
                $textarea.text(errors.join('\n\n')).
                    removeClass('no-errors').removeAttr('disabled');
                $hidden.val('true');
            } else {
                $textarea.text("Could not detect any errors").
                    addClass('no-errors').attr('disabled', 'disabled');
                $hidden.val('');
            }
        });
    };

    $.fn.addExtensionsSwitches = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            $container.each(function () {
                var uuid = $(this).data('uuid');
                addExtensionSwitch(uuid, extensions[uuid], $(this));
            });
        });
    };

});
<commit_msg>Output a message when the user has no extensions installed<commit_after>"use strict";

define(['jquery', 'messages', 'dbus!_',
        'switch', 'jquery.tipsy'],
function($, messages, dbusProxy) {

    // ExtensionState and versionCheck are stolen and should
    // be kept in sync those from the Shell.
    // Licensed under GPL2+
    // See: http://git.gnome.org/browse/gnome-shell/tree/js/ui/extensionSystem.js

    var ExtensionState = {
        ENABLED: 1,
        DISABLED: 2,
        ERROR: 3,
        OUT_OF_DATE: 4,
        DOWNLOADING: 5,

        // Not a real state, used when there's no extension
        // with the associated UUID in the extension map.
        UNINSTALLED: 99
    };

    function versionCheck(required, current) {
        var currentArray = current.split('.');
        var major = currentArray[0];
        var minor = currentArray[1];
        var point = currentArray[2];
        for (var i = 0; i < required.length; i++) {
            var requiredArray = required[i].split('.');
            if (requiredArray[0] == major &&
                requiredArray[1] == minor &&
                (requiredArray[2] == point ||
                 (requiredArray[2] == undefined && parseInt(minor) % 2 == 0)))
                return true;
        }
        return false;
    }

    // While technically we shouldn't have mismatched API versions,
    // the plugin doesn't check whether the Shell matches, so if someone
    // is running with an old Shell version but a newer plugin, error out.
    if (dbusProxy === undefined ||
        dbusProxy.ShellVersion === undefined) {
        // We don't have a proper DBus proxy -- it's probably an old
        // version of GNOME3 or the Shell.
        messages.addError("You do not appear to have an up to date version of GNOME3. Some parts of the website may be disabled.");

        $.fn.addExtensionsSwitches = function() {
            // Don't show our switches -- CSS styles define a clickable
            // area even with no content.
            $(this).find('.switch').hide();
        };

        $.fn.addLocalExtensions = function() {
            $(this).append("GNOME Shell Extensions cannot list your installed extensions.");
        };

        $.fn.fillInErrors = function() {
            $(this).append("GNOME Shell Extensions cannot automatically detect any errors.");
        };

        return;
    }

    // uuid => elem
    var elems = {};

    dbusProxy.extensionStateChangedHandler = function(uuid, newState, _) {
        elems[uuid].trigger('state-changed', newState);
    };

    function addExtensionSwitch(uuid, extension, $elem) {
        var shellVersions = $elem.data('sv');

        var $switch = $elem.find('.switch');
        var _state = ExtensionState.UNINSTALLED;

        if (shellVersions && !versionCheck(shellVersions, dbusProxy.ShellVersion)) {
            _state = ExtensionState.OUT_OF_DATE;
        } else if (extension) {
            _state = extension.state;
        }

        $elem.data({'elem': $elem,
                    'state': _state,
                    'uninstalled': false});

        $switch.data('elem', $elem);
        $switch.switchify();
        if ($switch.hasClass('insensitive'))
            return;

        $switch.bind('changed', function(e, newValue) {
            var oldState = $elem.data('state');
            if (newValue) {
                if (oldState == ExtensionState.UNINSTALLED) {
                    // If the extension is uninstalled and we
                    // flick the switch on, install.
                    dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());
                } else if (oldState == ExtensionState.DISABLED) {
                    dbusProxy.EnableExtension(uuid);
                }
            } else {
                if (oldState == ExtensionState.ENABLED)
                    dbusProxy.DisableExtension(uuid);
            }
        });

        $elem.bind('state-changed', function(e, newState) {
            $elem.data('state', newState);
            $switch.switchify('insensitive', false);
            $switch.tipsy({ gravity: 'e', fade: true });
            if (newState == ExtensionState.DISABLED ||
                newState == ExtensionState.UNINSTALLED) {
                $switch.switchify('activate', false);
            } else if (newState == ExtensionState.ENABLED) {
                $switch.switchify('activate', true);
            } else if (newState == ExtensionState.ERROR) {
                $switch.switchify('insensitive', true);
                $switch.attr('title', "This extension had an error.");
            } else if (newState == ExtensionState.OUT_OF_DATE) {
                $switch.switchify('insensitive', true);
                messages.addError("This extension is not compatible with your version of GNOME.");
            }

            if ($elem.data('uninstalled') && (newState == ExtensionState.ENABLED ||
                                              newState == ExtensionState.ERROR ||
                                              newState == ExtensionState.OUT_OF_DATE)) {
                $elem.fadeIn({ queue: false }).slideDown();
                $elem.data('uninstalled', false);
            }

        });
        $elem.trigger('state-changed', _state);
        elems[uuid] = $elem;
    }

    $.fn.addLocalExtensions = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            if (extensions && extensions.length) {
                $.each(extensions, function(uuid, extension) {
                    function reinstall() {
                        dbusProxy.InstallExtension(uuid, $elem.data('pk').toString());

                        // If the user clicks "Install" we need to show that we
                        // installed it by reattaching the element, but we can't do
                        // that here -- the user might click "Cancel".
                        $elem.data('uninstalled', true);

                        message.slideUp();
                    }

                    function uninstall() {
                        dbusProxy.UninstallExtension(uuid).done(function(result) {
                            if (result) {
                                $elem.fadeOut({ queue: false }).slideUp({ queue: false });

                                // Construct a dummy
 node as we need something
                                // to stuff everything else in...
                                var messageHTML = $("
You uninstalled
").
                                    append($('').text(extension.name)).
                                    append(". ").
                                    append($('', {'href': '#'}).text("Undo?")).html();

                                var message = messages.addInfo(messageHTML);
                                message.find('a').click(reinstall);
                                $elem.data('undo-uninstall-message', message);
                            }
                        });
                    }

                    var $elem = $('
', {'class': 'extension'}).
                        append($('
', {'class': 'switch'})).
                        append($('', {'class': 'icon'})).
                        append($('
', {'class': 'extension-name'}).text(extension.name)).
                        append($('', {'class': 'author'})).
                        append($('
', {'class': 'description'}).text(extension.description));

                    $.ajax({
                        url: "/ajax/detail/",
                        dataType: "json",
                        data: { uuid: uuid },
                        type: "GET",
                    }).done(function(result) {
                        $elem.
                            find('span.author').html(" by "+result.creator+"").end().
                            find('h3').html($('', {'href': result.link}).text(extension.name)).end().
                            find('img.icon').attr('src', result.icon).end().
                            append($('<button>', {'class': 'uninstall', 'title': "Uninstall"}).text("Uninstall").bind('click', uninstall)).
                            data('pk', result.pk);
                    });

                    // The DOM element's CSS styles won't be fully
                    // computed, so the switch will be incorrectly
                    // positioned -- wait a bit before adding them.
                    setTimeout(function() {
                        addExtensionSwitch(uuid, extension, $elem);
                    }, 0);

                    $container.append($elem);
                });
            } else {
                $container.append("You don't have any extensions installed.");
            }
        });
    };

    $.fn.fillInErrors = function (uuid) {
        var $form = $(this);
        var $textarea = $form.find('textarea[name=error]');
        var $hidden = $form.find('input:hidden[name=has_errors]');
        dbusProxy.GetErrors(uuid).done(function(errors) {
            if (errors && errors.length) {
                $textarea.text(errors.join('\n\n')).
                    removeClass('no-errors').removeAttr('disabled');
                $hidden.val('true');
            } else {
                $textarea.text("Could not detect any errors").
                    addClass('no-errors').attr('disabled', 'disabled');
                $hidden.val('');
            }
        });
    };

    $.fn.addExtensionsSwitches = function () {
        var $container = $(this);
        dbusProxy.ListExtensions().done(function(extensions) {
            $container.each(function () {
                var uuid = $(this).data('uuid');
                addExtensionSwitch(uuid, extensions[uuid], $(this));
            });
        });
    };

});
<|endoftext|>


<commit_before>// refers to Constant.js
var defaultWpsVersion = WPS_VERSION_1_0_0;

/**
 * requires Constants.js!
 */
var WpsService = Class.extend({

	/**
	 *
	 */
	init : function(settings) {
		this.settings = settings;

		if (!this.settings.version)
			this.settings.version = defaultWpsVersion;
	},

	/**
	 * allowed values : "1.0.0" or "2.0.0"
	 *
	 * requires Constant.js
	 */
	setVersion : function(version) {
		if (version == WPS_VERSION_1_0_0 || version == WPS_VERSION_2_0_0)
			this.settings.version = version;
	},

	/**
	 * set base URL of target WPS
	 */
	setUrl : function(url) {
		this.settings.url = url;
	},

	/**
	 * getCapabilities via HTTP GET
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method
	 */
	getCapabilities_GET : function(callbackFunction) {
		var capabilitiesRequest;

		/**
		 * getCapabilities via HTTP GET
		 *
		 * @callbackFunction is triggered on success-event of JQuery.ajax
		 *                   method. Takes the response object as argument
		 */
		capabilitiesRequest = new GetCapabilitiesGetRequest({
			url : this.settings.url,
			version : this.settings.version
		});

		capabilitiesRequest.execute(callbackFunction);
	},

	/**
	 * getCapabilities via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 */
	getCapabilities_POST : function(callbackFunction) {
		var capabilitiesRequest;

		/*
		 * TODO has to be instantiated depending on the version
		 */
		capabilitiesRequest = new GetCapabilitiesPostRequest({
			url : this.settings.url,
			version : this.settings.version
		});

		capabilitiesRequest.execute(callbackFunction);
	},

	/**
	 * process description via HTTP GET
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 */
	describeProcess_GET : function(callbackFunction, processIdentifier) {
		var processDescriptionRequest;

		processDescriptionRequest = new DescribeProcessGetRequest({
			url : this.settings.url,
			version : this.settings.version,
			processIdentifier : processIdentifier
		});

		processDescriptionRequest.execute(callbackFunction);
	},

	/**
	 * process description via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 */
	describeProcess_POST : function(callbackFunction, processIdentifier) {
		var processDescriptionRequest;

		processDescriptionRequest = new DescribeProcessPostRequest({
			url : this.settings.url,
			version : this.settings.version,
			processIdentifier : processIdentifier
		});

		processDescriptionRequest.execute(callbackFunction);
	},

	/**
	 * WPS execute request via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 * @responseFormat either "raw" or "document", default is "document"
	 * @executionMode either "sync" or "async";
	 * @lineage only relevant for WPS 1.0; boolean, if "true" then returned
	 *          response will include original input and output definition
	 * @inputs an array of needed Input objects, use JS-object InputGenerator to
	 *         create inputs
	 * @outputs an array of requested Output objects, use JS-object
	 *          OutputGenerator to create inputs
	 */
	execute : function(callbackFunction, processIdentifier, responseFormat,
			executionMode, lineage, inputs, outputs) {
		var executeRequest;

		if (this.settings.version == Constants.WPS_VERSION_1_0_0) {
			executeRequest = new ExecuteRequest_v1({
				url : this.settings.url,
				version : this.settings.version,
				processIdentifier : processIdentifier,
				responseFormat : responseFormat,
				executionMode : executionMode,
				lineage : lineage,
				inputs : inputs,
				outputs : outputs
			});
		}

		else {
			executeRequest = new ExecuteRequest_v2({
				url : this.settings.url,
				version : this.settings.version,
				processIdentifier : processIdentifier,
				responseFormat : responseFormat,
				executionMode : executionMode,
				inputs : inputs,
				outputs : outputs
			});
		}

		executeRequest.execute(callbackFunction);
	},

});<commit_msg>fix wrong variable instantiation causing a runtim error<commit_after>// refers to Constant.js
var defaultWpsVersion = WPS_VERSION_1_0_0;

/**
 * requires Constants.js!
 */
var WpsService = Class.extend({

	/**
	 *
	 */
	init : function(settings) {
		this.settings = settings;

		if (!this.settings.version)
			this.settings.version = defaultWpsVersion;
	},

	/**
	 * allowed values : "1.0.0" or "2.0.0"
	 *
	 * requires Constant.js
	 */
	setVersion : function(version) {
		if (version == WPS_VERSION_1_0_0 || version == WPS_VERSION_2_0_0)
			this.settings.version = version;
	},

	/**
	 * set base URL of target WPS
	 */
	setUrl : function(url) {
		this.settings.url = url;
	},

	/**
	 * getCapabilities via HTTP GET
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method
	 */
	getCapabilities_GET : function(callbackFunction) {
		var capabilitiesRequest;

		/**
		 * getCapabilities via HTTP GET
		 *
		 * @callbackFunction is triggered on success-event of JQuery.ajax
		 *                   method. Takes the response object as argument
		 */
		capabilitiesRequest = new GetCapabilitiesGetRequest({
			url : this.settings.url,
			version : this.settings.version
		});

		capabilitiesRequest.execute(callbackFunction);
	},

	/**
	 * getCapabilities via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 */
	getCapabilities_POST : function(callbackFunction) {
		var capabilitiesRequest;

		/*
		 * TODO has to be instantiated depending on the version
		 */
		capabilitiesRequest = new GetCapabilitiesPostRequest({
			url : this.settings.url,
			version : this.settings.version
		});

		capabilitiesRequest.execute(callbackFunction);
	},

	/**
	 * process description via HTTP GET
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 */
	describeProcess_GET : function(callbackFunction, processIdentifier) {
		var processDescriptionRequest;

		processDescriptionRequest = new DescribeProcessGetRequest({
			url : this.settings.url,
			version : this.settings.version,
			processIdentifier : processIdentifier
		});

		processDescriptionRequest.execute(callbackFunction);
	},

	/**
	 * process description via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 */
	describeProcess_POST : function(callbackFunction, processIdentifier) {
		var processDescriptionRequest;

		processDescriptionRequest = new DescribeProcessPostRequest({
			url : this.settings.url,
			version : this.settings.version,
			processIdentifier : processIdentifier
		});

		processDescriptionRequest.execute(callbackFunction);
	},

	/**
	 * WPS execute request via HTTP POST
	 *
	 * @callbackFunction is triggered on success-event of JQuery.ajax method.
	 *                   Takes the response object as argument
	 * @processIdentifier the identifier of the process
	 * @responseFormat either "raw" or "document", default is "document"
	 * @executionMode either "sync" or "async";
	 * @lineage only relevant for WPS 1.0; boolean, if "true" then returned
	 *          response will include original input and output definition
	 * @inputs an array of needed Input objects, use JS-object InputGenerator to
	 *         create inputs
	 * @outputs an array of requested Output objects, use JS-object
	 *          OutputGenerator to create inputs
	 */
	execute : function(callbackFunction, processIdentifier, responseFormat,
			executionMode, lineage, inputs, outputs) {
		var executeRequest;

		if (this.settings.version == WPS_VERSION_1_0_0) {
			executeRequest = new ExecuteRequest_v1({
				url : this.settings.url,
				version : this.settings.version,
				processIdentifier : processIdentifier,
				responseFormat : responseFormat,
				executionMode : executionMode,
				lineage : lineage,
				inputs : inputs,
				outputs : outputs
			});
		}

		else {
			executeRequest = new ExecuteRequest_v2({
				url : this.settings.url,
				version : this.settings.version,
				processIdentifier : processIdentifier,
				responseFormat : responseFormat,
				executionMode : executionMode,
				inputs : inputs,
				outputs : outputs
			});
		}

		executeRequest.execute(callbackFunction);
	},

});<|endoftext|>


<commit_before>'use strict';
const debug = require('debug')('brunch:modules');
const commonRequireDefinition = require('commonjs-require-definition');

const backslashRe = new RegExp('\\\\', 'g');
const dotRe = new RegExp('^(\.\.\/)*', 'g');
const wrapperRe = /\.\w+$/;
const amdRe = /define\s*\(/;

const cleanModuleName = exports.cleanModuleName = (path, nameCleaner) => {
  return nameCleaner(path.replace(backslashRe, '/').replace(dotRe, ''));
};

const getModuleWrapper = (type, nameCleaner) => {
  return (fullPath, data, isVendor) => {
    const sourceURLPath = cleanModuleName(fullPath, nameCleaner);
    const moduleName = sourceURLPath.replace(wrapperRe, '');
    const path = JSON.stringify(moduleName);
    if (isVendor) {
      debug(`Not wrapping (is vendor file) ${moduleName}`);
      return data;
    }
    debug(`Wrapping ${moduleName} @ ${type}`);

    /* Wrap in common.js require definition. */
    if (type === 'commonjs') {
      return {
        prefix: 'require.register(' + path + ', function(exports, require, module) {\n',
        suffix: '});\n\n'
      };
    } else if (type === 'amd') {
      return {
        data: data.replace(amdRe, match => '' + match + path + ', ')
      };
    }
  };
};

const normalizeWrapper = (typeOrFunction, nameCleaner) => {
  switch (typeOrFunction) {
    case 'commonjs':
      return getModuleWrapper('commonjs', nameCleaner);
    case 'amd':
      return getModuleWrapper('amd', nameCleaner);
    case false:
      return (path, data) => {
        return data;
      };
    default:
      if (typeof typeOrFunction === 'function') {
        return typeOrFunction;
      } else {
        throw new Error('config.modules.wrapper should be a ' +
          'function or one of: "commonjs", "amd", false');
      }
  }
};

exports.normalizeWrapper = normalizeWrapper;

exports.normalizeDefinition = typeOrFunction => {
  switch (typeOrFunction) {
    case 'commonjs':
      return () => commonRequireDefinition;
    case 'amd':
    case false:
      return () => '';
    default:
      if (typeof typeOrFunction === 'function') {
        return typeOrFunction;
      } else {
        throw new Error('config.modules.definition should be a ' +
          'function or one of: "commonjs", false');
      }
  }
};
<commit_msg>Align function as a wrapper with other types<commit_after>'use strict';
const debug = require('debug')('brunch:modules');
const commonRequireDefinition = require('commonjs-require-definition');

const backslashRe = new RegExp('\\\\', 'g');
const dotRe = new RegExp('^(\.\.\/)*', 'g');
const wrapperRe = /\.\w+$/;
const amdRe = /define\s*\(/;

const cleanModuleName = exports.cleanModuleName = (path, nameCleaner) => {
  return nameCleaner(path.replace(backslashRe, '/').replace(dotRe, ''));
};

const getModuleWrapper = (type, nameCleaner, wrapper) => {
  return (fullPath, data, isVendor) => {
    const sourceURLPath = cleanModuleName(fullPath, nameCleaner);
    const moduleName = sourceURLPath.replace(wrapperRe, '');
    const path = JSON.stringify(moduleName);
    if (isVendor) {
      debug(`Not wrapping (is vendor file) ${moduleName}`);
      return data;
    }
    debug(`Wrapping ${moduleName} @ ${type}`);

    /* Wrap in common.js require definition. */
    if (type === 'commonjs') {
      return {
        prefix: 'require.register(' + path + ', function(exports, require, module) {\n',
        suffix: '});\n\n'
      };
    } else if (type === 'amd') {
      return {
        data: data.replace(amdRe, match => '' + match + path + ', ')
      };
    } else if (type === 'function') {
      return {
        data: wrapper(sourceURLPath, data)
      };
    }
  };
};

const normalizeWrapper = (typeOrFunction, nameCleaner) => {
  switch (typeOrFunction) {
    case 'commonjs':
      return getModuleWrapper('commonjs', nameCleaner);
    case 'amd':
      return getModuleWrapper('amd', nameCleaner);
    case false:
      return (path, data) => {
        return data;
      };
    default:
      if (typeof typeOrFunction === 'function') {
        return getModuleWrapper('function', nameCleaner, typeOrFunction);
      } else {
        throw new Error('config.modules.wrapper should be a ' +
          'function or one of: "commonjs", "amd", false');
      }
  }
};

exports.normalizeWrapper = normalizeWrapper;

exports.normalizeDefinition = typeOrFunction => {
  switch (typeOrFunction) {
    case 'commonjs':
      return () => commonRequireDefinition;
    case 'amd':
    case false:
      return () => '';
    default:
      if (typeof typeOrFunction === 'function') {
        return typeOrFunction;
      } else {
        throw new Error('config.modules.definition should be a ' +
          'function or one of: "commonjs", false');
      }
  }
};
<|endoftext|>