<commit_before>import { NativeModules, Platform } from 'react-native'
import processTheme from './utils/processTheme'
import checkArgs from './utils/checkArgs'
import checkInit from './utils/checkInit'
import * as types from './utils/types'
import errorCodes from './errorCodes'
import deprecatedMethodsForInstance from './Stripe.deprecated'
/**
 * @typedef {Object} PaymentMethodAddress
 * @property {string} city
 * @property {string} country
 * @property {string} line1
 * @property {string} line2
 * @property {string} postalCode
 * @property {string} state
 */

/**
 * @typedef {Object} BillingDetails
 * @property {PaymentMethodAddress} address
 * @property {string} email
 * @property {string} name
 * @property {string} phone
 */

/**
 * @typedef {Object} PaymentMethod
 * @property {string} id
 * @property {number} created
 * @property {boolean} livemode
 * @property {string} type
 * @property {BillingDetails} billingDetails
 * @property {string} customerId
 */

/* eslint-disable max-len */
/**
 * https://stripe.com/docs/api/payment_intents/object#payment_intent_object-status
 * @typedef {('unknown'|'canceled'|'processing'|'requires_action'|'requires_capture'|'requires_payment_method'|'requires_confirmation'|'succeeded')} StripePaymentIntentStatus
 */

/**
 * https://stripe.com/docs/api/setup_intents/object#setup_intent_object-status
 * @typedef {('unknown'|'canceled'|'processing'|'requires_action'|'requires_payment_method'|'requires_confirmation'|'succeeded')} StripeSetupIntentStatus
 */
/* eslint-enable max-len */

/**
 * @typedef {Object} PaymentMethodParamsCardByToken
 * @property {string} token - Token String
 */

/**
 * @typedef {Object} CreatePaymentMethodParams
 * @property {string} id
 * @property {BillingDetails} billingDetails
 * @property {(PaymentMethodCardParams|PaymentMethodParamsCardByToken)} card - the Parameters to build a card
 * @property {Object} metadata
 * @property {string} customerId
 */

/**
 * @typedef {Object} ConfirmPaymentIntentParams
 * @property {string} clientSecret
 * @property {CreatePaymentMethodParams} paymentMethod
 * @property {string} paymentMethodId
 * @property {string} sourceId
 * @property {string} returnURL
 * @property {boolean} savePaymentMethod
 */

/**
 * @typedef {Object} PaymentIntentConfirmationResult
 * @property {StripePaymentIntentStatus} status
 * @property {string} paymentIntentId
 */

/**
 * @typedef {Object} AuthenticatePaymentIntentParams
 * @property {string} clientSecret
 */

/**
 * @typedef {Object} PaymentIntentAuthenticationResult
 * @property {StripePaymentIntentStatus} status
 * @property {string} paymentIntentId
 */

/**
 * @typedef {Object} ConfirmSetupIntentParams
 * @property {string} clientSecret
 * @property {CreatePaymentMethodParams} paymentMethod
 * @property {string} paymentMethodId
 * @property {string} returnURL
 */

/**
 * @typedef {Object} SetupIntentConfirmationResult
 * @property {StripeSetupIntentStatus} status
 * @property {string} setupIntentId
 */

/**
 * @typedef {Object} AuthenticateSetupIntentParams
 * @property {string} clientSecret
 */

/**
 * @typedef {Object} SetupIntentAuthenticationResult
 * @property {StripeSetupIntentStatus} status
 * @property {string} setupIntentId
 */

const { StripeModule } = NativeModules

class Stripe {
  stripeInitialized = false

  constructor() {
    // Mix in the deprecated methods
    Object.assign(this, deprecatedMethodsForInstance(this))
  }
  /**
   * @param options: {StripeOptions}
   * @returns {void}
   */
  setOptions = (options = {}) => {
    checkArgs(types.setOptionsOptionsPropTypes, options, 'options', 'Stripe.setOptions')

    this.stripeInitialized = true

    return StripeModule.init(options, errorCodes)
  }

  /**
   * @returns {Promise<boolean>}
   */
  deviceSupportsNativePay = () =>
    Platform.select({
      ios: () => this.deviceSupportsApplePay(),
      android: () => this.deviceSupportsAndroidPay(),
    })()

  // iOS requires networks array while Android requires nothing
  canMakeNativePayPayments = (options = {}) =>
    Platform.select({
      ios: () => this.canMakeApplePayPayments(options),
      android: () => this.canMakeAndroidPayPayments(),
    })()

  potentiallyAvailableNativePayNetworks = () =>
    Platform.select({
      ios: () => StripeModule.potentiallyAvailableNativePayNetworks(),
      // Android doesn't expose this information, so resolve empty array
      android: async () => {
        const canNativePay = await this.canMakeAndroidPayPayments()
        return canNativePay ? [] : null
      },
    })()

  paymentRequestWithNativePay(options = {}, items = []) {
    return Platform.select({
      ios: () => this.paymentRequestWithApplePay(items, options),
      android: () => this.paymentRequestWithAndroidPay(options),
    })()
  }

  // no corresponding android impl exists
  completeNativePayRequest = () =>
    Platform.select({
      ios: () => this.completeApplePayRequest(),
      android: () => Promise.resolve(),
    })()

  // no corresponding android impl exists
  cancelNativePayRequest = () =>
    Platform.select({
      ios: () => this.cancelApplePayRequest(),
      android: () => Promise.resolve(),
    })()

  // no corresponding android impl exists
  openNativePaySetup = () =>
    Platform.select({
      ios: () => this.openApplePaySetup(),
      android: () => Promise.resolve(),
    })()

  paymentRequestWithCardForm = (options = {}) => {
    checkInit(this)
    checkArgs(
      types.paymentRequestWithCardFormOptionsPropTypes,
      options,
      'options',
      'Stripe.paymentRequestWithCardForm'
    )
    return StripeModule.paymentRequestWithCardForm({
      ...options,
      theme: processTheme(options.theme),
    })
  }

  createTokenWithCard = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createTokenWithCardParamsPropTypes,
      params,
      'params',
      'Stripe.createTokenWithCard'
    )
    return StripeModule.createTokenWithCard(params)
  }

  createTokenWithBankAccount = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createTokenWithBankAccountParamsPropTypes,
      params,
      'params',
      'Stripe.createTokenWithBankAccount'
    )
    return StripeModule.createTokenWithBankAccount(params)
  }

  createSourceWithParams = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createSourceWithParamsPropType,
      params,
      'params',
      'Stripe.createSourceWithParams'
    )
    return StripeModule.createSourceWithParams(params)
  }

  /**
   * After calling this, you need to hit your backend with this method to get a clientSecret
   * @param {CreatePaymentMethodParams} params
   * @returns {Promise<PaymentMethod>}
   */
  createPaymentMethod = (params = {}) => {
    checkInit(this)
    checkArgs(types.createPaymentMethodPropType, params, 'params', 'Stripe.createPaymentMethod')
    return StripeModule.createPaymentMethod(params)
  }

  /**
   * Takes a previously created paymentMethodId or a new paymentMethod, and then generates a paymentIntent
   * @param {ConfirmPaymentIntentParams} params
   * @returns {Promise<PaymentIntentConfirmationResult>}
   */
  confirmPaymentIntent = (params = {}) => {
    checkInit(this)
    checkArgs(types.confirmPaymentIntentPropType, params, 'params', 'Stripe.confirmPaymentIntent')
    return StripeModule.confirmPaymentIntent(params)
  }

  /**
   * @param {AuthenticatePaymentIntentParams} params
   * @returns {Promise<PaymentIntentAuthenticationResult>}
   */
  authenticatePaymentIntent = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.authenticatePaymentIntentPropType,
      params,
      'params',
      'Stripe.authenticatePaymentIntent'
    )
    return StripeModule.authenticatePaymentIntent(params)
  }

  /**
   * @param {ConfirmSetupIntentParams} params
   * @returns {Promise<SetupIntentConfirmationResult>}
   */
  confirmSetupIntent = (params = {}) => {
    checkInit(this)
    checkArgs(types.confirmSetupIntentPropType, params, 'params', 'Stripe.confirmSetupIntent')
    return StripeModule.confirmSetupIntent(params)
  }

  /**
   * Displays 3DSecure2 or other flows to authenticate a SetupIntent
   * @param {AuthenticateSetupIntentParams} params
   * @returns {Promise<SetupIntentAuthenticationResult>}
   */
  /*

  DISABLED FOR NOW - you should be able to use confirmSetupIntent
  Will re-add if needed.

  authenticateSetupIntent = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.authenticateSetupIntentPropType,
      params,
      'params',
      'Stripe.authenticateSetupIntent'
    )
    return StripeModule.authenticateSetupIntent(params)
  }
  */
}

export default new Stripe()
<commit_msg>Fix JSDocs around PaymentMethod customerId<commit_after>import { NativeModules, Platform } from 'react-native'
import processTheme from './utils/processTheme'
import checkArgs from './utils/checkArgs'
import checkInit from './utils/checkInit'
import * as types from './utils/types'
import errorCodes from './errorCodes'
import deprecatedMethodsForInstance from './Stripe.deprecated'
/**
 * @typedef {Object} PaymentMethodAddress
 * @property {string} city
 * @property {string} country
 * @property {string} line1
 * @property {string} line2
 * @property {string} postalCode
 * @property {string} state
 */

/**
 * @typedef {Object} BillingDetails
 * @property {PaymentMethodAddress} address
 * @property {string} email
 * @property {string} name
 * @property {string} phone
 */

/**
 * @typedef {Object} PaymentMethod
 * @property {string} id
 * @property {number} created
 * @property {boolean} livemode
 * @property {string} type
 * @property {BillingDetails} billingDetails
 * @property {string} customerId to set this, you must attach the PaymentMethod to a customer on your backend
 */

/* eslint-disable max-len */
/**
 * https://stripe.com/docs/api/payment_intents/object#payment_intent_object-status
 * @typedef {('unknown'|'canceled'|'processing'|'requires_action'|'requires_capture'|'requires_payment_method'|'requires_confirmation'|'succeeded')} StripePaymentIntentStatus
 */

/**
 * https://stripe.com/docs/api/setup_intents/object#setup_intent_object-status
 * @typedef {('unknown'|'canceled'|'processing'|'requires_action'|'requires_payment_method'|'requires_confirmation'|'succeeded')} StripeSetupIntentStatus
 */
/* eslint-enable max-len */

/**
 * @typedef {Object} PaymentMethodParamsCardByToken
 * @property {string} token - Token String
 */

/**
 * @typedef {Object} CreatePaymentMethodParams
 * @property {string} id
 * @property {BillingDetails} billingDetails
 * @property {(PaymentMethodCardParams|PaymentMethodParamsCardByToken)} card - the Parameters to build a card
 * @property {Object} metadata
 */

/**
 * @typedef {Object} ConfirmPaymentIntentParams
 * @property {string} clientSecret
 * @property {CreatePaymentMethodParams} paymentMethod
 * @property {string} paymentMethodId
 * @property {string} sourceId
 * @property {string} returnURL
 * @property {boolean} savePaymentMethod
 */

/**
 * @typedef {Object} PaymentIntentConfirmationResult
 * @property {StripePaymentIntentStatus} status
 * @property {string} paymentIntentId
 */

/**
 * @typedef {Object} AuthenticatePaymentIntentParams
 * @property {string} clientSecret
 */

/**
 * @typedef {Object} PaymentIntentAuthenticationResult
 * @property {StripePaymentIntentStatus} status
 * @property {string} paymentIntentId
 */

/**
 * @typedef {Object} ConfirmSetupIntentParams
 * @property {string} clientSecret
 * @property {CreatePaymentMethodParams} paymentMethod
 * @property {string} paymentMethodId
 * @property {string} returnURL
 */

/**
 * @typedef {Object} SetupIntentConfirmationResult
 * @property {StripeSetupIntentStatus} status
 * @property {string} setupIntentId
 */

/**
 * @typedef {Object} AuthenticateSetupIntentParams
 * @property {string} clientSecret
 */

/**
 * @typedef {Object} SetupIntentAuthenticationResult
 * @property {StripeSetupIntentStatus} status
 * @property {string} setupIntentId
 */

const { StripeModule } = NativeModules

class Stripe {
  stripeInitialized = false

  constructor() {
    // Mix in the deprecated methods
    Object.assign(this, deprecatedMethodsForInstance(this))
  }
  /**
   * @param options: {StripeOptions}
   * @returns {void}
   */
  setOptions = (options = {}) => {
    checkArgs(types.setOptionsOptionsPropTypes, options, 'options', 'Stripe.setOptions')

    this.stripeInitialized = true

    return StripeModule.init(options, errorCodes)
  }

  /**
   * @returns {Promise<boolean>}
   */
  deviceSupportsNativePay = () =>
    Platform.select({
      ios: () => this.deviceSupportsApplePay(),
      android: () => this.deviceSupportsAndroidPay(),
    })()

  // iOS requires networks array while Android requires nothing
  canMakeNativePayPayments = (options = {}) =>
    Platform.select({
      ios: () => this.canMakeApplePayPayments(options),
      android: () => this.canMakeAndroidPayPayments(),
    })()

  potentiallyAvailableNativePayNetworks = () =>
    Platform.select({
      ios: () => StripeModule.potentiallyAvailableNativePayNetworks(),
      // Android doesn't expose this information, so resolve empty array
      android: async () => {
        const canNativePay = await this.canMakeAndroidPayPayments()
        return canNativePay ? [] : null
      },
    })()

  paymentRequestWithNativePay(options = {}, items = []) {
    return Platform.select({
      ios: () => this.paymentRequestWithApplePay(items, options),
      android: () => this.paymentRequestWithAndroidPay(options),
    })()
  }

  // no corresponding android impl exists
  completeNativePayRequest = () =>
    Platform.select({
      ios: () => this.completeApplePayRequest(),
      android: () => Promise.resolve(),
    })()

  // no corresponding android impl exists
  cancelNativePayRequest = () =>
    Platform.select({
      ios: () => this.cancelApplePayRequest(),
      android: () => Promise.resolve(),
    })()

  // no corresponding android impl exists
  openNativePaySetup = () =>
    Platform.select({
      ios: () => this.openApplePaySetup(),
      android: () => Promise.resolve(),
    })()

  paymentRequestWithCardForm = (options = {}) => {
    checkInit(this)
    checkArgs(
      types.paymentRequestWithCardFormOptionsPropTypes,
      options,
      'options',
      'Stripe.paymentRequestWithCardForm'
    )
    return StripeModule.paymentRequestWithCardForm({
      ...options,
      theme: processTheme(options.theme),
    })
  }

  createTokenWithCard = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createTokenWithCardParamsPropTypes,
      params,
      'params',
      'Stripe.createTokenWithCard'
    )
    return StripeModule.createTokenWithCard(params)
  }

  createTokenWithBankAccount = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createTokenWithBankAccountParamsPropTypes,
      params,
      'params',
      'Stripe.createTokenWithBankAccount'
    )
    return StripeModule.createTokenWithBankAccount(params)
  }

  createSourceWithParams = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.createSourceWithParamsPropType,
      params,
      'params',
      'Stripe.createSourceWithParams'
    )
    return StripeModule.createSourceWithParams(params)
  }

  /**
   * After calling this, you need to hit your backend with this method to get a clientSecret
   * @param {CreatePaymentMethodParams} params
   * @returns {Promise<PaymentMethod>}
   */
  createPaymentMethod = (params = {}) => {
    checkInit(this)
    checkArgs(types.createPaymentMethodPropType, params, 'params', 'Stripe.createPaymentMethod')
    return StripeModule.createPaymentMethod(params)
  }

  /**
   * Takes a previously created paymentMethodId or a new paymentMethod, and then generates a paymentIntent
   * @param {ConfirmPaymentIntentParams} params
   * @returns {Promise<PaymentIntentConfirmationResult>}
   */
  confirmPaymentIntent = (params = {}) => {
    checkInit(this)
    checkArgs(types.confirmPaymentIntentPropType, params, 'params', 'Stripe.confirmPaymentIntent')
    return StripeModule.confirmPaymentIntent(params)
  }

  /**
   * @param {AuthenticatePaymentIntentParams} params
   * @returns {Promise<PaymentIntentAuthenticationResult>}
   */
  authenticatePaymentIntent = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.authenticatePaymentIntentPropType,
      params,
      'params',
      'Stripe.authenticatePaymentIntent'
    )
    return StripeModule.authenticatePaymentIntent(params)
  }

  /**
   * @param {ConfirmSetupIntentParams} params
   * @returns {Promise<SetupIntentConfirmationResult>}
   */
  confirmSetupIntent = (params = {}) => {
    checkInit(this)
    checkArgs(types.confirmSetupIntentPropType, params, 'params', 'Stripe.confirmSetupIntent')
    return StripeModule.confirmSetupIntent(params)
  }

  /**
   * Displays 3DSecure2 or other flows to authenticate a SetupIntent
   * @param {AuthenticateSetupIntentParams} params
   * @returns {Promise<SetupIntentAuthenticationResult>}
   */
  /*

  DISABLED FOR NOW - you should be able to use confirmSetupIntent
  Will re-add if needed.

  authenticateSetupIntent = (params = {}) => {
    checkInit(this)
    checkArgs(
      types.authenticateSetupIntentPropType,
      params,
      'params',
      'Stripe.authenticateSetupIntent'
    )
    return StripeModule.authenticateSetupIntent(params)
  }
  */
}

export default new Stripe()
<|endoftext|>


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

    /** Home view controller */
    angular.module('app')
        .controller('HomeController', ['$scope', function ($scope) {

            $scope.message = "Welcome in our shop!!!";

        }]);
})();<commit_msg>Update HomeController in order to use NewsService<commit_after>(function () {
    "use strict";

    /** Home view controller */
    angular.module('app')
        .controller('HomeController', ['$scope','NewsService', function ($scope,NewsService) {

            $scope.message = "Welcome in our shop!!!";

            /** Gets all the news. */
            $scope.lstNews = NewsService.query();

            /** Gets the news with id = 1. */
            $scope.currentNews = NewsService.get({ id: 1 });
            $scope.newsOfTheDay = NewsService.random();

            /** Creates a new news. */
            $scope.addedNews = new NewsService();

            /** Increments the number of likes of a news, and saves the changes. */
            $scope.addLike = function(news) {
                news.$like();
            };

            /** Deletes a news. */
            $scope.deleteNews = function(news) {
                news.$delete(function(){
                    $scope.lstNews.splice($scope.lstNews.indexOf(news),1);
                });

            };

            /** Adds a news. */
            $scope.addNews = function() {
                $scope.addedNews.$save(function(){
                    $scope.lstNews.push($scope.addedNews);
                    $scope.addedNews = new NewsService();
                });

            };
        }]);
})();<|endoftext|>


<commit_before>/*global angular, NGS */
/**
 * User:    Josh Adam <josh.adam@phac-aspc.gc.ca>
 * Date:    2013-06-04
 * Time:    9:51 AM
 * License: MIT
 */

(function (ng, app) {
    'use strict';

    /**
     * AngularJS Controller for the Projects List Sidebar
     *
     * @method ProjectsListCtrl
     * @param {Object} $scope
     * @param {Object} ajaxService
     * @param {Object} $location
     */
    app.controller('ProjectsListCtrl', ['$rootScope', '$scope', 'ajaxService', '$location', '$dialog', function ($rootScope, $scope, ajaxService, $location, $dialog) {

        var active = '';

        $scope.$on('PROJECT_CREATED', function (event, msg) {
           $scope.projects.unshift(msg);
            $rootScope.$broadcast('NOTIFY', {msg:msg.name + " created."});
        });

        // DOM
//        var DOM_TOP_BOTTOM = $('#sidebar-top').height();
//        var DOM_BOTTOM_TOP = $('#sidebar-bottom').offset().top;
//        var DOM_SIDEBAR_INNER = $('.sidebar-inner');

//        $document.keydown(function (e) {
//                if (e.which === 40) {
//                    e.preventDefault();
//                    if (active) {
//                        var next = active.next();
//                        if (next.length > 0) {
//                            active.removeClass('active');
//                            active = next.addClass('active');
//                            var diff = DOM_BOTTOM_TOP - (active.offset().top + active.outerHeight());
//                            if (diff < 0) {
//                                DOM_SIDEBAR_INNER.scrollTop(DOM_SIDEBAR_INNER.scrollTop() - diff);
//                            }
//                        }
//                    }
//                }
//                else if (e.which === 38) {
//                    e.preventDefault();
//                    if (active) {
//                        var prev = active.prev();
//                        if (prev.length > 0) {
//                            active.removeClass('active');
//                            active = prev.addClass('active');
//                            var diff = active.offset().top - DOM_TOP_BOTTOM;
//                            if (diff < 0) {
//                                DOM_SIDEBAR_INNER.scrollTop(DOM_SIDEBAR_INNER.scrollTop() + diff);
//                            }
//                        }
//                    }
//                }
//        });

        ajaxService.get('/api/projects/all').then(function (data) {
            $scope.projects = data.resource.resources;
        });

        /**
         * Loads the selected project into the ui-view section.
         *
         * @method $scope.gotoProject
         * @param {Object} e - the event that triggered the call
         * @param {String} uri - the uri for the project.
         */
        $scope.gotoProject = function (e, uri) {
            if (active) {
                active.removeClass('active');
            }
            active = $(e.currentTarget);
            active.addClass('active');
            $location.path(uri.match(/\/projects\/.*$/)[0] + "/samples");
        };

        /**
         * New Project Stuff
         */

        var t = '
' +
            '
Create New Project
' +
            '
' +
            '
' +
            '
Project Name: <input ng-model="project.name" />
' +
            '
' +
            '
' +
            '<button ng-click="createProject()" class="btn btn-primary" >Create</button>' +
            '
';

        $scope.projectModal = {
            openDialog: function () {
                var d = $dialog.dialog(this.opts);
                d.open();
            },
            opts: {
                backdrop: true,
                keyboard: true,
                backdropClick: true,
                template: t,
                controller: 'NewProjectCtrl'
            }
        };
    }]);

    app.controller('NewProjectCtrl', function ($rootScope, $scope, dialog, ajaxService) {
        $scope.project = {
            name: ''
        };
        $scope.createProject = function () {
            dialog.close();
            ajaxService.create('/api/projects', {name:$scope.project.name}).then(function (data) {
                $rootScope.$broadcast('PROJECT_CREATED', {name:$scope.project.name});
            });
        };
    });
})(angular, NGS);
<commit_msg>When a new project is created, a new project is added to the projects list and therefore updates the sidebar.<commit_after>/*global angular, NGS */
/**
 * User:    Josh Adam <josh.adam@phac-aspc.gc.ca>
 * Date:    2013-06-04
 * Time:    9:51 AM
 * License: MIT
 */

(function (ng, app) {
    'use strict';

    /**
     * AngularJS Controller for the Projects List Sidebar
     *
     * @method ProjectsListCtrl
     * @param {Object} $scope
     * @param {Object} ajaxService
     * @param {Object} $location
     */
    app.controller('ProjectsListCtrl', ['$rootScope', '$scope', 'ajaxService', '$location', '$dialog', function ($rootScope, $scope, ajaxService, $location, $dialog) {

        var active = '';

        $scope.$on('PROJECT_CREATED', function (event, msg) {
           $scope.projects.unshift(msg);
            $rootScope.$broadcast('NOTIFY', {msg:msg.name + " created."});
        });

        // DOM
//        var DOM_TOP_BOTTOM = $('#sidebar-top').height();
//        var DOM_BOTTOM_TOP = $('#sidebar-bottom').offset().top;
//        var DOM_SIDEBAR_INNER = $('.sidebar-inner');

//        $document.keydown(function (e) {
//                if (e.which === 40) {
//                    e.preventDefault();
//                    if (active) {
//                        var next = active.next();
//                        if (next.length > 0) {
//                            active.removeClass('active');
//                            active = next.addClass('active');
//                            var diff = DOM_BOTTOM_TOP - (active.offset().top + active.outerHeight());
//                            if (diff < 0) {
//                                DOM_SIDEBAR_INNER.scrollTop(DOM_SIDEBAR_INNER.scrollTop() - diff);
//                            }
//                        }
//                    }
//                }
//                else if (e.which === 38) {
//                    e.preventDefault();
//                    if (active) {
//                        var prev = active.prev();
//                        if (prev.length > 0) {
//                            active.removeClass('active');
//                            active = prev.addClass('active');
//                            var diff = active.offset().top - DOM_TOP_BOTTOM;
//                            if (diff < 0) {
//                                DOM_SIDEBAR_INNER.scrollTop(DOM_SIDEBAR_INNER.scrollTop() + diff);
//                            }
//                        }
//                    }
//                }
//        });

        ajaxService.get('/api/projects/all').then(function (data) {
            $scope.projects = data.resource.resources;
        });

        /**
         * Loads the selected project into the ui-view section.
         *
         * @method $scope.gotoProject
         * @param {Object} e - the event that triggered the call
         * @param {String} uri - the uri for the project.
         */
        $scope.gotoProject = function (e, uri) {
            if (active) {
                active.removeClass('active');
            }
            active = $(e.currentTarget);
            active.addClass('active');
            $location.path(uri.match(/\/projects\/.*$/)[0] + "/samples");
        };

        /**
         * New Project Stuff
         */

        var t = '
' +
            '
Create New Project
' +
            '
' +
            '
' +
            '
Project Name: <input ng-model="project.name" />
' +
            '
' +
            '
' +
            '<button ng-click="createProject()" class="btn btn-primary" >Create</button>' +
            '
';

        $scope.projectModal = {
            openDialog: function () {
                var d = $dialog.dialog(this.opts);
                d.open();
            },
            opts: {
                backdrop: true,
                keyboard: true,
                backdropClick: true,
                template: t,
                controller: 'NewProjectCtrl'
            }
        };
    }]);

    app.controller('NewProjectCtrl', function ($rootScope, $scope, dialog, ajaxService) {
        $scope.project = {
            name: ''
        };
        $scope.createProject = function () {
            dialog.close();
            ajaxService.create('/api/projects', {name:$scope.project.name}).then(function (uri) {
                var msg = {
                    name: $scope.project.name,
                    links: {
                        self: uri
                    }
                };
                $rootScope.$broadcast('PROJECT_CREATED', msg);
            });
        };
    });
})(angular, NGS);
<|endoftext|>


<commit_before>/* ==========================================================
 * bc-bootstrap-collection.js
 * http://bootstrap.braincrafted.com
 * ==========================================================
 * Copyright 2013 Florian Eckerstorfer
 *
 * ========================================================== */

!function ($) {

    "use strict"; // jshint ;_;

    /* COLLECTION CLASS DEFINITION
     * ====================== */

    var addField = '[data-addfield="collection"]',
        removeField = '[data-removefield="collection"]',
        CollectionAdd = function (el) {
            $(el).on('click', addField, this.addField);
        },
        CollectionRemove = function (el) {
            $(el).on('click', removeField, this.removeField);
        }
    ;

    CollectionAdd.prototype.addField = function (e) {
        var $this = $(this),
            selector = $this.attr('data-collection'),
            $parent
        ;

        $parent = $(selector);

        e && e.preventDefault();

        var collection = $('#'+selector),
            list = collection.find('ul'),
            count = list.find('li').size()
        ;

        var newWidget = collection.attr('data-prototype');

        // Check if an element with this ID already exists.
        // If it does, increase the count by one and try again
        var newName = newWidget.match(/id="(.*?)"/);
        while ($('#' + newName[1].replace(/__name__/g, count)).size() > 0) {
            count++;
        }
        newWidget = newWidget.replace(/__name__/g, count);
        newWidget = newWidget.replace(/__id__/g, newName[1].replace(/__name__/g, count));
        var newLi = $('

').html(newWidget);
        newLi.appendTo(list);
    };

    CollectionRemove.prototype.removeField = function (e) {
        var $this = $(this),
            selector = $this.attr('data-field'),
            $parent
        ;

        $parent = $(selector);

        e && e.preventDefault();

        var listElement = $this.closest('li').remove();
    }

    /* COLLECTION PLUGIN DEFINITION
     * ======================= */

    var oldAdd = $.fn.addField;
    var oldRemove = $.fn.removeField;

    $.fn.addField = function (option) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('addfield')
            ;
            if (!data) {
                $this.data('addfield', (data = new CollectionAdd(this)));
            }
            if (typeof option == 'string') {
                data[option].call($this);
            }
        });
    };

    $.fn.removeField = function (option) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('removefield')
            ;
            if (!data) {
                $this.data('removefield', (data = new CollectionRemove(this)));
            }
            if (typeof option == 'string') {
                data[option].call($this);
            }
        });
    };

    $.fn.addField.Constructor = CollectionAdd;
    $.fn.removeField.Constructor = CollectionRemove;

    /* COLLECTION NO CONFLICT
     * ================= */

    $.fn.addField.noConflict = function () {
        $.fn.addField = oldAdd;
        return this;
    }
    $.fn.removeField.noConflict = function () {
        $.fn.removeField = oldRemove;
        return this;
    }

    /* COLLECTION DATA-API
     * ============== */

    $(document).on('click.addfield.data-api', addField, CollectionAdd.prototype.addField);
    $(document).on('click.removefield.data-api', removeField, CollectionRemove.prototype.removeField);

 }(window.jQuery);<commit_msg>JavaScript handles nested bootstrap_collection form types<commit_after>/* ==========================================================
 * bc-bootstrap-collection.js
 * http://bootstrap.braincrafted.com
 * ==========================================================
 * Copyright 2013 Florian Eckerstorfer
 *
 * ========================================================== */

!function ($) {

    "use strict"; // jshint ;_;

    /* COLLECTION CLASS DEFINITION
     * ====================== */

    var addField = '[data-addfield="collection"]',
        removeField = '[data-removefield="collection"]',
        CollectionAdd = function (el) {
            $(el).on('click', addField, this.addField);
        },
        CollectionRemove = function (el) {
            $(el).on('click', removeField, this.removeField);
        }
    ;

    CollectionAdd.prototype.addField = function (e) {
        var $this = $(this),
            selector = $this.attr('data-collection')
        ;

        e && e.preventDefault();

        var collection = $('#'+selector),
            list = collection.find('> ul'),
            count = list.find('li').size()
        ;

        var newWidget = collection.attr('data-prototype');

        // Check if an element with this ID already exists.
        // If it does, increase the count by one and try again
        var newName = newWidget.match(/id="(.*?)"/);
        while ($('#' + newName[1].replace(/__name__/g, count)).size() > 0) {
            count++;
        }
        newWidget = newWidget.replace(/__name__/g, count);
        newWidget = newWidget.replace(/__id__/g, newName[1].replace(/__name__/g, count));
        var newLi = $('

').html(newWidget);
        newLi.appendTo(list);
    };

    CollectionRemove.prototype.removeField = function (e) {
        var $this = $(this),
            selector = $this.attr('data-field')
        ;

        e && e.preventDefault();

        var listElement = $this.closest('li').remove();
    }

    /* COLLECTION PLUGIN DEFINITION
     * ======================= */

    var oldAdd = $.fn.addField;
    var oldRemove = $.fn.removeField;

    $.fn.addField = function (option) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('addfield')
            ;
            if (!data) {
                $this.data('addfield', (data = new CollectionAdd(this)));
            }
            if (typeof option == 'string') {
                data[option].call($this);
            }
        });
    };

    $.fn.removeField = function (option) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('removefield')
            ;
            if (!data) {
                $this.data('removefield', (data = new CollectionRemove(this)));
            }
            if (typeof option == 'string') {
                data[option].call($this);
            }
        });
    };

    $.fn.addField.Constructor = CollectionAdd;
    $.fn.removeField.Constructor = CollectionRemove;

    /* COLLECTION NO CONFLICT
     * ================= */

    $.fn.addField.noConflict = function () {
        $.fn.addField = oldAdd;
        return this;
    }
    $.fn.removeField.noConflict = function () {
        $.fn.removeField = oldRemove;
        return this;
    }

    /* COLLECTION DATA-API
     * ============== */

    $(document).on('click.addfield.data-api', addField, CollectionAdd.prototype.addField);
    $(document).on('click.removefield.data-api', removeField, CollectionRemove.prototype.removeField);

 }(window.jQuery);<|endoftext|>


<commit_before>function queryDataMining(p_data, p_callback = null) {
	var v_state = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.state;

	if(v_state != v_queryState.Idle) {
		showAlert('Tab with activity in progress.');
	}
	else {
		var v_tab_tag = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag;
		v_tab_tag.queryTabControl.tabList[0].elementDiv.innerHTML = '';
		var v_db_index  = v_connTabControl.selectedTab.tag.selectedDatabaseIndex;
		var v_tab_loading_span = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_loading_span;
		var v_tab_close_span = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_close_span;

		//Change to run mode if database index changed
		if(v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex == null || v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex != v_connTabControl.selectedTab.tag.selectedDatabaseIndex) {
			v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex = v_connTabControl.selectedTab.tag.selectedDatabaseIndex;
		}

		var v_message_data = {
			v_sql_cmd : '',
			v_db_index: v_db_index,
			v_conn_tab_id: v_connTabControl.selectedTab.id,
			v_tab_id: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_id,
			v_tab_db_id: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_db_id,
            text: p_data.text,
            regex: p_data.regex,
            caseSensitive: p_data.caseSensitive,
            categoryList: p_data.categoryList,
            schemaList: p_data.schemaList
		};

		v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.state = v_queryState.Executing;

		var start_time = new Date().getTime();

		var d = new Date,
        dformat = [(d.getMonth()+1).padLeft(),
                   d.getDate().padLeft(),
                   d.getFullYear()].join('/') +' ' +
                  [d.getHours().padLeft(),
                   d.getMinutes().padLeft(),
                   d.getSeconds().padLeft()].join(':');

		v_tab_tag.tab_loading_span.style.display = '';
		v_tab_tag.tab_stub_span.style.display = 'none';
		v_tab_tag.bt_cancel.style.display = '';

		var v_context = {
			tab_tag: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag,
			start_time: new Date().getTime(),
			start_datetime: dformat,
			database_index: v_connTabControl.selectedTab.tag.selectedDatabaseIndex,
			callback: p_callback,
			acked: false,
            mode: 0
		}

		v_context.tab_tag.context = v_context;

		if (p_callback==null) {
			if (v_context.tab_tag.ht!=null) {
				v_context.tab_tag.ht.destroy();
				v_context.tab_tag.ht = null;
			}

			v_context.tab_tag.div_result.innerHTML = '';
		}

		v_context.tab_tag.query_info.innerHTML = 'Start time: ' + dformat + '
Running...';

		sendWebSocketMessage(v_queryWebSocket, v_queryRequestCodes.DataMining, v_message_data, false, v_context);

		setTimeout(function() {
			if (!v_context.acked) {
				cancelSQLTab(v_context.tab_tag);
				showAlert('No response from query server.');
			}
		},20000);
	}
}

function checkDataMiningStatus(p_tab) {
	if(p_tab.tag.state == v_queryState.Ready) {
		dataMiningReturnRender(p_tab.tag.data, p_tab.tag.context);
	}
}

function dataMiningReturn(p_message, p_context) {
	//If data mining wasn't canceled already
	if(p_context.tab_tag.state!=v_queryState.Idle) {

		if(p_context.tab_tag.tab_id == p_context.tab_tag.tabControl.selectedTab.id && p_context.tab_tag.connTab.id == p_context.tab_tag.connTab.tag.connTabControl.selectedTab.id) {
			dataMiningReturnRender(p_message, p_context);
		}
		else {
			p_context.tab_tag.state = v_queryState.Ready;
			p_context.tab_tag.context = p_context;
			p_context.tab_tag.data = p_message;

			p_context.tab_tag.tab_loading_span.style.display = 'none';
			p_context.tab_tag.tab_check_span.style.display = '';
		}
	}
}

function dataMiningReturnRender(p_message, p_context) {
	p_context.tab_tag.state = v_queryState.Idle;
	p_context.tab_tag.context = null;
	p_context.tab_tag.data = null;

	var v_div_result = p_context.tab_tag.div_result;
	var v_query_info = p_context.tab_tag.query_info;

	if(p_message.v_error) {
		v_div_result.innerHTML = '
' + p_message.v_data.message + '
';
		v_query_info.innerHTML = "Start time: " + p_context.start_datetime + " Duration: " + p_message.v_data.v_duration;
	}
	else {
		v_query_info.innerHTML = "Start time: " + p_context.start_datetime + " Duration: " + p_message.v_data.v_duration;
		v_div_result.innerHTML = '
Done.
';

		var v_context_menu = {
	        'cm_see_details': {
	            elements: [{
	                text: 'See More',
	                icon: '/static/OmniDB_app/images/explain.png',
	                action: function(p_node) {
						tabSQLTemplate('Data Mining - ' + p_node.tag.key, p_node.tag.sql, false);
	                }
	            }]
	        }
		};

		var v_tree = createTree(p_context.tab_tag.queryTabControl.tabList[0].elementDiv.id, '#fcfdfd', v_context_menu);

		for(v_key in p_message.v_data.v_result) {
			if(v_key == 'Data') {
				var v_count = 0;

				var v_node = v_tree.createNode(
					v_key,
					false,
					'/static/OmniDB_app/images/data_mining.png',
					null,
					p_message.v_data.v_result[v_key],
					null
				);

				v_node.tag.key = v_key;

				for(v_key2 in p_message.v_data.v_result[v_key]) {
					if(p_message.v_data.v_result[v_key][v_key2].count > 0) {
						var v_matches = '';
						v_count += p_message.v_data.v_result[v_key][v_key2].count;

						switch(p_message.v_data.v_result[v_key][v_key2].count) {
							case 1: {
								v_matches = '(1 match)';
								break;
							}
							default: {
								v_matches = '(' + p_message.v_data.v_result[v_key][v_key2].count + ' matches)';
								break;
							}
						}

						var v_childNode = v_node.createChildNode(
							v_key2 + ' ' + v_matches,
							false,
							'/static/OmniDB_app/images/data_mining.png',
							p_message.v_data.v_result[v_key][v_key2],
							'cm_see_details'
						);

						v_childNode.tag.key = v_key2;
					}
				}

				var v_dataMatches = '';

				switch(v_count) {
					case 0: {
						v_dataMatches = '(No match)';
						break;
					}
					case 1: {
						v_dataMatches = '(1 match)';
						break;
					}
					default: {
						v_dataMatches = '(' + v_count + ' matches)';
						break;
					}
				}

				v_node.text = v_key + ' ' + v_dataMatches;
			}
			else {
				var v_matches = '';

				switch(p_message.v_data.v_result[v_key].count) {
					case 0: {
						v_matches = '(No match)';
						break;
					}
					case 1: {
						v_matches = '(1 match)';
						break;
					}
					default: {
						v_matches = '(' + p_message.v_data.v_result[v_key].count + ' matches)';
						break;
					}
				}

				var v_node = v_tree.createNode(
					v_key + ' ' + v_matches,
					false,
					'/static/OmniDB_app/images/data_mining.png',
					null,
					p_message.v_data.v_result[v_key],
					'cm_see_details'
				);

				v_node.tag.key = v_key;
			}
		}

		v_tree.drawTree();
	}

	p_context.tab_tag.tab_loading_span.style.display = 'none';
	p_context.tab_tag.tab_check_span.style.display = 'none';
	p_context.tab_tag.tab_stub_span.style.display = '';
	p_context.tab_tag.bt_cancel.style.display = 'none';
}
<commit_msg>data mining corrections<commit_after>function queryDataMining(p_data, p_callback = null) {
	var v_state = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.state;

	if(v_state != v_queryState.Idle) {
		showAlert('Tab with activity in progress.');
	}
	else {
		var v_tab_tag = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag;
		v_tab_tag.queryTabControl.tabList[0].elementDiv.innerHTML = '';
		var v_db_index  = v_connTabControl.selectedTab.tag.selectedDatabaseIndex;
		var v_tab_loading_span = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_loading_span;
		var v_tab_close_span = v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_close_span;

		//Change to run mode if database index changed
		if(v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex == null || v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex != v_connTabControl.selectedTab.tag.selectedDatabaseIndex) {
			v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.currDatabaseIndex = v_connTabControl.selectedTab.tag.selectedDatabaseIndex;
		}

		var v_message_data = {
			v_sql_cmd : '',
			v_db_index: v_db_index,
			v_conn_tab_id: v_connTabControl.selectedTab.id,
			v_tab_id: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_id,
			v_tab_db_id: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.tab_db_id,
            text: p_data.text,
            regex: p_data.regex,
            caseSensitive: p_data.caseSensitive,
            categoryList: p_data.categoryList,
            schemaList: p_data.schemaList
		};

		v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag.state = v_queryState.Executing;

		var start_time = new Date().getTime();

		var d = new Date,
        dformat = [(d.getMonth()+1).padLeft(),
                   d.getDate().padLeft(),
                   d.getFullYear()].join('/') +' ' +
                  [d.getHours().padLeft(),
                   d.getMinutes().padLeft(),
                   d.getSeconds().padLeft()].join(':');

		v_tab_tag.tab_loading_span.style.display = '';
		v_tab_tag.tab_stub_span.style.display = 'none';
		v_tab_tag.bt_cancel.style.display = '';

		var v_context = {
			tab_tag: v_connTabControl.selectedTab.tag.tabControl.selectedTab.tag,
			start_time: new Date().getTime(),
			start_datetime: dformat,
			database_index: v_connTabControl.selectedTab.tag.selectedDatabaseIndex,
			callback: p_callback,
			acked: false,
            mode: 0
		}

		v_context.tab_tag.context = v_context;

		if (p_callback==null) {
			if (v_context.tab_tag.ht!=null) {
				v_context.tab_tag.ht.destroy();
				v_context.tab_tag.ht = null;
			}

			v_context.tab_tag.div_result.innerHTML = '';
		}

		v_context.tab_tag.query_info.innerHTML = 'Start time: ' + dformat + '
Running...';

		sendWebSocketMessage(v_queryWebSocket, v_queryRequestCodes.DataMining, v_message_data, false, v_context);

		setTimeout(function() {
			if (!v_context.acked) {
				cancelSQLTab(v_context.tab_tag);
				showAlert('No response from query server.');
			}
		},20000);
	}
}

function checkDataMiningStatus(p_tab) {
	if(p_tab.tag.state == v_queryState.Ready) {
		dataMiningReturnRender(p_tab.tag.data, p_tab.tag.context);
	}
}

function dataMiningReturn(p_message, p_context) {
	//If data mining wasn't canceled already
	if(p_context.tab_tag.state!=v_queryState.Idle) {

		if(p_context.tab_tag.tab_id == p_context.tab_tag.tabControl.selectedTab.id && p_context.tab_tag.connTab.id == p_context.tab_tag.connTab.tag.connTabControl.selectedTab.id) {
			dataMiningReturnRender(p_message, p_context);
		}
		else {
			p_context.tab_tag.state = v_queryState.Ready;
			p_context.tab_tag.context = p_context;
			p_context.tab_tag.data = p_message;

			p_context.tab_tag.tab_loading_span.style.display = 'none';
			p_context.tab_tag.tab_check_span.style.display = '';
		}
	}
}

function dataMiningReturnRender(p_message, p_context) {
	p_context.tab_tag.state = v_queryState.Idle;
	p_context.tab_tag.context = null;
	p_context.tab_tag.data = null;

	var v_div_result = p_context.tab_tag.div_result;
	var v_query_info = p_context.tab_tag.query_info;

	if(p_message.v_error) {
		v_div_result.innerHTML = '
' + p_message.v_data.message + '
';
		v_query_info.innerHTML = "Start time: " + p_context.start_datetime + " Duration: " + p_message.v_data.v_duration;
	}
	else {
		v_query_info.innerHTML = "Start time: " + p_context.start_datetime + " Duration: " + p_message.v_data.v_duration;
		v_div_result.innerHTML = '

';

		var v_context_menu = {
	        'cm_see_details': {
	            elements: [{
	                text: 'See More',
	                icon: '/static/OmniDB_app/images/explain.png',
	                action: function(p_node) {
						tabSQLTemplate('Data Mining - ' + p_node.tag.key, p_node.tag.sql, false);
	                }
	            }]
	        }
		};

		var v_tree = createTree(p_context.tab_tag.queryTabControl.tabList[0].elementDiv.id, '#fcfdfd', v_context_menu);

		for(v_key in p_message.v_data.v_result) {
			if(v_key == 'Data') {
				var v_count = 0;

				var v_node = v_tree.createNode(
					v_key,
					false,
					'/static/OmniDB_app/images/data_mining.png',
					null,
					p_message.v_data.v_result[v_key],
					null
				);

				v_node.tag.key = v_key;

				for(v_key2 in p_message.v_data.v_result[v_key]) {
					if(p_message.v_data.v_result[v_key][v_key2].count > 0) {
						var v_matches = '';
						v_count += p_message.v_data.v_result[v_key][v_key2].count;

						switch(p_message.v_data.v_result[v_key][v_key2].count) {
							case 1: {
								v_matches = '(1 match)';
								break;
							}
							default: {
								v_matches = '(' + p_message.v_data.v_result[v_key][v_key2].count + ' matches)';
								break;
							}
						}

						var v_childNode = v_node.createChildNode(
							v_key2 + ' ' + v_matches,
							false,
							'/static/OmniDB_app/images/data_mining.png',
							p_message.v_data.v_result[v_key][v_key2],
							'cm_see_details'
						);

						v_childNode.tag.key = v_key2;
					}
				}

				var v_dataMatches = '';

				switch(v_count) {
					case 0: {
						v_dataMatches = '(No match)';
						break;
					}
					case 1: {
						v_dataMatches = '(1 match)';
						break;
					}
					default: {
						v_dataMatches = '(' + v_count + ' matches)';
						break;
					}
				}

				v_node.text = v_key + ' ' + v_dataMatches;
			}
			else {
				var v_matches = '';

				switch(p_message.v_data.v_result[v_key].count) {
					case 0: {
						v_matches = '(No match)';
						break;
					}
					case 1: {
						v_matches = '(1 match)';
						break;
					}
					default: {
						v_matches = '(' + p_message.v_data.v_result[v_key].count + ' matches)';
						break;
					}
				}

				var v_node = v_tree.createNode(
					v_key + ' ' + v_matches,
					false,
					'/static/OmniDB_app/images/data_mining.png',
					null,
					p_message.v_data.v_result[v_key],
					'cm_see_details'
				);

				v_node.tag.key = v_key;
			}
		}

		v_tree.drawTree();
	}

	p_context.tab_tag.tab_loading_span.style.display = 'none';
	p_context.tab_tag.tab_check_span.style.display = 'none';
	p_context.tab_tag.tab_stub_span.style.display = '';
	p_context.tab_tag.bt_cancel.style.display = 'none';
}
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('./webpack.config');

webpack.module.rules.push(
  // instrument only testing sources with Istanbul
  {
    test: /\.js$/,
    use: { loader: 'istanbul-instrumenter-loader' },
    include: process.env.KARMA_COVER_FOLDER
  }
);

module.exports = function (config) {
  config.set({
    basePath: '.',
    frameworks: ['mocha'],
    reporters: ['mocha', 'coverage-istanbul'],
    client: {
      mocha: {
        timeout : 10000, // 10 seconds - upped from 2 seconds
        retries: 3 // Allow for slow server on CI.
      }
    },
    files: [
      {pattern: path.resolve('./build/injector.js'), watched: false},
      {pattern: process.env.KARMA_FILE_PATTERN, watched: false}
    ],
    preprocessors: {
      'build/injector.js': ['webpack'],
      'src/*.spec.ts': ['webpack', 'sourcemap']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    webpack: webpack,
    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
    coverageIstanbulReporter: {
      reports: ['html', 'text-summary'],
      dir: path.join('.', 'coverage'),
      fixWebpackSourcePaths: true
    },
    browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds
    browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds
    browserDisconnectTolerance: 2,
    port: 9876,
    colors: true,
    singleRun: true,
    logLevel: config.LOG_INFO
  });
};
<commit_msg>fix coverage tests<commit_after>var path = require('path');
var webpack = require('./webpack.config');

webpack.module.rules.push(
  // instrument only testing sources with Istanbul
  {
    test: /\.js$/,
    use: { loader: 'istanbul-instrumenter-loader' },
    include: process.env.KARMA_COVER_FOLDER
  }
);

module.exports = function (config) {
  config.set({
    basePath: '.',
    frameworks: ['mocha'],
    reporters: ['mocha', 'coverage-istanbul'],
    client: {
      mocha: {
        timeout : 10000, // 10 seconds - upped from 2 seconds
        retries: 3 // Allow for slow server on CI.
      }
    },
    files: [
      {pattern: path.resolve('./build/injector.js'), watched: false},
      {pattern: process.env.KARMA_FILE_PATTERN, watched: false}
    ],
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    },
    preprocessors: {
      'build/injector.js': ['webpack'],
      'src/*.spec.ts': ['webpack', 'sourcemap']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    webpack: webpack,
    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
    coverageIstanbulReporter: {
      reports: ['html', 'text-summary'],
      dir: path.join('.', 'coverage'),
      fixWebpackSourcePaths: true
    },
    browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds
    browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds
    browserDisconnectTolerance: 2,
    port: 9876,
    colors: true,
    singleRun: true,
    logLevel: config.LOG_INFO
  });
};
<|endoftext|>


<commit_before>for(var i=0; i<3; i++){
  alert(i);
}
$(document).ready(function(){
});

<commit_msg>Update jscript.js<commit_after>
$(document).ready(function(){
  for(var i=0; i<3; i++){
  alert(i);
}
});

<|endoftext|>


<commit_before>require([
    'chai',
    'jquery',
    'underscore',
    'tests/utils',
    'text!static/modeliteration/case-list-iteration.xml',
    'text!static/modeliteration/case-list-iteration-with-questions.xml',
    'text!static/modeliteration/fixture-iteration.xml',
    'text!static/modeliteration/regular-repeat.xml',
    'tests/modeliteration'
], function (
    chai,
    $,
    _,
    util,
    CASE_LIST_REPEAT_XML,
    CASE_LIST_REPEAT_WITH_QUESTIONS_XML,
    FIXTURE_REPEAT_XML,
    REGULAR_REPEAT_XML
) {
    var assert = chai.assert,
        call = util.call,
        plugins = util.options.options.plugins || [],
        pluginsWithModelIteration = _.union(plugins, ["modeliteration"]);

    describe("The model repeat plugin", function () {
        before(function (done) {
            util.init({
                plugins: pluginsWithModelIteration,
                javaRosa: { langs: ['en'] },
                core: {
                    onReady: function () {
                        assert(this.isPluginEnabled("modeliteration"),
                               "modeliteration plugin should be enabled");
                        done();
                    }
                }
            });
        });

        it("should load a case list repeat", function () {
            util.loadXML(CASE_LIST_REPEAT_XML);
            var repeat = util.getMug("child");
            assert.deepEqual(repeat.p.dataSource, {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            });
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_XML);
        });

        it("should create a case list repeat", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "child");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_XML,
                                {normalize_xmlns: true});
        });

        it("should create a case list repeat with questions", function () {
            util.loadXML("");
            var group = util.addQuestion("Repeat", "group");
            group.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.addQuestion("PhoneNumber", "phone");
            var hidden = util.addQuestion("DataBindOnly", "hidden");
            hidden.p.calculateAttr = "/data/group/item/phone = '12345'";
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_WITH_QUESTIONS_XML,
                                {normalize_xmlns: true});
        });

        it("should load a fixture repeat", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            assert.deepEqual(repeat.p.dataSource, {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            });
            util.assertXmlEqual(call("createXML"), FIXTURE_REPEAT_XML);
        });

        it("should create a fixture repeat", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            };
            util.assertXmlEqual(call("createXML"), FIXTURE_REPEAT_XML,
                                {normalize_xmlns: true});
        });

        it("should convert fixture repeat to regular repeat when data source is removed", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {};
            repeat.p.repeat_count = "";
            util.assertXmlEqual(call("createXML"), REGULAR_REPEAT_XML);
        });

        it("should create a fixture repeat containing a text input", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            };
            util.addQuestion("Text", "text");
            util.assertJSTreeState(
                "product",
                "  text"
            );
        });

        it("should change a fixture repeat to a case list repeat", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.assertXmlEqual(call("createXML").replace(/product/g, "child"),
                                CASE_LIST_REPEAT_XML);
        });

        it("should not remove instance when ignore/retain is active", function () {
            var normal = '<bind nodeset="/data/product/item" />',
                ignore = '<bind nodeset="/data/product/item" wierd="true()" vellum:ignore="retain" />',
                xml = FIXTURE_REPEAT_XML.replace(normal, normal + ignore);
            assert(xml.indexOf(ignore) > 0, ignore + " not found in XML:\n\n" + xml);
            util.loadXML(xml);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {};
            repeat.p.repeat_count = "";
            xml = call("createXML");
            assert($(xml).find("instance[id=products]").length === 1,
                   "products instance not found in XML\n\n" + xml);
        });

        it("should not write duplicate <setvalue> nodes after rename", function () {
            // add question, save, rename, save, should not have two sets of <setvalue>s
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            var xml = call("createXML"),
                firstCount = $(xml).find("setvalue").length;
            repeat.p.nodeID = "group";
            xml = call("createXML");
            assert.equal($(xml).find("setvalue").length, firstCount,
                         "wrong number of <setvalue> nodes\n\n" + xml);
        });

        it("should update expressions on set data source", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product"),
                blue = util.addQuestion("Text", "blue"),
                text = util.addQuestion("Text", "text"),
                getPath = blue.form.getAbsolutePath.bind(blue.form);
            text.p.calculateAttr = getPath(blue);
            blue.p.labelItextID.setDefaultValue(
                '<output value="' + getPath(text) + '"/>');
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            var xml = $(call("createXML"));
            assert.equal(getPath(blue), "/data/product/item/blue");
            assert.equal(getPath(text), "/data/product/item/text");
            assert.equal(
                xml.find("bind[calculate]").attr("calculate"),
                "/data/product/item/blue",
                xml.find("bind[calculate]").attr("nodeset") + "calculate expression mismatch");
            assert.equal(xml.find("output:first").attr("value"),
                         "/data/product/item/text",
                         "output value mismatch");
            var errors = _.flatten(_.map([blue, text], function (mug) {
                    return call("getErrors", mug);
                }));
            assert(!errors.length, errors.join("\n"));
        });

        // TODO should update expressions on clear data source
    });
});
<commit_msg>Add test: update expressions on clear data source<commit_after>require([
    'chai',
    'jquery',
    'underscore',
    'tests/utils',
    'text!static/modeliteration/case-list-iteration.xml',
    'text!static/modeliteration/case-list-iteration-with-questions.xml',
    'text!static/modeliteration/fixture-iteration.xml',
    'text!static/modeliteration/regular-repeat.xml',
    'tests/modeliteration'
], function (
    chai,
    $,
    _,
    util,
    CASE_LIST_REPEAT_XML,
    CASE_LIST_REPEAT_WITH_QUESTIONS_XML,
    FIXTURE_REPEAT_XML,
    REGULAR_REPEAT_XML
) {
    var assert = chai.assert,
        call = util.call,
        plugins = util.options.options.plugins || [],
        pluginsWithModelIteration = _.union(plugins, ["modeliteration"]);

    describe("The model repeat plugin", function () {
        before(function (done) {
            util.init({
                plugins: pluginsWithModelIteration,
                javaRosa: { langs: ['en'] },
                core: {
                    onReady: function () {
                        assert(this.isPluginEnabled("modeliteration"),
                               "modeliteration plugin should be enabled");
                        done();
                    }
                }
            });
        });

        it("should load a case list repeat", function () {
            util.loadXML(CASE_LIST_REPEAT_XML);
            var repeat = util.getMug("child");
            assert.deepEqual(repeat.p.dataSource, {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            });
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_XML);
        });

        it("should create a case list repeat", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "child");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_XML,
                                {normalize_xmlns: true});
        });

        it("should create a case list repeat with questions", function () {
            util.loadXML("");
            var group = util.addQuestion("Repeat", "group");
            group.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.addQuestion("PhoneNumber", "phone");
            var hidden = util.addQuestion("DataBindOnly", "hidden");
            hidden.p.calculateAttr = "/data/group/item/phone = '12345'";
            util.assertXmlEqual(call("createXML"), CASE_LIST_REPEAT_WITH_QUESTIONS_XML,
                                {normalize_xmlns: true});
        });

        it("should load a fixture repeat", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            assert.deepEqual(repeat.p.dataSource, {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            });
            util.assertXmlEqual(call("createXML"), FIXTURE_REPEAT_XML);
        });

        it("should create a fixture repeat", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            };
            util.assertXmlEqual(call("createXML"), FIXTURE_REPEAT_XML,
                                {normalize_xmlns: true});
        });

        it("should convert fixture repeat to regular repeat when data source is removed", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {};
            repeat.p.repeat_count = "";
            util.assertXmlEqual(call("createXML"), REGULAR_REPEAT_XML);
        });

        it("should create a fixture repeat containing a text input", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "products", src: "jr://fixture/commtrack:products"},
                idsQuery: "instance('products')/products/product/@id"
            };
            util.addQuestion("Text", "text");
            util.assertJSTreeState(
                "product",
                "  text"
            );
        });

        it("should change a fixture repeat to a case list repeat", function () {
            util.loadXML(FIXTURE_REPEAT_XML);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            util.assertXmlEqual(call("createXML").replace(/product/g, "child"),
                                CASE_LIST_REPEAT_XML);
        });

        it("should not remove instance when ignore/retain is active", function () {
            var normal = '<bind nodeset="/data/product/item" />',
                ignore = '<bind nodeset="/data/product/item" wierd="true()" vellum:ignore="retain" />',
                xml = FIXTURE_REPEAT_XML.replace(normal, normal + ignore);
            assert(xml.indexOf(ignore) > 0, ignore + " not found in XML:\n\n" + xml);
            util.loadXML(xml);
            var repeat = util.getMug("product");
            repeat.p.dataSource = {};
            repeat.p.repeat_count = "";
            xml = call("createXML");
            assert($(xml).find("instance[id=products]").length === 1,
                   "products instance not found in XML\n\n" + xml);
        });

        it("should not write duplicate <setvalue> nodes after rename", function () {
            // add question, save, rename, save, should not have two sets of <setvalue>s
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            var xml = call("createXML"),
                firstCount = $(xml).find("setvalue").length;
            repeat.p.nodeID = "group";
            xml = call("createXML");
            assert.equal($(xml).find("setvalue").length, firstCount,
                         "wrong number of <setvalue> nodes\n\n" + xml);
        });

        it("should update expressions on set data source", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product"),
                blue = util.addQuestion("Text", "blue"),
                text = util.addQuestion("Text", "text"),
                getPath = blue.form.getAbsolutePath.bind(blue.form);
            assert.equal(getPath(blue), "/data/product/blue");
            assert.equal(getPath(text), "/data/product/text");
            text.p.calculateAttr = getPath(blue);
            blue.p.labelItextID.setDefaultValue(
                '<output value="' + getPath(text) + '"/>');
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            var xml = $(call("createXML"));
            assert.equal(getPath(blue), "/data/product/item/blue");
            assert.equal(getPath(text), "/data/product/item/text");
            assert.equal(
                xml.find("bind[calculate]").attr("calculate"),
                "/data/product/item/blue",
                xml.find("bind[calculate]").attr("nodeset") + " calculate expression mismatch");
            assert.equal(xml.find("output:first").attr("value"),
                         "/data/product/item/text",
                         "output value mismatch");
            var errors = _.flatten(_.map([blue, text], function (mug) {
                    return call("getErrors", mug);
                }));
            assert(!errors.length, errors.join("\n"));
        });

        it("should update expressions on clear data source", function () {
            util.loadXML("");
            var repeat = util.addQuestion("Repeat", "product");
            repeat.p.dataSource = {
                instance: {id: "casedb", src: "jr://instance/casedb"},
                idsQuery: "instance('casedb')/mother/child/@case_id"
            };
            var blue = util.addQuestion("Text", "blue"),
                text = util.addQuestion("Text", "text"),
                getPath = blue.form.getAbsolutePath.bind(blue.form);
            text.p.calculateAttr = getPath(blue);
            blue.p.labelItextID.setDefaultValue(
                '<output value="' + getPath(text) + '"/>');
            assert.equal(getPath(blue), "/data/product/item/blue");
            assert.equal(getPath(text), "/data/product/item/text");

            repeat.p.dataSource = {};
            assert.equal(getPath(blue), "/data/product/blue");
            assert.equal(getPath(text), "/data/product/text");
            var xml = $(call("createXML"));
            assert.equal(
                xml.find("bind[calculate]").attr("calculate"),
                "/data/product/blue",
                xml.find("bind[calculate]").attr("nodeset") + " calculate expression mismatch");
            assert.equal(xml.find("output:first").attr("value"),
                         "/data/product/text",
                         "output value mismatch");
            var errors = _.flatten(_.map([blue, text], function (mug) {
                    return call("getErrors", mug);
                }));
            assert(!errors.length, errors.join("\n"));
        });

    });
});
<|endoftext|>


<commit_before>/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles */

// Clean up all instances been created on the page.
(function () {

  bender.editor = {
    allowedForTests: "h1; p"
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    "CKEditor Loads": function () {
      CKEDITOR.replace("editor1");
      assert.isObject(CKEDITOR.instances.editor1, "editor instance not found");
    },

    "Structured Headings Plugin Available": function () {
      assert.isObject(CKEDITOR.plugins.get("structuredheadings"), "plugin not available");
    },

    "Command Active but Off Inside Header Tag": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_OFF, testCommand.state,
        "autoNumberHeading OFF in H1"
      );

    },

    "Command Active and On Inside AutoNumbered Header": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_ON, testCommand.state,
        "autoNumberHeading ON in H1"
      );

    },

    "Command Disabled Outside Header": function () {
      this.editorBot.setHtmlWithSelection("
^Paragraph
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_DISABLED, testCommand.state,
        "autoNumberHeading DISABLEd in P"
      );

    },

    "Command Adds Class, Sets State On": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");
      this.editorBot.execCommand("autoNumberHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
	"
^Heading
", updatedContent,
	"CSS class applied"
      );
      assert.areSame(
	CKEDITOR.TRISTATE_ON, testCommand.state,
	"autoNumberHeading ON"
      );
    },

    "Command Removes Class, Sets State Off": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");
      this.editorBot.execCommand("autoNumberHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
          "
^Heading
", updatedContent,
          "CSS class removed"
        );
      assert.areSame(
          CKEDITOR.TRISTATE_OFF, testCommand.state,
          "autoNumberHeading OFF"
        );
    }

  });
})();
<commit_msg>Tests for MatchHeading Command<commit_after>/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles */

// Clean up all instances been created on the page.
(function () {

  bender.editor = {
    allowedForTests: "h1; p"
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    "CKEditor Loads": function () {
      CKEDITOR.replace("editor1");
      assert.isObject(CKEDITOR.instances.editor1, "editor instance not found");
    },

    "Structured Headings Plugin Available": function () {
      assert.isObject(CKEDITOR.plugins.get("structuredheadings"), "plugin not available");
    },

    "AutoNumber Active but Off Inside Header Tag": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_OFF, testCommand.state,
        "autoNumberHeading OFF in H1"
      );

    },

    "AutoNumber Active and On Inside AutoNumbered Header": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_ON, testCommand.state,
        "autoNumberHeading ON in H1"
      );

    },

    "AutoNumber Disabled Outside Header": function () {
      this.editorBot.setHtmlWithSelection("
^Paragraph
");
      var testCommand = this.editor.getCommand("autoNumberHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_DISABLED, testCommand.state,
        "autoNumberHeading DISABLEd in P"
      );

    },

    "AutoNumber Adds Class, Sets State On": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");
      this.editorBot.execCommand("autoNumberHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
	"
^Heading
", updatedContent,
	"CSS class applied"
      );
      assert.areSame(
	CKEDITOR.TRISTATE_ON, testCommand.state,
	"autoNumberHeading ON"
      );
    },

    "AutoNumber Removes Class, Sets State Off": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("autoNumberHeading");
      this.editorBot.execCommand("autoNumberHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
          "
^Heading
", updatedContent,
          "CSS class removed"
        );
      assert.areSame(
          CKEDITOR.TRISTATE_OFF, testCommand.state,
          "autoNumberHeading OFF"
        );
    },

    "MatchHeading Active and On Inside Header Tag": function () {
      this.editorBot.setHtmlWithSelection("
^Heading
");
      var testCommand = this.editor.getCommand("matchHeading");

      assert.areSame(
        CKEDITOR.TRISTATE_ON, testCommand.state,
        "MatchHeading ON in H1"
      );

    },

    "MatchHeading Active and Off Inside P Tag": function () {
      this.editorBot.setHtmlWithSelection("
^Paragraph
");
      var testCommand = this.editor.getCommand("matchHeading");

      assert.areSame(
       CKEDITOR.TRISTATE_OFF, testCommand.state,
       "MatchHeading OFF in P"
      );

    },

    "MatchHeading Disabled Inside Span Tag": function () {
      this.editorBot.setHtmlWithSelection("^Span");
      var testCommand = this.editor.getCommand("matchHeading");

      assert.areSame(
       CKEDITOR.TRISTATE_DISABLED, testCommand.state,
       "MatchHeading DISABLED in SPAN"
      );

    },

    "MatchHeading Updates P Tag to H1 if No Previous": function () {
      this.editorBot.setHtmlWithSelection("
^Paragraph
");
      this.editorBot.execCommand("matchHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
        "
^Paragraph
", updatedContent,
        "P changed to H1"
      );

    },

    "MatchHeading Updates P Tag to H3 if Previous": function () {
      this.editorBot.setHtmlWithSelection("
Header

^Paragraph
");
      this.editorBot.execCommand("matchHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
        "
Header

^Paragraph
", updatedContent,
        "P changed to previous H3"
      );

    },

    "MatchHeading Updates P Tag to H2 and Autonumbered if Previous": function () {
      this.editorBot.setHtmlWithSelection(
        "
Header
" +
        "
^Paragraph
"
      );
      this.editorBot.execCommand("matchHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
        "
Header
" +
        "
^Paragraph
", updatedContent,
        "P changed to previous H2 autonumber"
      );

    },

    "MatchHeading Does Not Match Previous if Different Parent": function () {
      this.editorBot.setHtmlWithSelection(
        "
Header
" +
        "

^Paragraph

"
      );
      this.editorBot.execCommand("matchHeading");
      var updatedContent = bender.tools.getHtmlWithSelection(this.editorBot.editor);

      assert.areSame(
        "
Header
" +
        "

^Paragraph

", updatedContent,
        "P Only Matches Siblings"
      );

    }

  });
})();
<|endoftext|>


<commit_before>// ========================================================================
// SC.Binding Tests
// ========================================================================

Test.context("basic object binding", {

  setup: function() {
    fromObject = SC.Object.create({ value: 'start' }) ;
    toObject = SC.Object.create({ value: 'end' }) ;
    binding = SC.Binding.from("value", fromObject).to("value", toObject).connect() ;
  },

  "changing fromObject should mark binding as dirty": function() {
    fromObject.set("value", "change") ;
    assertEqual(binding._changePending, YES) ;
  },

  "fromObject change should propogate to toObject only after flush": function() {
    fromObject.set("value", "change") ;
    assertEqual(toObject.get("value"), "end") ;
    SC.Binding.flushPendingChanges() ;
    assertEqual(toObject.get("value"), "change") ;
  },

  "changing toObject should mark binding as dirty": function() {
    toObject.set("value", "change") ;
    assertEqual(binding._changePending, YES) ;
  },

  "toObject change should propogate to fromObject only after flush": function() {
    toObject.set("value", "change") ;
    assertEqual(fromObject.get("value"), "start") ;
    SC.Binding.flushPendingChanges() ;
    assertEqual(fromObject.get("value"), "change") ;
  }

});

Test.context("one way binding", {

  setup: function() {
    fromObject = SC.Object.create({ value: 'start' }) ;
    toObject = SC.Object.create({ value: 'end' }) ;
    binding = SC.Binding.from("value", fromObject).to("value", toObject).oneWay().connect() ;
  },

  "changing fromObject should mark binding as dirty": function() {
    fromObject.set("value", "change") ;
    assertEqual(binding._changePending, YES) ;
  },

  "fromObject change should propogate after flush": function() {
    fromObject.set("value", "change") ;
    assertEqual(toObject.get("value"), "end") ;
    SC.Binding.flushPendingChanges() ;
    assertEqual(toObject.get("value"), "change") ;
  },

  "changing toObject should not make binding dirty": function() {
    toObject.set("value", "change") ;
    assertEqual(binding._changePending, NO) ;
  },

  "toObject change should NOT propogate": function() {
    toObject.set("value", "change") ;
    assertEqual(fromObject.get("value"), "start") ;
    SC.Binding.flushPendingChanges() ;
    assertEqual(fromObject.get("value"), "start") ;
  }

});

Test.context("chained binding", {

  setup: function() {
    first = SC.Object.create({ output: 'first' }) ;

    second = SC.Object.create({
      input: 'second',
      output: 'second',

      inputDidChange: function() {
        this.set("output", this.get("input")) ;
      }.observes("input")
    }) ;

    third = SC.Object.create({ input: "third" }) ;

    binding1 = SC.Binding.from("output", first).to("input", second).connect() ;
    binding2 = SC.Binding.from("output", second).to("input", third).connect() ;
  },

  "changing first output should propograte to third after flush": function() {

    first.set("output", "change") ;
    assertEqual("change", first.get("output"), "first.output") ;
    assertNotEqual("change", second.get("input"), "second.input") ;
    assertNotEqual("change", second.get("output"), "second.output") ;
    assertNotEqual("change", third.get("input"), "third.input") ;

    SC.Binding.flushPendingChanges() ;
    assertEqual("change", first.get("output"), "first.output") ;
    assertEqual("change", second.get("input"), "second.input") ;
    assertEqual("change", second.get("output"), "second.output") ;
    assertEqual("change", third.get("input"), "third.input") ;
  }

});

<commit_msg>port SC.Binding tests to qUnit<commit_after>// ========================================================================
// SC.Binding Tests
// ========================================================================
/*globals module test ok isObj equals expects */

var fromObject, toObject, binding ; // global variables

module("basic object binding", {

  setup: function() {
    fromObject = SC.Object.create({ value: 'start' }) ;
    toObject = SC.Object.create({ value: 'end' }) ;
    binding = SC.Binding.from("value", fromObject).to("value", toObject).connect() ;
  }
});

// FAILS
test("changing fromObject should mark binding as dirty", function() {
  fromObject.set("value", "change") ;
  equals(binding._changePending, YES) ;
});

// FAILS
test("fromObject change should propogate to toObject only after flush", function() {
  fromObject.set("value", "change") ;
  equals(toObject.get("value"), "end") ;
  SC.Binding.flushPendingChanges() ;
  equals(toObject.get("value"), "change") ;
});

// FAILS
test("changing toObject should mark binding as dirty", function() {
  toObject.set("value", "change") ;
  equals(binding._changePending, YES) ;
});

// FAILS
test("toObject change should propogate to fromObject only after flush", function() {
  toObject.set("value", "change") ;
  equals(fromObject.get("value"), "start") ;
  SC.Binding.flushPendingChanges() ;
  equals(fromObject.get("value"), "change") ;
});

module("one way binding", {

  setup: function() {
    fromObject = SC.Object.create({ value: 'start' }) ;
    toObject = SC.Object.create({ value: 'end' }) ;
    binding = SC.Binding.from("value", fromObject).to("value", toObject).oneWay().connect() ;
  }

});

// FAILS
test("changing fromObject should mark binding as dirty", function() {
  fromObject.set("value", "change") ;
  equals(binding._changePending, YES) ;
});

// FAILS
test("fromObject change should propogate after flush", function() {
  fromObject.set("value", "change") ;
  equals(toObject.get("value"), "end") ;
  SC.Binding.flushPendingChanges() ;
  equals(toObject.get("value"), "change") ;
});

test("changing toObject should not make binding dirty", function() {
  toObject.set("value", "change") ;
  equals(binding._changePending, NO) ;
});

test("toObject change should NOT propogate", function() {
  toObject.set("value", "change") ;
  equals(fromObject.get("value"), "start") ;
  SC.Binding.flushPendingChanges() ;
  equals(fromObject.get("value"), "start") ;
});

var first, second, third, binding1, binding2 ; // global variables

module("chained binding", {

  setup: function() {
    first = SC.Object.create({ output: 'first' }) ;

    second = SC.Object.create({
      input: 'second',
      output: 'second',

      inputDidChange: function() {
        this.set("output", this.get("input")) ;
      }.observes("input")
    }) ;

    third = SC.Object.create({ input: "third" }) ;

    binding1 = SC.Binding.from("output", first).to("input", second).connect() ;
    binding2 = SC.Binding.from("output", second).to("input", third).connect() ;
  }

});

// FAILS
test("changing first output should propograte to third after flush", function() {
  first.set("output", "change") ;
  equals("change", first.get("output"), "first.output") ;
  ok("change" !== third.get("input"), "third.input") ;

  SC.Binding.flushPendingChanges() ;
  equals("change", first.get("output"), "first.output") ;
  equals("change", second.get("input"), "second.input") ;
  equals("change", second.get("output"), "second.output") ;
  equals("change", third.get("input"), "third.input") ;
});
<|endoftext|>


<commit_before>/*globals initTestDB: false, emit: true, generateAdapterUrl: false */
/*globals PERSIST_DATABASES: false, initDBPair: false, utils: true */
/*globals ajax: true, LevelPouch: true, makeDocs: false */
/*globals cleanupTestDatabases: false */

"use strict";

// Porting tests from Apache CouchDB bulk docs tests
// https://github.com/apache/couchdb/blob/master/share/www/script/test/bulk_docs.js

var adapters = ['local-1', 'http-1'];
var qunit = module;
var LevelPouch;

if (typeof module !== undefined && module.exports) {
  Pouch = require('../src/pouch.js');
  LevelPouch = require('../src/adapters/pouch.leveldb.js');
  utils = require('./test.utils.js');

  for (var k in utils) {
    global[k] = global[k] || utils[k];
  }
  qunit = QUnit.module;
}

adapters.map(function(adapter) {

  qunit('bulk_docs: ' + adapter, {
    setup : function () {
      this.name = generateAdapterUrl(adapter);
      Pouch.enableAllDbs = true;
    },
    teardown: cleanupTestDatabases
  });

  var authors = [
    {name: 'Dale Harvey', commits: 253},
    {name: 'Mikeal Rogers', commits: 42},
    {name: 'Johannes J. Schmidt', commits: 13},
    {name: 'Randall Leeds', commits: 9}
  ];

  asyncTest('Testing bulk docs', function() {
    initTestDB(this.name, function(err, db) {
      var docs = makeDocs(5);
      db.bulkDocs({docs: docs}, function(err, results) {
        ok(results.length === 5, 'results length matches');
        for (var i = 0; i < 5; i++) {
          ok(results[i].id === docs[i]._id, 'id matches');
          ok(results[i].rev, 'rev is set');
          // Update the doc
          docs[i]._rev = results[i].rev;
          docs[i].string = docs[i].string + ".00";
        }
        db.bulkDocs({docs: docs}, function(err, results) {
          ok(results.length === 5, 'results length matches');
          for (i = 0; i < 5; i++) {
            ok(results[i].id === i.toString(), 'id matches again');
            // set the delete flag to delete the docs in the next step
            docs[i]._rev = results[i].rev;
            docs[i]._deleted = true;
          }
          db.put(docs[0], function(err, doc) {
            db.bulkDocs({docs: docs}, function(err, results) {
              ok(results[0].error === 'conflict', 'First doc should be in conflict');
              ok(typeof results[0].rev === "undefined", 'no rev in conflict');
              for (i = 1; i < 5; i++) {
                ok(results[i].id === i.toString());
                ok(results[i].rev);
              }
              start();
            });
          });
        });
      });
    });
  });

  asyncTest('No id in bulk docs', function() {
    initTestDB(this.name, function(err, db) {
      var newdoc = {"_id": "foobar", "body": "baz"};
      db.put(newdoc, function(err, doc) {
        ok(doc.ok);
        var docs = [
          {"_id": newdoc._id, "_rev": newdoc._rev, "body": "blam"},
          {"_id": newdoc._id, "_rev": newdoc._rev, "_deleted": true}
        ];
        db.bulkDocs({docs: docs}, function(err, results) {
          ok(results[0].error === 'conflict' || results[1].error === 'conflict');
          start();
        });
      });
    });
  });

  asyncTest("Test errors on invalid doc id", function() {
    var docs = [
      {'_id': '_invalid', foo: 'bar'}
    ];
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: docs}, function(err, info) {
        equal(err.error, 'bad_request', 'correct error returned');
        ok(!info, 'info is empty');
        start();
      });
    });
  });

  asyncTest("Test two errors on invalid doc id", function() {
    var docs = [
      {'_id': '_invalid', foo: 'bar'},
      {'_id': 123, foo: 'bar'}
    ];
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: docs}, function(err, info) {
        equal(err.error, 'bad_request', 'correct error returned');
        equal(err.reason, Pouch.Errors.RESERVED_ID.reason, 'correct error message returned');
        ok(!info, 'info is empty');
        start();
      });
    });
  });

  asyncTest('No docs', function() {
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({"doc": [{"foo":"bar"}]}, function(err, result) {
        ok(err.status === 400);
        ok(err.error === 'bad_request');
        ok(err.reason === "Missing JSON list of 'docs'");
        start();
      });
    });
  });

  asyncTest('Jira 911', function() {
    initTestDB(this.name, function(err, db) {
      var docs = [
        {"_id":"0", "a" : 0},
        {"_id":"1", "a" : 1},
        {"_id":"1", "a" : 1},
        {"_id":"3", "a" : 3}
      ];
      db.bulkDocs({docs: docs}, function(err, results) {
        ok(results[1].id === "1", 'check ordering');
        ok(results[1].error === undefined, 'first id succeded');
        ok(results[2].error === "conflict", 'second conflicted');
        ok(results.length === 4, 'got right amount of results');
        start();
      });
    });
  });

  asyncTest('Test multiple bulkdocs', function() {
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: authors}, function (err, res) {
        db.bulkDocs({docs: authors}, function (err, res) {
          db.allDocs(function(err, result) {
            ok(result.total_rows === 8, 'correct number of results');
            start();
          });
        });
      });
    });
  });

  asyncTest('Bulk with new_edits=false', function() {
    initTestDB(this.name, function(err, db) {
      var docs = [
        {"_id":"foo","_rev":"2-x","_revisions":
          {"start":2,"ids":["x","a"]}
        },
        {"_id":"foo","_rev":"2-y","_revisions":
          {"start":2,"ids":["y","a"]}
        }
      ];
      db.bulkDocs({docs: docs}, {new_edits: false}, function(err, res){
        //ok(res.length === 0, "empty array returned");
        db.get("foo", {open_revs: "all"}, function(err, res){
          ok(res[0].ok._rev === "2-x", "doc1 ok");
          ok(res[1].ok._rev === "2-y", "doc2 ok");
          start();
        });
      });
    });
  });
});
<commit_msg>(#656) - add test for specific example of deletion<commit_after>/*globals initTestDB: false, emit: true, generateAdapterUrl: false */
/*globals PERSIST_DATABASES: false, initDBPair: false, utils: true */
/*globals ajax: true, LevelPouch: true, makeDocs: false */
/*globals cleanupTestDatabases: false */

"use strict";

// Porting tests from Apache CouchDB bulk docs tests
// https://github.com/apache/couchdb/blob/master/share/www/script/test/bulk_docs.js

var adapters = ['local-1', 'http-1'];
var qunit = module;
var LevelPouch;

if (typeof module !== undefined && module.exports) {
  Pouch = require('../src/pouch.js');
  LevelPouch = require('../src/adapters/pouch.leveldb.js');
  utils = require('./test.utils.js');

  for (var k in utils) {
    global[k] = global[k] || utils[k];
  }
  qunit = QUnit.module;
}

adapters.map(function(adapter) {

  qunit('bulk_docs: ' + adapter, {
    setup : function () {
      this.name = generateAdapterUrl(adapter);
      Pouch.enableAllDbs = true;
    },
    teardown: cleanupTestDatabases
  });

  var authors = [
    {name: 'Dale Harvey', commits: 253},
    {name: 'Mikeal Rogers', commits: 42},
    {name: 'Johannes J. Schmidt', commits: 13},
    {name: 'Randall Leeds', commits: 9}
  ];

  asyncTest('Testing bulk docs', function() {
    initTestDB(this.name, function(err, db) {
      var docs = makeDocs(5);
      db.bulkDocs({docs: docs}, function(err, results) {
        ok(results.length === 5, 'results length matches');
        for (var i = 0; i < 5; i++) {
          ok(results[i].id === docs[i]._id, 'id matches');
          ok(results[i].rev, 'rev is set');
          // Update the doc
          docs[i]._rev = results[i].rev;
          docs[i].string = docs[i].string + ".00";
        }
        db.bulkDocs({docs: docs}, function(err, results) {
          ok(results.length === 5, 'results length matches');
          for (i = 0; i < 5; i++) {
            ok(results[i].id === i.toString(), 'id matches again');
            // set the delete flag to delete the docs in the next step
            docs[i]._rev = results[i].rev;
            docs[i]._deleted = true;
          }
          db.put(docs[0], function(err, doc) {
            db.bulkDocs({docs: docs}, function(err, results) {
              ok(results[0].error === 'conflict', 'First doc should be in conflict');
              ok(typeof results[0].rev === "undefined", 'no rev in conflict');
              for (i = 1; i < 5; i++) {
                ok(results[i].id === i.toString());
                ok(results[i].rev);
              }
              start();
            });
          });
        });
      });
    });
  });

  asyncTest('No id in bulk docs', function() {
    initTestDB(this.name, function(err, db) {
      var newdoc = {"_id": "foobar", "body": "baz"};
      db.put(newdoc, function(err, doc) {
        ok(doc.ok);
        var docs = [
          {"_id": newdoc._id, "_rev": newdoc._rev, "body": "blam"},
          {"_id": newdoc._id, "_rev": newdoc._rev, "_deleted": true}
        ];
        db.bulkDocs({docs: docs}, function(err, results) {
          ok(results[0].error === 'conflict' || results[1].error === 'conflict');
          start();
        });
      });
    });
  });

  asyncTest("Test errors on invalid doc id", function() {
    var docs = [
      {'_id': '_invalid', foo: 'bar'}
    ];
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: docs}, function(err, info) {
        equal(err.error, 'bad_request', 'correct error returned');
        ok(!info, 'info is empty');
        start();
      });
    });
  });

  asyncTest("Test two errors on invalid doc id", function() {
    var docs = [
      {'_id': '_invalid', foo: 'bar'},
      {'_id': 123, foo: 'bar'}
    ];
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: docs}, function(err, info) {
        equal(err.error, 'bad_request', 'correct error returned');
        equal(err.reason, Pouch.Errors.RESERVED_ID.reason, 'correct error message returned');
        ok(!info, 'info is empty');
        start();
      });
    });
  });

  asyncTest('No docs', function() {
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({"doc": [{"foo":"bar"}]}, function(err, result) {
        ok(err.status === 400);
        ok(err.error === 'bad_request');
        ok(err.reason === "Missing JSON list of 'docs'");
        start();
      });
    });
  });

  asyncTest('Jira 911', function() {
    initTestDB(this.name, function(err, db) {
      var docs = [
        {"_id":"0", "a" : 0},
        {"_id":"1", "a" : 1},
        {"_id":"1", "a" : 1},
        {"_id":"3", "a" : 3}
      ];
      db.bulkDocs({docs: docs}, function(err, results) {
        ok(results[1].id === "1", 'check ordering');
        ok(results[1].error === undefined, 'first id succeded');
        ok(results[2].error === "conflict", 'second conflicted');
        ok(results.length === 4, 'got right amount of results');
        start();
      });
    });
  });

  asyncTest('Test multiple bulkdocs', function() {
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: authors}, function (err, res) {
        db.bulkDocs({docs: authors}, function (err, res) {
          db.allDocs(function(err, result) {
            ok(result.total_rows === 8, 'correct number of results');
            start();
          });
        });
      });
    });
  });

  asyncTest('Bulk with new_edits=false', function() {
    initTestDB(this.name, function(err, db) {
      var docs = [
        {"_id":"foo","_rev":"2-x","_revisions":
          {"start":2,"ids":["x","a"]}
        },
        {"_id":"foo","_rev":"2-y","_revisions":
          {"start":2,"ids":["y","a"]}
        }
      ];
      db.bulkDocs({docs: docs}, {new_edits: false}, function(err, res){
        //ok(res.length === 0, "empty array returned");
        db.get("foo", {open_revs: "all"}, function(err, res){
          ok(res[0].ok._rev === "2-x", "doc1 ok");
          ok(res[1].ok._rev === "2-y", "doc2 ok");
          start();
        });
      });
    });
  });

  asyncTest('656 regression in handling deleted docs', function() {
    initTestDB(this.name, function(err, db) {
      db.bulkDocs({docs: [{_id: "foo", _rev: "1-a", _deleted: true}]}, {new_edits: false}, function(err, res){
        db.get("foo", function(err, res){
          ok(err, "deleted");
          start();
        });
      });
    });
  });
});
<|endoftext|>