<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

var channel = require('cordova/channel');
var platform = require('cordova/platform');

/**
 * Intercept calls to addEventListener + removeEventListener and handle deviceready,
 * resume, and pause events.
 */
var m_document_addEventListener = document.addEventListener;
var m_document_removeEventListener = document.removeEventListener;
var m_window_addEventListener = window.addEventListener;
var m_window_removeEventListener = window.removeEventListener;

/**
 * Houses custom event handlers to intercept on document + window event listeners.
 */
var documentEventHandlers = {},
    windowEventHandlers = {};

document.addEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    if (typeof documentEventHandlers[e] != 'undefined') {
        documentEventHandlers[e].subscribe(handler);
    } else {
        m_document_addEventListener.call(document, evt, handler, capture);
    }
};

window.addEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    if (typeof windowEventHandlers[e] != 'undefined') {
        windowEventHandlers[e].subscribe(handler);
    } else {
        m_window_addEventListener.call(window, evt, handler, capture);
    }
};

document.removeEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    // If unsubscribing from an event that is handled by a plugin
    if (typeof documentEventHandlers[e] != "undefined") {
        documentEventHandlers[e].unsubscribe(handler);
    } else {
        m_document_removeEventListener.call(document, evt, handler, capture);
    }
};

window.removeEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    // If unsubscribing from an event that is handled by a plugin
    if (typeof windowEventHandlers[e] != "undefined") {
        windowEventHandlers[e].unsubscribe(handler);
    } else {
        m_window_removeEventListener.call(window, evt, handler, capture);
    }
};

function createEvent(type, data) {
    var event = document.createEvent('Events');
    event.initEvent(type, false, false);
    if (data) {
        for (var i in data) {
            if (data.hasOwnProperty(i)) {
                event[i] = data[i];
            }
        }
    }
    return event;
}

var cordova = {
    platformVersion:PLATFORM_VERSION_BUILD_LABEL,
    version:PLATFORM_VERSION_BUILD_LABEL,
    require: function(module) {
        if(module === "cordova/exec") {
            return cordova.exec;
        }
        if(module === "org.apache.cordova.media.Media") {
            return window.Media;
        }

        return require(module);
    },
    platformId:platform.id,
    /**
     * Methods to add/remove your own addEventListener hijacking on document + window.
     */
    addWindowEventHandler:function(event) {
        return (windowEventHandlers[event] = channel.create(event));
    },
    addStickyDocumentEventHandler:function(event) {
        return (documentEventHandlers[event] = channel.createSticky(event));
    },
    addDocumentEventHandler:function(event) {
        return (documentEventHandlers[event] = channel.create(event));
    },
    removeWindowEventHandler:function(event) {
        delete windowEventHandlers[event];
    },
    removeDocumentEventHandler:function(event) {
        delete documentEventHandlers[event];
    },
    /**
     * Retrieve original event handlers that were replaced by Cordova
     *
     * @return object
     */
    getOriginalHandlers: function() {
        return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
        'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
    },
    /**
     * Method to fire event from native code
     * bNoDetach is required for events which cause an exception which needs to be caught in native code
     */
    fireDocumentEvent: function(type, data, bNoDetach) {
        var evt = createEvent(type, data);
        if (typeof documentEventHandlers[type] != 'undefined') {
            if( bNoDetach ) {
                documentEventHandlers[type].fire(evt);
            }
            else {
                setTimeout(function() {
                    // Fire deviceready on listeners that were registered before cordova.js was loaded.
                    if (type == 'deviceready') {
                        document.dispatchEvent(evt);
                    }
                    documentEventHandlers[type].fire(evt);
                }, 0);
            }
        } else {
            document.dispatchEvent(evt);
        }
    },
    fireWindowEvent: function(type, data) {
        var evt = createEvent(type,data);
        if (typeof windowEventHandlers[type] != 'undefined') {
            setTimeout(function() {
                windowEventHandlers[type].fire(evt);
            }, 0);
        } else {
            window.dispatchEvent(evt);
        }
    },

    /**
     * Plugin callback mechanism.
     */
    // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
    // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
    callbackId: Math.floor(Math.random() * 2000000000),
    callbacks:  {},
    callbackStatus: {
        NO_RESULT: 0,
        OK: 1,
        CLASS_NOT_FOUND_EXCEPTION: 2,
        ILLEGAL_ACCESS_EXCEPTION: 3,
        INSTANTIATION_EXCEPTION: 4,
        MALFORMED_URL_EXCEPTION: 5,
        IO_EXCEPTION: 6,
        INVALID_ACTION: 7,
        JSON_EXCEPTION: 8,
        ERROR: 9
    },
    /**
     * Called by native code when returning successful result from an action.
     */
    callbackSuccess: function(callbackId, args) {
        this.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
    },
    /**
     * Called by native code when returning error result from an action.
     */
    callbackError: function(callbackId, args) {
        // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
        // Derive success from status.
        this.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
    },
    /**
     * Called by native code when returning the result from an action.
     */
    callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) {
        try {
            var callback = cordova.callbacks[callbackId];
            if (callback) {
                if (isSuccess && status == cordova.callbackStatus.OK) {
                    callback.success && callback.success.apply(null, args);
                } else {
                    callback.fail && callback.fail.apply(null, args);
                }

                // Clear callback if not expecting any more results
                if (!keepCallback) {
                    delete cordova.callbacks[callbackId];
                }
            }
        }
        catch(err) {
            var msg = "Error in " + (isSuccess ? "Success" : "Error") + " callbackId: " + callbackId + " : " + err;
            console.log(msg);
            this.fireWindowEvent("callbackerror",{'message':msg});
        }
    },
    addConstructor: function(func) {
        channel.onCordovaReady.subscribe(function() {
            try {
                func();
            } catch(e) {
                console.log("Failed to run constructor: " + e);
            }
        });
    }
};

window.cordova = module.exports = cordova;
<commit_msg>browserify version rethrows also<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

var channel = require('cordova/channel');
var platform = require('cordova/platform');

/**
 * Intercept calls to addEventListener + removeEventListener and handle deviceready,
 * resume, and pause events.
 */
var m_document_addEventListener = document.addEventListener;
var m_document_removeEventListener = document.removeEventListener;
var m_window_addEventListener = window.addEventListener;
var m_window_removeEventListener = window.removeEventListener;

/**
 * Houses custom event handlers to intercept on document + window event listeners.
 */
var documentEventHandlers = {},
    windowEventHandlers = {};

document.addEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    if (typeof documentEventHandlers[e] != 'undefined') {
        documentEventHandlers[e].subscribe(handler);
    } else {
        m_document_addEventListener.call(document, evt, handler, capture);
    }
};

window.addEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    if (typeof windowEventHandlers[e] != 'undefined') {
        windowEventHandlers[e].subscribe(handler);
    } else {
        m_window_addEventListener.call(window, evt, handler, capture);
    }
};

document.removeEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    // If unsubscribing from an event that is handled by a plugin
    if (typeof documentEventHandlers[e] != "undefined") {
        documentEventHandlers[e].unsubscribe(handler);
    } else {
        m_document_removeEventListener.call(document, evt, handler, capture);
    }
};

window.removeEventListener = function(evt, handler, capture) {
    var e = evt.toLowerCase();
    // If unsubscribing from an event that is handled by a plugin
    if (typeof windowEventHandlers[e] != "undefined") {
        windowEventHandlers[e].unsubscribe(handler);
    } else {
        m_window_removeEventListener.call(window, evt, handler, capture);
    }
};

function createEvent(type, data) {
    var event = document.createEvent('Events');
    event.initEvent(type, false, false);
    if (data) {
        for (var i in data) {
            if (data.hasOwnProperty(i)) {
                event[i] = data[i];
            }
        }
    }
    return event;
}

var cordova = {
    platformVersion:PLATFORM_VERSION_BUILD_LABEL,
    version:PLATFORM_VERSION_BUILD_LABEL,
    require: function(module) {
        if(module === "cordova/exec") {
            return cordova.exec;
        }
        if(module === "org.apache.cordova.media.Media") {
            return window.Media;
        }

        return require(module);
    },
    platformId:platform.id,
    /**
     * Methods to add/remove your own addEventListener hijacking on document + window.
     */
    addWindowEventHandler:function(event) {
        return (windowEventHandlers[event] = channel.create(event));
    },
    addStickyDocumentEventHandler:function(event) {
        return (documentEventHandlers[event] = channel.createSticky(event));
    },
    addDocumentEventHandler:function(event) {
        return (documentEventHandlers[event] = channel.create(event));
    },
    removeWindowEventHandler:function(event) {
        delete windowEventHandlers[event];
    },
    removeDocumentEventHandler:function(event) {
        delete documentEventHandlers[event];
    },
    /**
     * Retrieve original event handlers that were replaced by Cordova
     *
     * @return object
     */
    getOriginalHandlers: function() {
        return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},
        'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};
    },
    /**
     * Method to fire event from native code
     * bNoDetach is required for events which cause an exception which needs to be caught in native code
     */
    fireDocumentEvent: function(type, data, bNoDetach) {
        var evt = createEvent(type, data);
        if (typeof documentEventHandlers[type] != 'undefined') {
            if( bNoDetach ) {
                documentEventHandlers[type].fire(evt);
            }
            else {
                setTimeout(function() {
                    // Fire deviceready on listeners that were registered before cordova.js was loaded.
                    if (type == 'deviceready') {
                        document.dispatchEvent(evt);
                    }
                    documentEventHandlers[type].fire(evt);
                }, 0);
            }
        } else {
            document.dispatchEvent(evt);
        }
    },
    fireWindowEvent: function(type, data) {
        var evt = createEvent(type,data);
        if (typeof windowEventHandlers[type] != 'undefined') {
            setTimeout(function() {
                windowEventHandlers[type].fire(evt);
            }, 0);
        } else {
            window.dispatchEvent(evt);
        }
    },

    /**
     * Plugin callback mechanism.
     */
    // Randomize the starting callbackId to avoid collisions after refreshing or navigating.
    // This way, it's very unlikely that any new callback would get the same callbackId as an old callback.
    callbackId: Math.floor(Math.random() * 2000000000),
    callbacks:  {},
    callbackStatus: {
        NO_RESULT: 0,
        OK: 1,
        CLASS_NOT_FOUND_EXCEPTION: 2,
        ILLEGAL_ACCESS_EXCEPTION: 3,
        INSTANTIATION_EXCEPTION: 4,
        MALFORMED_URL_EXCEPTION: 5,
        IO_EXCEPTION: 6,
        INVALID_ACTION: 7,
        JSON_EXCEPTION: 8,
        ERROR: 9
    },
    /**
     * Called by native code when returning successful result from an action.
     */
    callbackSuccess: function(callbackId, args) {
        this.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
    },
    /**
     * Called by native code when returning error result from an action.
     */
    callbackError: function(callbackId, args) {
        // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
        // Derive success from status.
        this.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
    },
    /**
     * Called by native code when returning the result from an action.
     */
    callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) {
        try {
            var callback = cordova.callbacks[callbackId];
            if (callback) {
                if (isSuccess && status == cordova.callbackStatus.OK) {
                    callback.success && callback.success.apply(null, args);
                } else {
                    callback.fail && callback.fail.apply(null, args);
                }

                // Clear callback if not expecting any more results
                if (!keepCallback) {
                    delete cordova.callbacks[callbackId];
                }
            }
        }
        catch(err) {
            var msg = "Error in " + (isSuccess ? "Success" : "Error") + " callbackId: " + callbackId + " : " + err;
            console && console.log && console.log(msg);
            this.fireWindowEvent("cordovacallbackerror", { 'message': msg });
            throw err;
        }
    },
    addConstructor: function(func) {
        channel.onCordovaReady.subscribe(function() {
            try {
                func();
            } catch(e) {
                console.log("Failed to run constructor: " + e);
            }
        });
    }
};

window.cordova = module.exports = cordova;
<|endoftext|>


<commit_before>// import React from 'react';
import utilities from './index';
import { _invokeWebhooks } from './webhooks';
// import AppError404 from '../components/AppError404';

/**
 * Because these dynamic data fetching functions are used in multiple locations this function standardizes access to the getState function
 * @return {Function} Returns the getState function that is either on this.props or on this directly
 */
var _getState = function () {
  return (this.props && typeof this.props.getState === 'function') ? this.props.getState : this.getState;
};

/**
 * Sets parameterized values derived from window location to their respective resource path counterparts
 * @param  {string} pathname  The dynamic path that parameters should be set in
 * @param  {Object} resources Contains resource paths
 * @param  {string} [current]   The actual current window path. If this argument is not passed the window path will be pulled from the window object or from this.props
 * @return {Object}           Returns the resource object with populated dynamic routes
 */
export const _handleDynamicParams = function (pathname, resources, current) {
  // console.log('_handleDynamicParams',{ pathname, resources, current });
  let currentPathname;
  if (typeof current === 'string') currentPathname = current;
  else currentPathname = (typeof window!== 'undefined' && window.location.pathname) ? window.location.pathname : this.props.location.pathname;
  return Object.keys(resources).reduce((result, key) => {
    let updatedPath = utilities.setParameters({
      route: pathname,
      location: currentPathname,
      query: (/\?[^\s]+$/.test(currentPathname)) ? currentPathname.replace(/\?([^\s]+)$/g, '$1') : undefined,
      resource: resources[key],
    });
    result[key] = updatedPath;
    return result;
  }, {});
};

/**
 * Handles making fetch requests for resource paths
 * @param  {Object} layout    Configuration for dynamic page, component or modal
 * @param  {Object} [resources={}] Dynamically loaded resources stored as resource name and resource path key value pairs
 * @param  {Object} [options={}]   Configurable options
 * @param {Function} [options.onSuccess] Optional success function
 * @param {Function} [options.onError] Optional error function
 */
export const _handleFetchPaths = function (layout, resources = {}, options = {}) {
  let state = _getState.call(this)();
  let headers = (state.settings && state.settings.userprofile && state.settings.userprofile.options && state.settings.userprofile.options.headers)
    ? state.settings.userprofile.options.headers
    : {};
  delete headers.clientid_default;
  if (state.user && state.user.jwt_token) {
    headers[ 'x-access-token' ] = state.user.jwt_token;
  }

  return utilities.fetchPaths.call(this, state.settings.basename, resources, headers)
    .then((typeof options.onSuccess === 'function') ? options.onSuccess : _resources => {
      if (!_resources || (_resources && !_resources.__hasError)) {
        this.uiLayout = this.getRenderedComponent(layout, _resources);
        this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
        if (options.callbacks) _invokeWebhooks.call(this, options.callbacks);
      }
    })
    .catch((typeof options.onError === 'function') ? e => options.onError( e, 'fetchResources', resources) : e => {
      if (this.props && this.props.errorNotification) this.props.errorNotification(e);
      else console.error(e);
      this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
    });
};

/**
 * Sets a configurable 404 error component or sets a default 404 component
 */
export const fetchErrorContent = function _fetchErrorContent (e, type, resources) {
  console.debug('fetchErrorContent', e, { type, resources, });
  let getState = _getState.call(this);
  let state = getState();
  let custom404Error;
  let componentData;
  let windowTitle;
  let navLabel;
  let get404Error = utilities.get404Error.bind(this);
  let errorComponents = (state.ui && state.ui.components && state.ui.components.error) ? state.ui.components.error : false;
  let errorCode = (type === 'fetchResources')
    ? '400'
    : '404';
  // console.debug({ errorComponents });

  get404Error({
    getState, _handleFetchPaths, state, custom404Error, componentData, windowTitle, navLabel, errorComponents, errorCode, resources, e,
  });
};

/**
 * Gets a dynamic page element and handles resolving async props if resources exist
 * @param  {string}  pathname  Dynamic page manifest pathname
 * @param  {Boolean} hasParams If true will attempt to assign dynamic params to resource path
 */
export const fetchSuccessContent = function _fetchSuccessContent (pathname, hasParams) {
  try {
    let getState = _getState.call(this);
    let state = getState();
    let containers = state.manifest.containers;
    let layout = Object.assign({}, containers[pathname].layout);
    if (containers[pathname].dynamic && typeof containers[pathname].dynamic === 'object') {
      Object.keys(containers[pathname].dynamic).forEach(dynamicProp => {
        this.props.setDynamicData(dynamicProp, containers[pathname].dynamic[dynamicProp]);
      });
    }
    if (containers[pathname].resources && typeof containers[pathname].resources === 'object') {
      let container = containers[pathname];
      let resources = container.resources;
      if (hasParams) resources = _handleDynamicParams.call(this, pathname, resources, (typeof this.props.pathname === 'string') ? this.props.pathname : undefined);
      if (container.pageData && container.pageData.title) window.document.title = container.pageData.title;
      if (container.pageData && container.pageData.navLabel && this.props && this.props.setNavLabel) this.props.setNavLabel(container.pageData.navLabel);
      else if (this.props && this.props.setNavLabel) this.props.setNavLabel('');
      return _handleFetchPaths.call(this, layout, resources, {
        getState,
        onError: fetchErrorContent.bind(this),
        callbacks: containers[pathname].callbacks,
      });
    } else {
      if (containers[pathname].callbacks) _invokeWebhooks.call(this, containers[pathname].callbacks);
      this.uiLayout = this.getRenderedComponent(containers[pathname].layout);
      this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
      if(window && window.scrollTo){
        window.scrollTo(0, 0);
      }
    }
  } catch (e) {
    if (this.props && this.props.errorNotification) this.props.errorNotification(e);
    else console.error(e);
    this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
    if(window && window.scrollTo){
      window.scrollTo(0, 0);
    }
  }
};

/**
 * Gets dynamic content for a given page, component, modal
 * @param  {string} [_pathname] The window path that should content is being fetched for. If the argument is not passed it will defaul to window.location.pathname
 * @param  {Function} [onSuccess] Optional success function override. If this isnt passed resource paths will be fetched for async props
 * @param  {Function} onError   Optional error function override. If this isnt passed 404 error page will be rendered
 */
export const fetchDynamicContent = function _fetchDynamicContent (_pathname, onSuccess, onError) {
  let pathname;
  let getState = _getState.call(this);
  let state = getState();
  if (typeof _pathname === 'string'){
    pathname = _pathname;
  } else {
    pathname = (window.location.pathname)
      ? window.location.pathname
      : this.props.location.pathname;
  }
  onSuccess = (typeof onSuccess === 'function')
    ? onSuccess
    : fetchSuccessContent.bind(this);
  onError = (typeof onError === 'function')
    ? onError
    : fetchErrorContent.bind(this);
  // console.log({pathname}, onSuccess, onError)
  if (state.manifest.containers[pathname]) {
    return onSuccess(pathname);
  } else if (state.manifest.containers[pathname.replace(state.settings.auth.admin_path, '')]) {
    let adminPathname = pathname.replace(state.settings.auth.admin_path, '');
    return onSuccess(adminPathname);
  } else {
    let dynamicPathname = utilities.findMatchingRoute(state.manifest.containers, pathname.replace(state.settings.auth.admin_path, ''));
    if (!dynamicPathname) return onError();
    return onSuccess(dynamicPathname, true);
  }
};

export const fetchAction = function _fetchAction(pathname, fetchOptions, success) {
  // let pathname, fetchOptions, success;
  if (typeof pathname === 'object') {
    pathname = pathname.pathname;
    fetchOptions = pathname.fetchOptions;
    success = pathname.success;
  }
  // console.debug('in fetch action this', this,{ pathname, fetchOptions, success, customThis, });
  let state = _getState.call(this)();
  let headers = (state.settings && state.settings.userprofile && state.settings.userprofile.options && state.settings.userprofile.options.headers)
    ? state.settings.userprofile.options.headers
    : {};
  let successCallback = console.debug;
  delete headers.clientid_default;
  if (state.user && state.user.jwt_token) {
    headers[ 'x-access-token' ] = state.user.jwt_token;
  }
  fetchOptions.headers = Object.assign({}, fetchOptions.headers, headers);

  fetch(pathname, fetchOptions)
    .then(utilities.checkStatus)
    .then(res => {
      if (success.success) {
        if (success.success.modal) {
          this.props.createModal(success.success.modal);
        } else if (success.success.notification) {
          this.props.createNotification(success.success.notification);
        } else {
          this.props.createNotification({ text: 'Saved', timeout:4000, type:'success',  });
        }
      }
      if (success.successCallback) {
        res.json()
          .then(successData => {
            let successCallbackProp = success.successCallback;
            if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:this.props.reduxRouter') !== -1) {
              successCallback = this.props.reduxRouter[ successCallbackProp.replace('func:this.props.reduxRouter.', '') ];
            } else if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:this.props') !== -1) {
              successCallback = this.props[ success.successCallback.replace('func:this.props.', '') ];
            } else if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:window') !== -1 && typeof window[ success.successCallback.replace('func:window.', '') ]==='function') {
              successCallback = window[ success.successCallback.replace('func:window.', '') ].bind(this);
            }
            if (fetchOptions.successCallback === 'func:this.props.setDynamicData') {
              this.props.setDynamicData(success.dynamicField, success.successProps || successData);
            } else {
              successCallback(success.successProps || successData);
            }
          });
      } else {
        return res.json();
      }
    }).catch(this.props.errorNotification);
};
<commit_msg>added pageScroll;<commit_after>// import React from 'react';
import utilities from './index';
import { _invokeWebhooks } from './webhooks';
// import AppError404 from '../components/AppError404';

/**
 * Because these dynamic data fetching functions are used in multiple locations this function standardizes access to the getState function
 * @return {Function} Returns the getState function that is either on this.props or on this directly
 */
var _getState = function () {
  return (this.props && typeof this.props.getState === 'function') ? this.props.getState : this.getState;
};

/**
 * Sets parameterized values derived from window location to their respective resource path counterparts
 * @param  {string} pathname  The dynamic path that parameters should be set in
 * @param  {Object} resources Contains resource paths
 * @param  {string} [current]   The actual current window path. If this argument is not passed the window path will be pulled from the window object or from this.props
 * @return {Object}           Returns the resource object with populated dynamic routes
 */
export const _handleDynamicParams = function (pathname, resources, current) {
  // console.log('_handleDynamicParams',{ pathname, resources, current });
  let currentPathname;
  if (typeof current === 'string') currentPathname = current;
  else currentPathname = (typeof window!== 'undefined' && window.location.pathname) ? window.location.pathname : this.props.location.pathname;
  return Object.keys(resources).reduce((result, key) => {
    let updatedPath = utilities.setParameters({
      route: pathname,
      location: currentPathname,
      query: (/\?[^\s]+$/.test(currentPathname)) ? currentPathname.replace(/\?([^\s]+)$/g, '$1') : undefined,
      resource: resources[key],
    });
    result[key] = updatedPath;
    return result;
  }, {});
};

/**
 * Handles making fetch requests for resource paths
 * @param  {Object} layout    Configuration for dynamic page, component or modal
 * @param  {Object} [resources={}] Dynamically loaded resources stored as resource name and resource path key value pairs
 * @param  {Object} [options={}]   Configurable options
 * @param {Function} [options.onSuccess] Optional success function
 * @param {Function} [options.onError] Optional error function
 */
export const _handleFetchPaths = function (layout, resources = {}, options = {}) {
  let state = _getState.call(this)();
  let headers = (state.settings && state.settings.userprofile && state.settings.userprofile.options && state.settings.userprofile.options.headers)
    ? state.settings.userprofile.options.headers
    : {};
  delete headers.clientid_default;
  if (state.user && state.user.jwt_token) {
    headers[ 'x-access-token' ] = state.user.jwt_token;
  }

  return utilities.fetchPaths.call(this, state.settings.basename, resources, headers)
    .then((typeof options.onSuccess === 'function') ? options.onSuccess : _resources => {
      if (!_resources || (_resources && !_resources.__hasError)) {
        this.uiLayout = this.getRenderedComponent(layout, _resources);
        this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
        if (options.callbacks) _invokeWebhooks.call(this, options.callbacks);
      }
    })
    .catch((typeof options.onError === 'function') ? e => options.onError( e, 'fetchResources', resources) : e => {
      if (this.props && this.props.errorNotification) this.props.errorNotification(e);
      else console.error(e);
      this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
    });
};

/**
 * Sets a configurable 404 error component or sets a default 404 component
 */
export const fetchErrorContent = function _fetchErrorContent (e, type, resources) {
  console.debug('fetchErrorContent', e, { type, resources, });
  let getState = _getState.call(this);
  let state = getState();
  let custom404Error;
  let componentData;
  let windowTitle;
  let navLabel;
  let get404Error = utilities.get404Error.bind(this);
  let errorComponents = (state.ui && state.ui.components && state.ui.components.error) ? state.ui.components.error : false;
  let errorCode = (type === 'fetchResources')
    ? '400'
    : '404';
  // console.debug({ errorComponents });

  get404Error({
    getState, _handleFetchPaths, state, custom404Error, componentData, windowTitle, navLabel, errorComponents, errorCode, resources, e,
  });
};

/**
 * Gets a dynamic page element and handles resolving async props if resources exist
 * @param  {string}  pathname  Dynamic page manifest pathname
 * @param  {Boolean} hasParams If true will attempt to assign dynamic params to resource path
 */
export const fetchSuccessContent = function _fetchSuccessContent (pathname, hasParams) {
  try {
    let getState = _getState.call(this);
    let state = getState();
    let containers = state.manifest.containers;
    let layout = Object.assign({}, containers[pathname].layout);
    if (containers[pathname].dynamic && typeof containers[pathname].dynamic === 'object') {
      Object.keys(containers[pathname].dynamic).forEach(dynamicProp => {
        this.props.setDynamicData(dynamicProp, containers[pathname].dynamic[dynamicProp]);
      });
    }
    if (containers[pathname].resources && typeof containers[pathname].resources === 'object') {
      let container = containers[pathname];
      let resources = container.resources;
      if (hasParams) resources = _handleDynamicParams.call(this, pathname, resources, (typeof this.props.pathname === 'string') ? this.props.pathname : undefined);
      if (container.pageData && container.pageData.title) window.document.title = container.pageData.title;
      if (container.pageData && container.pageData.navLabel && this.props && this.props.setNavLabel) this.props.setNavLabel(container.pageData.navLabel);
      else if (this.props && this.props.setNavLabel) this.props.setNavLabel('');
      return _handleFetchPaths.call(this, layout, resources, {
        getState,
        onError: fetchErrorContent.bind(this),
        callbacks: containers[pathname].callbacks,
      });
    } else {
      if (containers[pathname].callbacks) _invokeWebhooks.call(this, containers[pathname].callbacks);
      this.uiLayout = this.getRenderedComponent(containers[pathname].layout);
      this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
      if(window && window.scrollTo){
        window.scrollTo(0, 0);
      }
      if (document && document.querySelector && document.querySelector('.reactadmin__app_div_content')){
        document.querySelector('.reactadmin__app_div_content').scrollIntoView(true)
      }
    }
  } catch (e) {
    if (this.props && this.props.errorNotification) this.props.errorNotification(e);
    else console.error(e);
    this.setState({ ui_is_loaded: true, async_data_is_loaded: true, });
    if(window && window.scrollTo){
      window.scrollTo(0, 0);
    }
    if (document && document.querySelector && document.querySelector('.reactadmin__app_div_content')){
      document.querySelector('.reactadmin__app_div_content').scrollIntoView(true)
    }
  }
};

/**
 * Gets dynamic content for a given page, component, modal
 * @param  {string} [_pathname] The window path that should content is being fetched for. If the argument is not passed it will defaul to window.location.pathname
 * @param  {Function} [onSuccess] Optional success function override. If this isnt passed resource paths will be fetched for async props
 * @param  {Function} onError   Optional error function override. If this isnt passed 404 error page will be rendered
 */
export const fetchDynamicContent = function _fetchDynamicContent (_pathname, onSuccess, onError) {
  let pathname;
  let getState = _getState.call(this);
  let state = getState();
  if (typeof _pathname === 'string'){
    pathname = _pathname;
  } else {
    pathname = (window.location.pathname)
      ? window.location.pathname
      : this.props.location.pathname;
  }
  onSuccess = (typeof onSuccess === 'function')
    ? onSuccess
    : fetchSuccessContent.bind(this);
  onError = (typeof onError === 'function')
    ? onError
    : fetchErrorContent.bind(this);
  // console.log({pathname}, onSuccess, onError)
  if (state.manifest.containers[pathname]) {
    return onSuccess(pathname);
  } else if (state.manifest.containers[pathname.replace(state.settings.auth.admin_path, '')]) {
    let adminPathname = pathname.replace(state.settings.auth.admin_path, '');
    return onSuccess(adminPathname);
  } else {
    let dynamicPathname = utilities.findMatchingRoute(state.manifest.containers, pathname.replace(state.settings.auth.admin_path, ''));
    if (!dynamicPathname) return onError();
    return onSuccess(dynamicPathname, true);
  }
};

export const fetchAction = function _fetchAction(pathname, fetchOptions, success) {
  // let pathname, fetchOptions, success;
  if (typeof pathname === 'object') {
    pathname = pathname.pathname;
    fetchOptions = pathname.fetchOptions;
    success = pathname.success;
  }
  // console.debug('in fetch action this', this,{ pathname, fetchOptions, success, customThis, });
  let state = _getState.call(this)();
  let headers = (state.settings && state.settings.userprofile && state.settings.userprofile.options && state.settings.userprofile.options.headers)
    ? state.settings.userprofile.options.headers
    : {};
  let successCallback = console.debug;
  delete headers.clientid_default;
  if (state.user && state.user.jwt_token) {
    headers[ 'x-access-token' ] = state.user.jwt_token;
  }
  fetchOptions.headers = Object.assign({}, fetchOptions.headers, headers);

  fetch(pathname, fetchOptions)
    .then(utilities.checkStatus)
    .then(res => {
      if (success.success) {
        if (success.success.modal) {
          this.props.createModal(success.success.modal);
        } else if (success.success.notification) {
          this.props.createNotification(success.success.notification);
        } else {
          this.props.createNotification({ text: 'Saved', timeout:4000, type:'success',  });
        }
      }
      if (success.successCallback) {
        res.json()
          .then(successData => {
            let successCallbackProp = success.successCallback;
            if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:this.props.reduxRouter') !== -1) {
              successCallback = this.props.reduxRouter[ successCallbackProp.replace('func:this.props.reduxRouter.', '') ];
            } else if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:this.props') !== -1) {
              successCallback = this.props[ success.successCallback.replace('func:this.props.', '') ];
            } else if (typeof successCallbackProp === 'string' && successCallbackProp.indexOf('func:window') !== -1 && typeof window[ success.successCallback.replace('func:window.', '') ]==='function') {
              successCallback = window[ success.successCallback.replace('func:window.', '') ].bind(this);
            }
            if (fetchOptions.successCallback === 'func:this.props.setDynamicData') {
              this.props.setDynamicData(success.dynamicField, success.successProps || successData);
            } else {
              successCallback(success.successProps || successData);
            }
          });
      } else {
        return res.json();
      }
    }).catch(this.props.errorNotification);
};
<|endoftext|>


<commit_before>// my_scripts.js
// Modified: 03/05/2007
// This file contains global variables and functions.  This file
// should be minimized and abstracted whenever possible.  It is
// best to refrain from adding new variables/functions to this
// file.

var wait_for_input;
var edit_popup_open = 0;
var num_orig_anno;
var anno_count = 0;
var global_count = 0;
var req_submit;
var submission_edited = 0; // If polygon has been edited.

// Allowable user actions:
var action_CreatePolygon = 1;
var action_RenameExistingObjects = 0;
var action_ModifyControlExistingObjects = 0;
var action_DeleteExistingObjects = 0;

// Which polygons are visible:
var view_Existing = 1;
var view_Deleted = 0;

// Flag for right-hand object list:
var view_ObjList = true;

// MT variables:
// var LMbaseurl = 'http://old-labelme.csail.mit.edu/developers/brussell/LabelMe-video/tool.html';
// var MThelpPage = 'http://old-labelme.csail.mit.edu/developers/brussell/LabelMe-video/mt_instructions.html';
// var LMbaseurl = 'http://labelme.csail.mit.edu/tool.html';
var LMbaseurl = 'http://' + window.location.host + window.location.pathname;
// var MThelpPage = 'http://labelme.csail.mit.edu/mt_instructions.html';
var MThelpPage = 'annotationTools/html/mt_instructions.html';
var externalSubmitURL = 'http://mturk.com/mturk/externalSubmit';
var externalSubmitURLsandbox = 'http://workersandbox.mturk.com/mturk/externalSubmit';
var mt_N = 'inf';

var object_choices = '...';

// Get the x position of the mouse event.
function GetEventPosX(event) {
  if(IsNetscape()) return event.layerX;
  return event.offsetX;
}

// Get the y position of the mouse event.
function GetEventPosY(event) {
  if(IsNetscape()) return event.layerY;
  return event.offsetY;
}

// If IE, then makes the HTML to show the 'next' icon with the appropriate
// transparencies; if firefox, then just make an img src to show the image
function ShowUndoImg() {
  var oo = document.createElementNS(xhtmlNS,'img');
  oo.setAttributeNS(null,"id","undo_image_png");
  oo.setAttributeNS(null,"src","Icons/undo.png");
  oo.setAttributeNS(null,"style","cursor:hand; width:3em;");
  document.getElementById('png_undo').appendChild(oo);
}

function RemoveSpecialChars(str) {
  var re = /\$|@|#|~|`|\%|\*|\^|\&|\+|\=|\[|\]|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$/g;
  return str.replace(re,"_");
}

function WaitForInput() {
  alert("Need to enter object name.");
}

// Return true if the username is "anonymous".
function IsUserAnonymous() {
  return (username=='anonymous');
}

function IsUserAdmin() {
  var is_admin = false;
  var folder = main_image.GetFileInfo().GetDirName();
  var idx = folder.indexOf('/');
  if((idx != -1) && (folder.substring(0,idx)=='users')) {
    folder = folder.substring(idx+1,folder.length);
    idx = folder.indexOf('/');
    if((idx != -1) && (folder.substring(0,idx)==username)) is_admin = true;
  }
  return (username=='admin') | (username=='mtsupervisor') | is_admin | ((username.indexOf('submitted')!=-1)&(username==folder));
}

function IsCreator(u) {
  return (username==u);
}

function WriteLogMsg(msg) {
  var url = 'annotationTools/perl/write_logfile.cgi';
  var req_submit;
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.open("POST", url, true);
    req_submit.send(msg);
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.open("POST", url, true);
      req_submit.send(msg);
    }
  }
}

function loadXMLDoc() {
  if(wait_for_input) return WaitForInput();
  if(main_draw_canvas.GetAnnotation()) {
    alert("Need to close current polygon first.");
    return;
  }

  // Get a new image:
  var p = document.getElementById('main_image');
  p.parentNode.removeChild(p);

  RemoveAnnotationList();

  main_image.GetNewImage();
}

function ShowNextImage() {
  var s = document.getElementById("submitform");
  if(s!=null) s.submit();
}

// Insert HTML code after a div element:
function InsertAfterDiv(html_str,tag_id) {
  if((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
    Range.prototype.createContextualFragment = function(html) {
      var frag = document.createDocumentFragment(),
      div = document.createElement("div");
      frag.appendChild(div);
      div.outerHTML = html;
      return frag;
    };
  }

  var elt = document.getElementById(tag_id);
  var x = document.createRange();
  try {
    x.setStartAfter(elt);
  }
  catch(err) {
    alert(tag_id);
  }
  x = x.createContextualFragment(html_str);
  elt.appendChild(x);
}

function ChangeLinkColorBG(idx) {
  if(document.getElementById('Link'+idx)) {
    var isDeleted = main_canvas.GetAnnotations()[idx].GetDeleted();
    if(isDeleted) document.getElementById('Link'+idx).style.color = '#888888';
    else document.getElementById('Link'+idx).style.color = '#0000FF';
  }
}

function ChangeLinkColorFG(idx) {
  document.getElementById('Link'+idx).style.color = '#FF0000';
}

function UpdateCounterHTML() {
  var m = main_image.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) return;
  document.getElementById('anno_count').innerHTML = anno_count;
}

function LoadCounterText() {
  var cookie_counter = getCookie('counter');
  if(cookie_counter > anno_count) anno_count = cookie_counter;

  var objXml = XMLGet('annotationCache/counter');

  if(objXml.status==200) {
    var tmp_count = parseInt(objXml.responseText);
    if(tmp_count > anno_count) {
      anno_count = tmp_count;
      setCookie('counter',anno_count);
    }
    UpdateCounterHTML();
  }
  else if(objXml.status==404) {
    alert('counter file not found');
  }
  else {
    alert('Unknown objXml.status');
  }
}

function XMLGet(fname) {
  var url = 'annotationTools/perl/get_anno_file.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send(fname);
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send(fname);
    }
  }
  return req_anno;
}

function LoadAnnotationSuccess(xml) {
  // Set global variable:
  LM_xml = xml;

  var obj_elts = LM_xml.getElementsByTagName("object");
  var num_obj = obj_elts.length;

  main_canvas.CreateNewAnnotations(num_obj);
  num_orig_anno = num_obj;

  // Set object IDs:
  for(var pp = 0; pp < num_obj; pp++) {
    var curr_obj = $(LM_xml).children("annotation").children("object").eq(pp);
    if(curr_obj.children("id").length > 0) {
      curr_obj.children("id").text(""+pp);
    }
    else {
      curr_obj.append($("<id>" + pp + "</id>"));
    }
  }

  // loop over annotated objects
  for(var pp = 0; pp < num_obj; pp++) {
    main_canvas.GetAnnotations()[pp] = new annotation(pp);

    // insert username field. Set it to "anonymous" if it is empty
    if((obj_elts[pp].getElementsByTagName("username").length>0) && obj_elts[pp].getElementsByTagName("username")[0].firstChild)
      main_canvas.GetAnnotations()[pp].SetUsername(obj_elts[pp].getElementsByTagName("username")[0].firstChild.nodeValue);
    else
      main_canvas.GetAnnotations()[pp].SetUsername("anonymous");

    // Set object IDs:
    main_canvas.GetAnnotations()[pp].SetID(""+pp);

    // insert object name
    if(!obj_elts[pp].getElementsByTagName("name")[0].firstChild)
      main_canvas.GetAnnotations()[pp].SetObjName(''); // if it does not exist set it to be empty
    else
      main_canvas.GetAnnotations()[pp].SetObjName(obj_elts[pp].getElementsByTagName("name")[0].firstChild.nodeValue);

    // insert polygon
    var pt_elts = obj_elts[pp].getElementsByTagName("polygon")[0].getElementsByTagName("pt");
    var numpts = pt_elts.length;
    main_canvas.GetAnnotations()[pp].CreatePtsX(numpts);
    main_canvas.GetAnnotations()[pp].CreatePtsY(numpts);
    for(ii=0; ii < numpts; ii++) {
      main_canvas.GetAnnotations()[pp].GetPtsX()[ii] = parseInt(pt_elts[ii].getElementsByTagName("x")[0].firstChild.nodeValue);
      main_canvas.GetAnnotations()[pp].GetPtsY()[ii] = parseInt(pt_elts[ii].getElementsByTagName("y")[0].firstChild.nodeValue);
    }
  }

  main_canvas.DrawAllPolygons();
  if(view_ObjList) LoadAnnotationList();
}

// Annotation file does not exist, so load template:
function LoadAnnotation404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML(main_image.GetFileInfo().GetTemplatePath(),LoadTemplateSuccess,LoadTemplate404);
  else
    alert(jqXHR.status);
}

// Annotation template does not exist for this folder, so load default
// LabelMe template:
function LoadTemplate404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML('annotationCache/XMLTemplates/labelme.xml',LoadTemplateSuccess,function(jqXHR) {
	alert(jqXHR.status);
      });
  else
    alert(jqXHR.status);
}

// Actions after template load success:
function LoadTemplateSuccess(xml) {
  LM_xml = xml;
  LM_xml.getElementsByTagName("filename")[0].firstChild.nodeValue = '\n'+main_image.GetFileInfo().GetImName()+'\n';
  LM_xml.getElementsByTagName("folder")[0].firstChild.nodeValue = '\n'+main_image.GetFileInfo().GetDirName()+'\n';
  main_canvas.CreateNewAnnotations(0);
  num_orig_anno = 0;
  if(view_ObjList) LoadAnnotationList();
}

function InsertServerLogData(modifiedControlPoints) {
  var old_pri = LM_xml.getElementsByTagName("private");
  for(ii=0;ii<old_pri.length;ii++) {
    old_pri[ii].parentNode.removeChild(old_pri[ii]);
  }

  // Add information to go into the log:
  var elt_pri = LM_xml.createElement("private");
  var elt_gct = LM_xml.createElement("global_count");
  var elt_user = LM_xml.createElement("pri_username");
  var elt_edt = LM_xml.createElement("edited");
  var elt_onm = LM_xml.createElement("old_name");
  var elt_nnm = LM_xml.createElement("new_name");
  var elt_mcp = LM_xml.createElement("modified_cpts");

  var txt_gct = LM_xml.createTextNode(global_count);
  var txt_user = LM_xml.createTextNode(username);
  var txt_edt = LM_xml.createTextNode(submission_edited);
  var txt_onm = LM_xml.createTextNode(old_name);
  var txt_nnm = LM_xml.createTextNode(new_name);
  var txt_mcp = LM_xml.createTextNode(modifiedControlPoints);
  var txt_pri = LM_xml.createTextNode(ref);

  LM_xml.documentElement.appendChild(elt_pri);
  elt_pri.appendChild(elt_gct);
  elt_pri.appendChild(elt_user);
  elt_pri.appendChild(elt_edt);
  elt_pri.appendChild(elt_onm);
  elt_pri.appendChild(elt_nnm);
  elt_pri.appendChild(elt_mcp);
  elt_pri.appendChild(txt_pri);

  elt_gct.appendChild(txt_gct);
  elt_user.appendChild(txt_user);
  elt_edt.appendChild(txt_edt);
  elt_onm.appendChild(txt_onm);
  elt_nnm.appendChild(txt_nnm);
  elt_mcp.appendChild(txt_mcp);
}

function PermissionError() {
  var m = main_image.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.');
  }
  else {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.  Do not forget to sign in if you want to be able to edit your annotations');
  }
}

function GetTimeStamp() {
  var url = 'annotationTools/perl/get_timestamp.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send();
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send();
    }
  }

  if(req_anno.status==200) return req_anno.responseText;
  return '';
}
<commit_msg>removed SetID()<commit_after>// my_scripts.js
// Modified: 03/05/2007
// This file contains global variables and functions.  This file
// should be minimized and abstracted whenever possible.  It is
// best to refrain from adding new variables/functions to this
// file.

var wait_for_input;
var edit_popup_open = 0;
var num_orig_anno;
var anno_count = 0;
var global_count = 0;
var req_submit;
var submission_edited = 0; // If polygon has been edited.

// Allowable user actions:
var action_CreatePolygon = 1;
var action_RenameExistingObjects = 0;
var action_ModifyControlExistingObjects = 0;
var action_DeleteExistingObjects = 0;

// Which polygons are visible:
var view_Existing = 1;
var view_Deleted = 0;

// Flag for right-hand object list:
var view_ObjList = true;

// MT variables:
// var LMbaseurl = 'http://old-labelme.csail.mit.edu/developers/brussell/LabelMe-video/tool.html';
// var MThelpPage = 'http://old-labelme.csail.mit.edu/developers/brussell/LabelMe-video/mt_instructions.html';
// var LMbaseurl = 'http://labelme.csail.mit.edu/tool.html';
var LMbaseurl = 'http://' + window.location.host + window.location.pathname;
// var MThelpPage = 'http://labelme.csail.mit.edu/mt_instructions.html';
var MThelpPage = 'annotationTools/html/mt_instructions.html';
var externalSubmitURL = 'http://mturk.com/mturk/externalSubmit';
var externalSubmitURLsandbox = 'http://workersandbox.mturk.com/mturk/externalSubmit';
var mt_N = 'inf';

var object_choices = '...';

// Get the x position of the mouse event.
function GetEventPosX(event) {
  if(IsNetscape()) return event.layerX;
  return event.offsetX;
}

// Get the y position of the mouse event.
function GetEventPosY(event) {
  if(IsNetscape()) return event.layerY;
  return event.offsetY;
}

// If IE, then makes the HTML to show the 'next' icon with the appropriate
// transparencies; if firefox, then just make an img src to show the image
function ShowUndoImg() {
  var oo = document.createElementNS(xhtmlNS,'img');
  oo.setAttributeNS(null,"id","undo_image_png");
  oo.setAttributeNS(null,"src","Icons/undo.png");
  oo.setAttributeNS(null,"style","cursor:hand; width:3em;");
  document.getElementById('png_undo').appendChild(oo);
}

function RemoveSpecialChars(str) {
  var re = /\$|@|#|~|`|\%|\*|\^|\&|\+|\=|\[|\]|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$/g;
  return str.replace(re,"_");
}

function WaitForInput() {
  alert("Need to enter object name.");
}

// Return true if the username is "anonymous".
function IsUserAnonymous() {
  return (username=='anonymous');
}

function IsUserAdmin() {
  var is_admin = false;
  var folder = main_image.GetFileInfo().GetDirName();
  var idx = folder.indexOf('/');
  if((idx != -1) && (folder.substring(0,idx)=='users')) {
    folder = folder.substring(idx+1,folder.length);
    idx = folder.indexOf('/');
    if((idx != -1) && (folder.substring(0,idx)==username)) is_admin = true;
  }
  return (username=='admin') | (username=='mtsupervisor') | is_admin | ((username.indexOf('submitted')!=-1)&(username==folder));
}

function IsCreator(u) {
  return (username==u);
}

function WriteLogMsg(msg) {
  var url = 'annotationTools/perl/write_logfile.cgi';
  var req_submit;
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_submit = new XMLHttpRequest();
    req_submit.open("POST", url, true);
    req_submit.send(msg);
  }
  else if (window.ActiveXObject) {
    req_submit = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_submit) {
      req_submit.open("POST", url, true);
      req_submit.send(msg);
    }
  }
}

function loadXMLDoc() {
  if(wait_for_input) return WaitForInput();
  if(main_draw_canvas.GetAnnotation()) {
    alert("Need to close current polygon first.");
    return;
  }

  // Get a new image:
  var p = document.getElementById('main_image');
  p.parentNode.removeChild(p);

  RemoveAnnotationList();

  main_image.GetNewImage();
}

function ShowNextImage() {
  var s = document.getElementById("submitform");
  if(s!=null) s.submit();
}

// Insert HTML code after a div element:
function InsertAfterDiv(html_str,tag_id) {
  if((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
    Range.prototype.createContextualFragment = function(html) {
      var frag = document.createDocumentFragment(),
      div = document.createElement("div");
      frag.appendChild(div);
      div.outerHTML = html;
      return frag;
    };
  }

  var elt = document.getElementById(tag_id);
  var x = document.createRange();
  try {
    x.setStartAfter(elt);
  }
  catch(err) {
    alert(tag_id);
  }
  x = x.createContextualFragment(html_str);
  elt.appendChild(x);
}

function ChangeLinkColorBG(idx) {
  if(document.getElementById('Link'+idx)) {
    var isDeleted = main_canvas.GetAnnotations()[idx].GetDeleted();
    if(isDeleted) document.getElementById('Link'+idx).style.color = '#888888';
    else document.getElementById('Link'+idx).style.color = '#0000FF';
  }
}

function ChangeLinkColorFG(idx) {
  document.getElementById('Link'+idx).style.color = '#FF0000';
}

function UpdateCounterHTML() {
  var m = main_image.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) return;
  document.getElementById('anno_count').innerHTML = anno_count;
}

function LoadCounterText() {
  var cookie_counter = getCookie('counter');
  if(cookie_counter > anno_count) anno_count = cookie_counter;

  var objXml = XMLGet('annotationCache/counter');

  if(objXml.status==200) {
    var tmp_count = parseInt(objXml.responseText);
    if(tmp_count > anno_count) {
      anno_count = tmp_count;
      setCookie('counter',anno_count);
    }
    UpdateCounterHTML();
  }
  else if(objXml.status==404) {
    alert('counter file not found');
  }
  else {
    alert('Unknown objXml.status');
  }
}

function XMLGet(fname) {
  var url = 'annotationTools/perl/get_anno_file.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send(fname);
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send(fname);
    }
  }
  return req_anno;
}

function LoadAnnotationSuccess(xml) {
  // Set global variable:
  LM_xml = xml;

  var obj_elts = LM_xml.getElementsByTagName("object");
  var num_obj = obj_elts.length;

  main_canvas.CreateNewAnnotations(num_obj);
  num_orig_anno = num_obj;

  // Set object IDs:
  for(var pp = 0; pp < num_obj; pp++) {
    var curr_obj = $(LM_xml).children("annotation").children("object").eq(pp);
    if(curr_obj.children("id").length > 0) {
      curr_obj.children("id").text(""+pp);
    }
    else {
      curr_obj.append($("<id>" + pp + "</id>"));
    }
  }

  // loop over annotated objects
  for(var pp = 0; pp < num_obj; pp++) {
    main_canvas.GetAnnotations()[pp] = new annotation(pp);

    // insert username field. Set it to "anonymous" if it is empty
    if((obj_elts[pp].getElementsByTagName("username").length>0) && obj_elts[pp].getElementsByTagName("username")[0].firstChild)
      main_canvas.GetAnnotations()[pp].SetUsername(obj_elts[pp].getElementsByTagName("username")[0].firstChild.nodeValue);
    else
      main_canvas.GetAnnotations()[pp].SetUsername("anonymous");

    // insert object name
    if(!obj_elts[pp].getElementsByTagName("name")[0].firstChild)
      main_canvas.GetAnnotations()[pp].SetObjName(''); // if it does not exist set it to be empty
    else
      main_canvas.GetAnnotations()[pp].SetObjName(obj_elts[pp].getElementsByTagName("name")[0].firstChild.nodeValue);

    // insert polygon
    var pt_elts = obj_elts[pp].getElementsByTagName("polygon")[0].getElementsByTagName("pt");
    var numpts = pt_elts.length;
    main_canvas.GetAnnotations()[pp].CreatePtsX(numpts);
    main_canvas.GetAnnotations()[pp].CreatePtsY(numpts);
    for(ii=0; ii < numpts; ii++) {
      main_canvas.GetAnnotations()[pp].GetPtsX()[ii] = parseInt(pt_elts[ii].getElementsByTagName("x")[0].firstChild.nodeValue);
      main_canvas.GetAnnotations()[pp].GetPtsY()[ii] = parseInt(pt_elts[ii].getElementsByTagName("y")[0].firstChild.nodeValue);
    }
  }

  main_canvas.DrawAllPolygons();
  if(view_ObjList) LoadAnnotationList();
}

// Annotation file does not exist, so load template:
function LoadAnnotation404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML(main_image.GetFileInfo().GetTemplatePath(),LoadTemplateSuccess,LoadTemplate404);
  else
    alert(jqXHR.status);
}

// Annotation template does not exist for this folder, so load default
// LabelMe template:
function LoadTemplate404(jqXHR,textStatus,errorThrown) {
  if(jqXHR.status==404)
    ReadXML('annotationCache/XMLTemplates/labelme.xml',LoadTemplateSuccess,function(jqXHR) {
	alert(jqXHR.status);
      });
  else
    alert(jqXHR.status);
}

// Actions after template load success:
function LoadTemplateSuccess(xml) {
  LM_xml = xml;
  LM_xml.getElementsByTagName("filename")[0].firstChild.nodeValue = '\n'+main_image.GetFileInfo().GetImName()+'\n';
  LM_xml.getElementsByTagName("folder")[0].firstChild.nodeValue = '\n'+main_image.GetFileInfo().GetDirName()+'\n';
  main_canvas.CreateNewAnnotations(0);
  num_orig_anno = 0;
  if(view_ObjList) LoadAnnotationList();
}

function InsertServerLogData(modifiedControlPoints) {
  var old_pri = LM_xml.getElementsByTagName("private");
  for(ii=0;ii<old_pri.length;ii++) {
    old_pri[ii].parentNode.removeChild(old_pri[ii]);
  }

  // Add information to go into the log:
  var elt_pri = LM_xml.createElement("private");
  var elt_gct = LM_xml.createElement("global_count");
  var elt_user = LM_xml.createElement("pri_username");
  var elt_edt = LM_xml.createElement("edited");
  var elt_onm = LM_xml.createElement("old_name");
  var elt_nnm = LM_xml.createElement("new_name");
  var elt_mcp = LM_xml.createElement("modified_cpts");

  var txt_gct = LM_xml.createTextNode(global_count);
  var txt_user = LM_xml.createTextNode(username);
  var txt_edt = LM_xml.createTextNode(submission_edited);
  var txt_onm = LM_xml.createTextNode(old_name);
  var txt_nnm = LM_xml.createTextNode(new_name);
  var txt_mcp = LM_xml.createTextNode(modifiedControlPoints);
  var txt_pri = LM_xml.createTextNode(ref);

  LM_xml.documentElement.appendChild(elt_pri);
  elt_pri.appendChild(elt_gct);
  elt_pri.appendChild(elt_user);
  elt_pri.appendChild(elt_edt);
  elt_pri.appendChild(elt_onm);
  elt_pri.appendChild(elt_nnm);
  elt_pri.appendChild(elt_mcp);
  elt_pri.appendChild(txt_pri);

  elt_gct.appendChild(txt_gct);
  elt_user.appendChild(txt_user);
  elt_edt.appendChild(txt_edt);
  elt_onm.appendChild(txt_onm);
  elt_nnm.appendChild(txt_nnm);
  elt_mcp.appendChild(txt_mcp);
}

function PermissionError() {
  var m = main_image.GetFileInfo().GetMode();
  if((m=='im') || (m=='mt')) {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.');
  }
  else {
    alert('This polygon was entered by another user.  You can only modify polygons that you have entered.  Do not forget to sign in if you want to be able to edit your annotations');
  }
}

function GetTimeStamp() {
  var url = 'annotationTools/perl/get_timestamp.cgi';
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req_anno = new XMLHttpRequest();
    req_anno.open("POST", url, false);
    req_anno.send();
  }
  else if (window.ActiveXObject) {
    req_anno = new ActiveXObject("Microsoft.XMLHTTP");
    if (req_anno) {
      req_anno.open("POST", url, false);
      req_anno.send();
    }
  }

  if(req_anno.status==200) return req_anno.responseText;
  return '';
}
<|endoftext|>


<commit_before>const Bot = require('../models/Bot');
const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');

exports.createOrFindBot = asyncFn((botData) => {
	console.log('[App] Creating or loading bot.')
	const foundBot = awaitFn(Bot.findOne());
	if (foundBot) return foundBot;
	const bot = new Bot(botData);
	return awaitFn(bot.save());
});
<commit_msg>adds missing semicolon<commit_after>const Bot = require('../models/Bot');
const asyncFn = require('asyncawait/async');
const awaitFn = require('asyncawait/await');

exports.createOrFindBot = asyncFn((botData) => {
	console.log('[App] Creating or loading bot.');
	const foundBot = awaitFn(Bot.findOne());
	if (foundBot) return foundBot;
	const bot = new Bot(botData);
	return awaitFn(bot.save());
});
<|endoftext|>


<commit_before>'use strict';

var cron = require('node-cron');
var _ = require('lodash');
var semver = require('semver');
var KongService = require('./KongService');
var async = require('async');
var Utils = require('../helpers/utils');

module.exports = {

  takeSnapShot: function (name, node, cb) {

    // Get node
    KongService.nodeInfo(node, function (err, status) {
      if (err) {
        return cb(err);
      }

      var result = {}

      var endpoints = ['/apis', '/plugins', '/consumers']

      status.version = Utils.ensureSemverFormat(status.version);

      if (semver.gte(status.version, '0.10.0')) {
        endpoints = endpoints.concat(['/upstreams']);
      }

      if (semver.gte(status.version, '0.13.0')) {
        endpoints = endpoints.concat(['/services', '/routes']);
      }

      var fns = []

      endpoints.forEach(function (endpoint) {
        fns.push(function (cb) {
          KongService.listAllCb(node, endpoint, function (err, data) {
            if (err) {
              return cb(err);
            }
            result[endpoint.replace("/", "")] = data.data
            return cb();
          });
        });
      });

      async.series(fns, function (err, data) {
        if (err) {
          return cb(err);
        }

        var servicePluginsMap = {};
        var routePluginsMap = {};
        var pluginsUpdated = [];
        var routesUpdated = [];

        _.forEach(result.plugins, function (plugin) {
          if (plugin.service_id) {

            if (!(plugin.service_id in servicePluginsMap)) {
              servicePluginsMap[plugin.service_id] = [];
            }
            servicePluginsMap[plugin.service_id].push(plugin);

          } else if (plugin.route_id) {

            if (!(plugin.route_id in routePluginsMap)) {
              routePluginsMap[plugin.route_id] = [];
            }
            routePluginsMap[plugin.route_id].push(plugin);

          } else {
            pluginsUpdated.push(plugin);
          }
        });

        result.plugins = pluginsUpdated;

        _.forEach(servicePluginsMap, function (arr, service_id) {
          var service = _.find(result.services, {id: service_id});

          if (service) {
            service.plugins = arr
          }

        });

        _.forEach(routePluginsMap, function (arr, route_id) {
          var route = _.find(result.routes, {id: route_id});

          if (route) {
            route.plugins = arr
          }
        });

        _.forEach(result.routes, function (route) {
          var routes = routesUpdated;
          if (route.service && route.service.id) {
            var service = _.find(result.services, {id: route.service.id});

            if (service) {
              if (!service.routes) {
                service.routes = [];
              }
              routes = service.routes;
            }
          }
          routes.push(route);
        });

        result.routes = [];

        // Foreach consumer get it's acls & plugins
        var consumerFns = []
        result.consumers.forEach(function (consumer) {
          consumerFns.push(function (cb) {
            KongService.listAllCb(node, '/consumers/' + consumer.id + '/acls', function (err, data) {
              if (err) {
                return cb();
              }
              sails.log(data)
              if (!consumer.acls) {
                consumer.acls = [];
              }
              data.data.forEach(function (item) {
                consumer.acls.push(item);
              })

              // Also get the consumer's plugins
              KongService.listAllCb(node, '/consumers/' + consumer.id + '/plugins', function (err, data) {
                if (err) {
                  return cb();
                }
                sails.log(data)
                if (!consumer.plugins) {
                  consumer.plugins = [];
                }
                data.data.forEach(function (item) {
                  consumer.plugins.push(item);
                })

                return cb();
              });
            });
          })

          var credentials = ["basic-auth", "key-auth", "hmac-auth", "jwt", "oauth2"]
          credentials.forEach(function (credential) {
            consumerFns.push(function (cb) {
              KongService.listAllCb(node, '/consumers/' + consumer.id + '/' + credential, function (err, data) {
                if (err) {
                  return cb();
                }
                if (!consumer.credentials) {
                  consumer.credentials = {};
                }
                if (!consumer.credentials[credential]) {
                  consumer.credentials[credential] = [];
                }
                data.data.forEach(function (item) {
                  consumer.credentials[credential].push(item);
                })

                return cb();
              });
            });
          });
        })

        async.series(consumerFns, function (err, data) {
          if (err) {
            return cb(err);
          }

          if (semver.gte(status.version, '0.10.0')) {
            // Foreach upstream get it's targets
            var fns = []
            result.upstreams.forEach(function (upstream) {
              fns.push(function (cb) {
                KongService.listAllCb(node, '/upstreams/' + upstream.id + '/targets', function (err, data) {
                  if (err) return cb()
                  sails.log(data.data)
                  if (!result.upstream_targets) result.upstream_targets = []
                  data.data.forEach(function (item) {
                    result.upstream_targets.push(item);
                  })

                  return cb();
                });
              });
            })

            async.series(fns, function (err, data) {
              if (err) {
                return cb(err);
              }

              sails.models.snapshot.create({
                name: name || "snap@" + Date.now(),
                kong_node_name: node.name,
                kong_node_url: node.kong_admin_url,
                kong_version: status.version,
                data: result
              }).exec(function (err, created) {
                if (err) {
                  sails.sockets.blast('events.snapshots', {
                    verb: 'failed',
                    data: {
                      name: node.name + "@" + Date.now()
                    }
                  });
                }

              });
            })
          } else {
            sails.models.snapshot.create({
              name: name || "snap@" + Date.now(),
              kong_node_name: node.name,
              kong_version: node.kong_version,
              data: result
            }).exec(function (err, created) {
              if (err) {
                sails.sockets.blast('events.snapshots', {
                  verb: 'failed',
                  data: {
                    name: node.name + "@" + Date.now()
                  }
                });
              }

            });
          }
        });
      });

    });
  },

}
<commit_msg>Worked on snapshots<commit_after>'use strict';

var cron = require('node-cron');
var _ = require('lodash');
var semver = require('semver');
var KongService = require('./KongService');
var async = require('async');
var Utils = require('../helpers/utils');

module.exports = {

  takeSnapShot: function (name, node, cb) {

    // Get node
    KongService.nodeInfo(node, function (err, status) {
      if (err) {
        return cb(err);
      }

      var result = {}

      var endpoints = ['/apis', '/plugins', '/consumers']

      status.version = Utils.ensureSemverFormat(status.version);

      if (semver.gte(status.version, '0.10.0')) {
        endpoints = endpoints.concat(['/upstreams']);
      }

      if (semver.gte(status.version, '0.13.0')) {
        endpoints = endpoints.concat(['/services', '/routes']);
      }

      var fns = []

      endpoints.forEach(function (endpoint) {
        fns.push(function (cb) {
          KongService.listAllCb(node, endpoint, function (err, data) {
            if (err) {
              return cb(err);
            }
            result[endpoint.replace("/", "")] = data.data
            return cb();
          });
        });
      });

      async.series(fns, function (err, data) {
        if (err) {
          return cb(err);
        }

        var servicePluginsMap = {};
        var consumerPluginsMap = {};
        var routePluginsMap = {};
        var pluginsUpdated = [];
        var routesUpdated = [];

        _.forEach(result.plugins, function (plugin) {
          if (plugin.service_id) {

            if (!(plugin.service_id in servicePluginsMap)) {
              servicePluginsMap[plugin.service_id] = [];
            }
            servicePluginsMap[plugin.service_id].push(plugin);

          } else if (plugin.route_id) {

            if (!(plugin.route_id in routePluginsMap)) {
              routePluginsMap[plugin.route_id] = [];
            }
            routePluginsMap[plugin.route_id].push(plugin);

          } else if(plugin.consumer_id) {
            if (!(plugin.consumer_id in consumerPluginsMap)) {
              consumerPluginsMap[plugin.consumer_id] = [];
            }
            consumerPluginsMap[plugin.consumer_id].push(plugin);
          } else {
            pluginsUpdated.push(plugin);
          }
        });

        result.plugins = pluginsUpdated;

        _.forEach(servicePluginsMap, function (arr, service_id) {
          var service = _.find(result.services, {id: service_id});

          if (service) {
            service.plugins = arr
          }

        });

        _.forEach(routePluginsMap, function (arr, route_id) {
          var route = _.find(result.routes, {id: route_id});

          if (route) {
            route.plugins = arr
          }
        });

        _.forEach(result.routes, function (route) {
          var routes = routesUpdated;
          if (route.service && route.service.id) {
            var service = _.find(result.services, {id: route.service.id});

            if (service) {
              if (!service.routes) {
                service.routes = [];
              }
              routes = service.routes;
            }
          }
          routes.push(route);
        });

        result.routes = [];

        // Foreach consumer get it's acls & plugins
        var consumerFns = []
        result.consumers.forEach(function (consumer) {
          consumerFns.push(function (cb) {
            KongService.listAllCb(node, '/consumers/' + consumer.id + '/acls', function (err, data) {
              if (err) {
                return cb();
              }
              sails.log(data)
              if (!consumer.acls) {
                consumer.acls = [];
              }
              data.data.forEach(function (item) {
                consumer.acls.push(item);
              })

              // Also get the consumer's plugins
              KongService.listAllCb(node, '/consumers/' + consumer.id + '/plugins', function (err, data) {
                if (err) {
                  return cb();
                }
                sails.log(data)
                if (!consumer.plugins) {
                  consumer.plugins = [];
                }
                data.data.forEach(function (item) {
                  consumer.plugins.push(item);
                })

                return cb();
              });
            });
          })

          var credentials = ["basic-auth", "key-auth", "hmac-auth", "jwt", "oauth2"]
          credentials.forEach(function (credential) {
            consumerFns.push(function (cb) {
              KongService.listAllCb(node, '/consumers/' + consumer.id + '/' + credential, function (err, data) {
                if (err) {
                  return cb();
                }
                if (!consumer.credentials) {
                  consumer.credentials = {};
                }
                if (!consumer.credentials[credential]) {
                  consumer.credentials[credential] = [];
                }
                data.data.forEach(function (item) {
                  consumer.credentials[credential].push(item);
                })

                return cb();
              });
            });
          });
        })

        async.series(consumerFns, function (err, data) {
          if (err) {
            return cb(err);
          }

          if (semver.gte(status.version, '0.10.0')) {
            // Foreach upstream get it's targets
            var fns = []
            result.upstreams.forEach(function (upstream) {
              fns.push(function (cb) {
                KongService.listAllCb(node, '/upstreams/' + upstream.id + '/targets', function (err, data) {
                  if (err) return cb()
                  sails.log(data.data)
                  if (!result.upstream_targets) result.upstream_targets = []
                  data.data.forEach(function (item) {
                    result.upstream_targets.push(item);
                  })

                  return cb();
                });
              });
            })

            async.series(fns, function (err, data) {
              if (err) {
                return cb(err);
              }

              sails.models.snapshot.create({
                name: name || "snap@" + Date.now(),
                kong_node_name: node.name,
                kong_node_url: node.kong_admin_url,
                kong_version: status.version,
                data: result
              }).exec(function (err, created) {
                if (err) {
                  sails.sockets.blast('events.snapshots', {
                    verb: 'failed',
                    data: {
                      name: node.name + "@" + Date.now()
                    }
                  });
                }

              });
            })
          } else {
            sails.models.snapshot.create({
              name: name || "snap@" + Date.now(),
              kong_node_name: node.name,
              kong_version: node.kong_version,
              data: result
            }).exec(function (err, created) {
              if (err) {
                sails.sockets.blast('events.snapshots', {
                  verb: 'failed',
                  data: {
                    name: node.name + "@" + Date.now()
                  }
                });
              }

            });
          }
        });
      });

    });
  },

}
<|endoftext|>


<commit_before>(function() {
    exports.testAIPerceptronXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "perceptron", args: [2, 3, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai perceptron 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai perceptron 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai perceptron 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai perceptron 1 XOR 0");
    };

    exports.testAILiquidXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "liquid", args: [2, 20, 1, 30, 10]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai liquid 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai liquid 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai liquid 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai liquid 1 XOR 0");
    };

    exports.testAILSTMXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "lstm", args: [2, 4, 4, 4, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}], { iterations: 100000, error: 0.001 });
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai lstm 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai lstm 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai lstm 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai lstm 1 XOR 0");
    };

    exports.testAINetworkSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "perceptron", args: [2, 3, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [1,0], output: [0]}, {input: [0,1], output: [0]}, {input: [1,1], output :[1]}]);
        nn.writeFile("autoTestAll.xorNet.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.xorNet.gz");

        ow.test.assert(Math.round(na.get([1,0])), Math.round(nn.get([1,0])), "Problem with saved ow.ai perceptron 1 AND 0");
        ow.test.assert(Math.round(na.get([1,1])), Math.round(nn.get([1,1])), "Problem with saved ow.ai perceptron 1 AND 1");
        ow.test.assert(Math.round(na.get([0,1])), Math.round(nn.get([0,1])), "Problem with saved ow.ai perceptron 0 AND 1");
        ow.test.assert(Math.round(na.get([0,0])), Math.round(nn.get([0,0])), "Problem with saved ow.ai perceptron 1 AND 0");

        af.rm("autoTestAll.xorNet.gz");
    };

    exports.testAILSTMXORSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "lstm", args: [2, 4, 4, 4, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}], { iterations: 100000, error: 0.001 });
        nn.writeFile("autoTestAll.ai.xorNet.lstm.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.ai.xorNet.lstm.gz");

        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with saved ow.ai lstm 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with saved ow.ai lstm 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with saved ow.ai lstm 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with saves ow.ai lstm 1 XOR 0");

        af.rm("autoTestAll.ai.xorNet.lstm.gz");
    };

    exports.testAILiquidXORSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "liquid", args: [2, 20, 1, 30, 10]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        nn.writeFile("autoTestAll.ai.xorNet.liquid.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.ai.xorNet.liquid.gz");

        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with saved ow.ai liquid 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with saved ow.ai liquid 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with saved ow.ai liquid 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with saves ow.ai liquid 1 XOR 0");

        af.rm("autoTestAll.ai.xorNet.liquid.gz");
    };

    exports.testNormalizeWithSchema = function() {
        ow.loadAI();

        var ar = [
            {name:'workout', duration:'120', enjoy: true, time:1455063275, tags:['gym', 'weights'], crucial: true },
            {name:'lunch', duration:'45', enjoy: false, time:1455063275, tags:['salad', 'wine'], crucial: false },
            {name:'sleep', duration:'420', enjoy: true, time:1455063275, tags:['bed', 'romance'], crucial: true}
        ];

        var sar = {
            name: {
                col: 0,
                oneOf: [ 'workout', 'lunch', 'sleep' ]
            },
            duration: {
                col: 1,
                min: 0,
                max: 1000
            },
            enjoy: {
                col: 2
            },
            tags: {
                col: 3,
                anyOf: [ 'gym', 'weights', 'salad', 'wine', 'bed', 'romance' ]
            },
            crucial: {
                col: 4,
                scaleOf: [
                    { val: true,  weight: 0.85 },
                    { val: false, weight: 0.15 }
                ]
            },
        };

        var res = $from(ar).sort("time").select((r) => { return ow.ai.normalize.withSchema(r, sar); });

        ow.test.assert(res[0], [1, 0, 0, 0.12, true, 1, 1, 0, 0, 0, 0, 0.85], "Problem with ow.ai.normalize.withSchema (1)");
        ow.test.assert(res[1], [0, 1, 0, 0.045, false, 0, 0, 1, 1, 0, 0, 0.15], "Problem with ow.ai.normalize.withSchema (2)");
        ow.test.assert(res[2], [0, 0, 1, 0.42, true, 0, 0, 0, 0, 1, 1, 0.85], "Problem with ow.ai.normalize.withSchema (3)");
    };
})();<commit_msg>ow.test.AI: Better LSTM network definition for testing<commit_after>(function() {
    exports.testAIPerceptronXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "perceptron", args: [2, 3, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai perceptron 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai perceptron 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai perceptron 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai perceptron 1 XOR 0");
    };

    exports.testAILiquidXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "liquid", args: [2, 20, 1, 30, 10]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai liquid 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai liquid 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai liquid 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai liquid 1 XOR 0");
    };

    exports.testAILSTMXOR = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "lstm", args: [2, 6, 2, 1, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}], { iterations: 100000, error: 0.001 });
        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with ow.ai lstm 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with ow.ai lstm 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with ow.ai lstm 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with ow.ai lstm 1 XOR 0");
    };

    exports.testAINetworkSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "perceptron", args: [2, 3, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [1,0], output: [0]}, {input: [0,1], output: [0]}, {input: [1,1], output :[1]}]);
        nn.writeFile("autoTestAll.xorNet.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.xorNet.gz");

        ow.test.assert(Math.round(na.get([1,0])), Math.round(nn.get([1,0])), "Problem with saved ow.ai perceptron 1 AND 0");
        ow.test.assert(Math.round(na.get([1,1])), Math.round(nn.get([1,1])), "Problem with saved ow.ai perceptron 1 AND 1");
        ow.test.assert(Math.round(na.get([0,1])), Math.round(nn.get([0,1])), "Problem with saved ow.ai perceptron 0 AND 1");
        ow.test.assert(Math.round(na.get([0,0])), Math.round(nn.get([0,0])), "Problem with saved ow.ai perceptron 1 AND 0");

        af.rm("autoTestAll.xorNet.gz");
    };

    exports.testAILSTMXORSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "lstm", args: [2, 6, 2, 1, 1]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}], { iterations: 100000, error: 0.001 });
        nn.writeFile("autoTestAll.ai.xorNet.lstm.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.ai.xorNet.lstm.gz");

        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with saved ow.ai lstm 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with saved ow.ai lstm 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with saved ow.ai lstm 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with saves ow.ai lstm 1 XOR 0");

        af.rm("autoTestAll.ai.xorNet.lstm.gz");
    };

    exports.testAILiquidXORSave = function() {
        ow.loadAI();
        var nn = new ow.ai.network({ type: "liquid", args: [2, 20, 1, 30, 10]});
        nn.train([{input: [0,0], output: [0]}, {input: [0,1], output: [1]}, {input: [1,0], output: [1]}, {input: [1,1], output :[0]}]);
        nn.writeFile("autoTestAll.ai.xorNet.liquid.gz");

        var na = new ow.ai.network();
        na.readFile("autoTestAll.ai.xorNet.liquid.gz");

        ow.test.assert(Math.round(nn.get([1,0])), 1, "Problem with saved ow.ai liquid 1 XOR 0");
        ow.test.assert(Math.round(nn.get([1,1])), 0, "Problem with saved ow.ai liquid 1 XOR 1");
        ow.test.assert(Math.round(nn.get([0,1])), 1, "Problem with saved ow.ai liquid 0 XOR 1");
        ow.test.assert(Math.round(nn.get([0,0])), 0, "Problem with saves ow.ai liquid 1 XOR 0");

        af.rm("autoTestAll.ai.xorNet.liquid.gz");
    };

    exports.testNormalizeWithSchema = function() {
        ow.loadAI();

        var ar = [
            {name:'workout', duration:'120', enjoy: true, time:1455063275, tags:['gym', 'weights'], crucial: true },
            {name:'lunch', duration:'45', enjoy: false, time:1455063275, tags:['salad', 'wine'], crucial: false },
            {name:'sleep', duration:'420', enjoy: true, time:1455063275, tags:['bed', 'romance'], crucial: true}
        ];

        var sar = {
            name: {
                col: 0,
                oneOf: [ 'workout', 'lunch', 'sleep' ]
            },
            duration: {
                col: 1,
                min: 0,
                max: 1000
            },
            enjoy: {
                col: 2
            },
            tags: {
                col: 3,
                anyOf: [ 'gym', 'weights', 'salad', 'wine', 'bed', 'romance' ]
            },
            crucial: {
                col: 4,
                scaleOf: [
                    { val: true,  weight: 0.85 },
                    { val: false, weight: 0.15 }
                ]
            },
        };

        var res = $from(ar).sort("time").select((r) => { return ow.ai.normalize.withSchema(r, sar); });

        ow.test.assert(res[0], [1, 0, 0, 0.12, true, 1, 1, 0, 0, 0, 0, 0.85], "Problem with ow.ai.normalize.withSchema (1)");
        ow.test.assert(res[1], [0, 1, 0, 0.045, false, 0, 0, 1, 1, 0, 0, 0.15], "Problem with ow.ai.normalize.withSchema (2)");
        ow.test.assert(res[2], [0, 0, 1, 0.42, true, 0, 0, 0, 0, 1, 1, 0.85], "Problem with ow.ai.normalize.withSchema (3)");
    };
})();
<|endoftext|>


<commit_before><commit_msg>Cleanup and this binding of the decoration event functions<commit_after><|endoftext|>


<commit_before>/** @license MIT License (c) copyright 2016 original author or authors */

import {describe, it} from 'mocha'
import assert from 'assert'

import { id, compose, apply, curry2, curry3 } from '../src/function'

describe('id', () => {
  it('id(x) === x', () => {
    const x = {}
    assert.strictEqual(id(x), x)
  })
})

describe('compose', () => {
  it('compose(f, g)(x) === f(g(x))', () => {
    const fx = '' + Math.random()
    const gx = '' + Math.random()
    const x = '' + Math.random()

    const f = x => x + fx
    const g = x => x + gx
    const h = compose(f, g)

    assert.strictEqual(f(g(x)), h(x))
  })
})

describe('apply', () => {
  it('apply(f, x) === f(x)', () => {
    const x = Math.random()
    const f = x => x + 1
    assert.strictEqual(apply(f, x), f(x))
  })
})

describe('curry2', () => {
  it('should return the original function if no args are given', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(curriedFn().length, 2)
  })

  it('should return a function of length 1 when 1 arg is given', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(curriedFn(1).length, 1)
  })

  it('should execute function when given 2 args', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(typeof curriedFn(1, 2).length, 'undefined')
    assert.strictEqual(curriedFn(1, 2), 3)
  })

  it('should be invariant', () => {
    const f = (x, y) => x + y
    const a = 1
    const b = 2

    const bool =
      curry2(f)(a)(b) === 3 &&
      curry2(f)(a, b) === 3 &&
      f(a, b) === 3

    assert.strictEqual(bool, true)
  })
})

describe('curry3', () => {
  it('should return the original function if no args are given', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(curriedFn().length, 3)
  })

  it('should return a function of length 2 when 1 arg is given', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(curriedFn(1).length, 2)
  })

  it('should return function of length 1 when given 2 args', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    const addOneTwo = curriedFn(1, 2)
    assert.strictEqual(addOneTwo.length, 1)
    assert.strictEqual(addOneTwo(3), 6)
  })

  it('should execute function when given 3 args', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(typeof curriedFn(1, 2, 3).length, 'undefined')
    assert.strictEqual(curriedFn(1, 2, 3), 6)
  })

  it('should be invariant', () => {
    const f = (x, y, z) => x + y + z
    const a = 1
    const b = 2
    const c = 3

    const bool =
      curry3(f)(a)(b)(c) === 6 &&
      curry3(f)(a, b)(c) === 6 &&
      curry3(f)(a)(b, c) === 6 &&
      curry3(f)(a, b, c) === 6 &&
      f(a, b, c) === 6

    assert.strictEqual(bool, true)
  })
})
<commit_msg>chore(): adjust invariant tests<commit_after>/** @license MIT License (c) copyright 2016 original author or authors */

import {describe, it} from 'mocha'
import assert from 'assert'

import { id, compose, apply, curry2, curry3 } from '../src/function'

describe('id', () => {
  it('id(x) === x', () => {
    const x = {}
    assert.strictEqual(id(x), x)
  })
})

describe('compose', () => {
  it('compose(f, g)(x) === f(g(x))', () => {
    const fx = '' + Math.random()
    const gx = '' + Math.random()
    const x = '' + Math.random()

    const f = x => x + fx
    const g = x => x + gx
    const h = compose(f, g)

    assert.strictEqual(f(g(x)), h(x))
  })
})

describe('apply', () => {
  it('apply(f, x) === f(x)', () => {
    const x = Math.random()
    const f = x => x + 1
    assert.strictEqual(apply(f, x), f(x))
  })
})

describe('curry2', () => {
  it('should return the original function if no args are given', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(curriedFn().length, 2)
  })

  it('should return a function of length 1 when 1 arg is given', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(curriedFn(1).length, 1)
  })

  it('should execute function when given 2 args', () => {
    const fn = (a, b) => a + b
    const curriedFn = curry2(fn)
    assert.strictEqual(typeof curriedFn(1, 2).length, 'undefined')
    assert.strictEqual(curriedFn(1, 2), 3)
  })

  it('should be invariant', () => {
    const f = (x, y) => x + y
    const a = 1
    const b = 2

    const expected = f(a, b)

    assert.strictEqual(expected, curry2(f)(a)(b))
    assert.strictEqual(expected, curry2(f)(a, b))
  })
})

describe('curry3', () => {
  it('should return the original function if no args are given', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(curriedFn().length, 3)
  })

  it('should return a function of length 2 when 1 arg is given', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(curriedFn(1).length, 2)
  })

  it('should return function of length 1 when given 2 args', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    const addOneTwo = curriedFn(1, 2)
    assert.strictEqual(addOneTwo.length, 1)
    assert.strictEqual(addOneTwo(3), 6)
  })

  it('should execute function when given 3 args', () => {
    const fn = (a, b, c) => a + b + c
    const curriedFn = curry3(fn)
    assert.strictEqual(typeof curriedFn(1, 2, 3).length, 'undefined')
    assert.strictEqual(curriedFn(1, 2, 3), 6)
  })

  it('should be invariant', () => {
    const f = (x, y, z) => x + y + z
    const a = 1
    const b = 2
    const c = 3

    const expected = f(a, b, c)

    assert.strictEqual(expected, curry3(f)(a)(b)(c))
    assert.strictEqual(expected, curry3(f)(a, b)(c))
    assert.strictEqual(expected, curry3(f)(a)(b, c))
    assert.strictEqual(expected, curry3(f)(a, b, c))
  })
})
<|endoftext|>