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

/* eslint-disable max-len */
import path from 'path';
import WxeApi from 'wxe-api';
import debug from 'debug';
import cache from 'memory-cache';
export const port = process.env.PORT || 3000;
export const host = process.env.WEBSITE_HOSTNAME || `localhost:${port}`;

export const databaseUrl = process.env.DATABASE_URL || 'sqlite:database.sqlite';

export const mysqlUrl = process.env.MYSQL_URL;

export const analytics = {

  // https://analytics.google.com/
  google: {
    trackingId: process.env.GOOGLE_TRACKING_ID, // UA-XXXXX-X
  },

};

export const auth = {

  jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' },

  // 微信企业号
  wxent: {
    corpId: process.env.WXE_CORPID,
    secret: process.env.WXE_SECRET,
    agentId: process.env.WXE_AGENTID || 28,
  },

  // ecard-api token
  ecardApiToken: process.env.ECARD_API_TOKEN,
};

export const tagPrefix = process.env.TAG_PREFIX || '一卡通';
export const roles = {
  posManager: process.env.POS_MANAGER || 'POS管理员',
  shopManager: process.env.SHOP_MANAGER || '商户管理员',
  ecManager: process.env.ECARD_CENTER_MANAGER || '中心管理员',
};
export const monitors = process.env.MONITOR_USERID || 'na57';

export const dailyReportPicUrl = process.env.DAILY_REPORT_PICURL;
export const monthlyReportPicUrl = process.env.MONTHLY_REPORT_PICURL;

export const getTag = (role, id) => `${tagPrefix}_${role}_${id}`;
export const getShopTag = shopName => getTag(roles.shopManager, shopName);

export const dailyReportCron = process.env.DAILY_REPORT_CRON || '0 0 8 * * *';
export const wxeapi = new WxeApi(auth.wxent);

// HTTPS 相关
export const enableHttps = process.env.ENABLE_HTTPS === 'true';
export const httpsPort = process.env.HTTPS_PORT || 3443;
export const privateKeyFilePath = process.env.PRIVETE_KEY_FILE_PATH || path.resolve(__dirname, '../ssl/example.key');
export const certificateFilePath = process.env.CERTIFICATE_FILE_PATH || path.resolve(__dirname, '../ssl/example.crt');

// debug
export const error = debug('ecard-wxe:error');
export const info = debug('ecard-wxe:info');

// ecard-api
export const ecardApiHost = process.env.ECARD_API_HOST || 'http://ecard-api.ynu.edu.cn';

// 缓存Key
export const TAG_LIST = 'wxeapi:getTagList';
export const CACHE_TIME_10_DAYS = 10 * 24 * 60 * 60 * 1000;
export const getShopBillCacheKey = (shopId, accDate) => `ecard-wxe:shopBill:${shopId}:${accDate}`;
export const getShopAncestorsCacheKey = shopId => `ecard-wxe:shop:ancestors:${shopId}`;
cache.debug(true);
<commit_msg>删除测试代码<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

/* eslint-disable max-len */
import path from 'path';
import WxeApi from 'wxe-api';
import debug from 'debug';
import cache from 'memory-cache';
export const port = process.env.PORT || 3000;
export const host = process.env.WEBSITE_HOSTNAME || `localhost:${port}`;

export const databaseUrl = process.env.DATABASE_URL || 'sqlite:database.sqlite';

export const mysqlUrl = process.env.MYSQL_URL;

export const analytics = {

  // https://analytics.google.com/
  google: {
    trackingId: process.env.GOOGLE_TRACKING_ID, // UA-XXXXX-X
  },

};

export const auth = {

  jwt: { secret: process.env.JWT_SECRET || 'React Starter Kit' },

  // 微信企业号
  wxent: {
    corpId: process.env.WXE_CORPID,
    secret: process.env.WXE_SECRET,
    agentId: process.env.WXE_AGENTID || 28,
  },

  // ecard-api token
  ecardApiToken: process.env.ECARD_API_TOKEN,
};

export const tagPrefix = process.env.TAG_PREFIX || '一卡通';
export const roles = {
  posManager: process.env.POS_MANAGER || 'POS管理员',
  shopManager: process.env.SHOP_MANAGER || '商户管理员',
  ecManager: process.env.ECARD_CENTER_MANAGER || '中心管理员',
};
export const monitors = process.env.MONITOR_USERID || 'na57';

export const dailyReportPicUrl = process.env.DAILY_REPORT_PICURL;
export const monthlyReportPicUrl = process.env.MONTHLY_REPORT_PICURL;

export const getTag = (role, id) => `${tagPrefix}_${role}_${id}`;
export const getShopTag = shopName => getTag(roles.shopManager, shopName);

export const dailyReportCron = process.env.DAILY_REPORT_CRON || '0 0 8 * * *';
export const wxeapi = new WxeApi(auth.wxent);

// HTTPS 相关
export const enableHttps = process.env.ENABLE_HTTPS === 'true';
export const httpsPort = process.env.HTTPS_PORT || 3443;
export const privateKeyFilePath = process.env.PRIVETE_KEY_FILE_PATH || path.resolve(__dirname, '../ssl/example.key');
export const certificateFilePath = process.env.CERTIFICATE_FILE_PATH || path.resolve(__dirname, '../ssl/example.crt');

// debug
export const error = debug('ecard-wxe:error');
export const info = debug('ecard-wxe:info');

// ecard-api
export const ecardApiHost = process.env.ECARD_API_HOST || 'http://ecard-api.ynu.edu.cn';

// 缓存Key
export const TAG_LIST = 'wxeapi:getTagList';
export const CACHE_TIME_10_DAYS = 10 * 24 * 60 * 60 * 1000;
export const getShopBillCacheKey = (shopId, accDate) => `ecard-wxe:shopBill:${shopId}:${accDate}`;
export const getShopAncestorsCacheKey = shopId => `ecard-wxe:shop:ancestors:${shopId}`;
<|endoftext|>


<commit_before>import is from 'is_js';

export const MALE = 'male';
export const FEMALE = 'female';
export const UNKNOWN = null;

export const isMale = (gender) => {
  if (is.not.string(gender)) {
    return false;
  }

  return /^m(ale)?$/i.test(gender);
};

export const isFemale = (gender) => {
  if (is.not.string(gender)) {
    return false;
  }

  return /^f(emale)?$/i.test(gender);
};

export const isUnknown = (gender) => ! isMale(gender) && ! isFemale(gender);

export const parse = (gender) => {
  if (isMale(gender)) {
    return MALE;
  }

  if (isFemale(gender)) {
    return FEMALE;
  }

  return UNKNOWN;
};

export const Gender = { MALE, FEMALE, UNKNOWN, isMale, isFemale, isUnknown, parse };

export default Gender;
<commit_msg>OMO-1417 Cleaned Gender<commit_after>import is from 'is_js';

const MALE = 'male';
const FEMALE = 'female';
const UNKNOWN = null;

class Gender {
  static isMale(gender) {
    if (is.not.string(gender)) {
      return false;
    }

    return /^m(ale)?$/i.test(gender);
  }

  static isFemale(gender) {
    if (is.not.string(gender)) {
      return false;
    }

    return /^f(emale)?$/i.test(gender);
  }

  static isUnknown(gender) {
    return ! Gender.isMale(gender) && ! Gender.isFemale(gender);
  }

  static parse(gender) {
    if (Gender.isMale(gender)) {
      return MALE;
    }

    if (Gender.isFemale(gender)) {
      return FEMALE;
    }

    return UNKNOWN;
  }
}

export default Gender;
<|endoftext|>


<commit_before>/*
 *  asf -- Ada Server Faces
 *  Copyright (C) 2009, 2010, 2011 Stephane Carrez
 *  Written by Stephane Carrez (Stephane.Carrez@gmail.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var ASF = {};

(function () {
    /**
     * Execute the AJAX response action represented by the JSON object action.
     *
     * @param node the current node
     * @param action the JSON action object
     */
    ASF.ExecuteOne = function(node, action) {
        var id = action.id === null ? node : action.id;
        if (action.action === "update") {
	        $(id).html(action.data);

        } else if (action.action === "prepend") {
	        $(id).prepend(action.data);

        } else if (action.action === "append") {
	        $(id).append(action.data);

        } else if (action.action === "show") {
            $(id).show('slow');

        } else if (action.action === "hide") {
            $(id).hide('slow');

        } else if (action.action === "delete") {
	        $(id).remove();

        } else if (action.action === "removeClass") {
	        $(id).removeClass(action.data);

        } else if (action.action === "addClass") {
	        $(id).addClass(action.data);

        } else if (action.action === "fadeIn") {
            $(id).fadeIn('slow');

        } else if (action.action === "fadeOut") {
            $(id).fadeOut('slow');

        } else if (action.action === "slideUp") {
            $(id).slideUp('slow');

        } else if (action.action === "slideDown") {
            $(id).slideDown('slow');

        } else if (action.action === "closeDialog") {
            $(id).dialog('close');

        } else if (action.action === "redirect") {
            document.location = action.url;
	    }
    };

    ASF.Execute = function(node, data) {
        if (data != null) {
            for (var i = 0; i < data.length; i++) {
                ASF.ExecuteOne(node, data[i]);
            }
        }
    };

    /**
     * Update the target container with the content of the AJAX GET request
     * on the given URL.  The target parameter is optional.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     */
    ASF.Update = function(node, url, target) {
        /* Find the container to update */
        var d;
        if (target != null) {
            d = $(target);
        } else {
            d = $(node);
            if (!d.is('.asf-container')) {
                d = d.parent('.asf-container');
            }
        }
        if (d.length > 0) {
            /* Perform the HTTP GET */
            jQuery.ajax({
                url: url,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.html(jqXHDR.responseText);

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
               }
            });
        }
    };

    /**
     * Submit the current form.  The node element refers to the element being clicked.
     * From that element, we can identify the form to submit.  The element to refresh upon
     * the form submit is an outer element that should have the asf-container class.
     * If not such element as parent node, the parent node of the form is used.
     *
     * After the form is submitted, the response is executed if it is a JSON response.
     * If the response is an HTML content, the container element is refreshed with it.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     */
    ASF.Submit = function(node) {
        /* Find the form and container to update */
        var f = $(node).closest("form");
        var d = $(f);
        if (!d.is('.asf-container,ui-dialog-content')) {
            d = d.closest('.asf-container,.ui-dialog-content');
        }
        if (d.length == 0) {
            d = $(f).parent();
        }
        if (d.length > 0) {
            var params;
            var params = $(f).serialize();
            var url = $(f).attr('action');

            if (node.tagName == 'a' || node.tagName == 'A') {
                params = node.id + "=1&" + $(f).serialize();
            } else {
                params = node.name + "=1&" + $(f).serialize();
            }
            /* Perform the HTTP POST */
            jQuery.ajax({
                type: "POST",
                url: url,
                data: params,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.html(jqXHDR.responseText);

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
               }
            });
        }
        return false;
    };

    /**
     * Open a dialog box and fetch the dialog content from the given URI.
     *
     * @param node the current element
     * @param id the dialog id
     * @param url the URL to fetch using an HTTP GET
     * @param params the optional dialog options
     */
    ASF.OpenDialog = function(node, id, url, params) {
        var div = $(id);
        if (div.length > 0) {
            return false;
        }

        div = document.createElement("div");
        div.id = id;
        div = $(div);

        var d = $(document);
        if (d.length == 0) {
            return false;
        }

        $(d).append($(div));

        /* Perform the HTTP GET */
        jQuery.ajax({
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).dialog({
                        autoOpen: false,
                        show: "blind",
                        hide: "explode",
                        minWidth: 600,
                        close: function() {
                            $(div).dialog('destroy');
                            $(div).remove();
                        }
                     });

                     $(div).html(jqXHDR.responseText);
                     var dTitle = $(div).children('div').attr('title');
                     if (dTitle != null) {
                        $(div).dialog("option", "title", dTitle );
                        /* $(div).attr('title', title); */
                     }
                     $(div).dialog('open');

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            }
        });
        return false;
    };

    /**
     * Close the dialog box identified by the given identifier.
     *
     * @param id the dialog box identifier
     */
    ASF.CloseDialog = function(id) {
        $('#' + id).dialog('close');
        return false;
    };

})();

<commit_msg>Add an optional complete function to the Update operation Add a fade out/fade in effect when updating the block<commit_after>/*
 *  asf -- Ada Server Faces
 *  Copyright (C) 2009, 2010, 2011 Stephane Carrez
 *  Written by Stephane Carrez (Stephane.Carrez@gmail.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var ASF = {};

(function () {
    /**
     * Execute the AJAX response action represented by the JSON object action.
     *
     * @param node the current node
     * @param action the JSON action object
     */
    ASF.ExecuteOne = function(node, action) {
        var id = action.id === null ? node : action.id;
        if (action.action === "update") {
	        $(id).html(action.data);

        } else if (action.action === "prepend") {
	        $(id).prepend(action.data);

        } else if (action.action === "append") {
	        $(id).append(action.data);

        } else if (action.action === "show") {
            $(id).show('slow');

        } else if (action.action === "hide") {
            $(id).hide('slow');

        } else if (action.action === "delete") {
	        $(id).remove();

        } else if (action.action === "removeClass") {
	        $(id).removeClass(action.data);

        } else if (action.action === "addClass") {
	        $(id).addClass(action.data);

        } else if (action.action === "fadeIn") {
            $(id).fadeIn('slow');

        } else if (action.action === "fadeOut") {
            $(id).fadeOut('slow');

        } else if (action.action === "slideUp") {
            $(id).slideUp('slow');

        } else if (action.action === "slideDown") {
            $(id).slideDown('slow');

        } else if (action.action === "closeDialog") {
            $(id).dialog('close');

        } else if (action.action === "redirect") {
            document.location = action.url;
	    }
    };

    ASF.Execute = function(node, data) {
        if (data != null) {
            for (var i = 0; i < data.length; i++) {
                ASF.ExecuteOne(node, data[i]);
            }
        }
    };

    /**
     * Update the target container with the content of the AJAX GET request
     * on the given URL.  The target parameter is optional.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     * @param complete an optional function called when the response is received
     */
    ASF.Update = function(node, url, target, complete) {
        /* Find the container to update */
        var d;
        if (target != null) {
            d = $(target);
        } else {
            d = $(node);
            if (!d.is('.asf-container')) {
                d = d.parent('.asf-container');
            }
        }
        if (d.length > 0) {
            /* Perform the HTTP GET */
            jQuery.ajax({
                url: url,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.html(jqXHDR.responseText);

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
                    if (complete != null) {
                        complete(d);
                    }
               }
            });
        }
    };

    /**
     * Submit the current form.  The node element refers to the element being clicked.
     * From that element, we can identify the form to submit.  The element to refresh upon
     * the form submit is an outer element that should have the asf-container class.
     * If not such element as parent node, the parent node of the form is used.
     *
     * After the form is submitted, the response is executed if it is a JSON response.
     * If the response is an HTML content, the container element is refreshed with it.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     */
    ASF.Submit = function(node) {
        /* Find the form and container to update */
        var f = $(node).closest("form");
        var d = $(f);
        if (!d.is('.asf-container,ui-dialog-content')) {
            d = d.closest('.asf-container,.ui-dialog-content');
        }
        if (d.length == 0) {
            d = $(f).parent();
        }
        if (d.length > 0) {
            var params;
            var params = $(f).serialize();
            var url = $(f).attr('action');

            if (node.tagName == 'a' || node.tagName == 'A') {
                params = node.id + "=1&" + $(f).serialize();
            } else {
                params = node.name + "=1&" + $(f).serialize();
            }
            /* Perform the HTTP POST */
            jQuery.ajax({
                type: "POST",
                url: url,
                data: params,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.fadeOut("fast", function() {
                            d.html(jqXHDR.responseText);
                            d.fadeIn("fast");
                        });

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
               }
            });
        }
        return false;
    };

    /**
     * Open a dialog box and fetch the dialog content from the given URI.
     *
     * @param node the current element
     * @param id the dialog id
     * @param url the URL to fetch using an HTTP GET
     * @param params the optional dialog options
     */
    ASF.OpenDialog = function(node, id, url, params) {
        var div = $(id);
        if (div.length > 0) {
            return false;
        }

        div = document.createElement("div");
        div.id = id;
        div = $(div);

        var d = $(document);
        if (d.length == 0) {
            return false;
        }

        $(d).append($(div));

        /* Perform the HTTP GET */
        jQuery.ajax({
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).dialog({
                        autoOpen: false,
                        show: "blind",
                        hide: "explode",
                        minWidth: 600,
                        close: function() {
                            $(div).dialog('destroy');
                            $(div).remove();
                        }
                     });

                     $(div).html(jqXHDR.responseText);
                     var dTitle = $(div).children('div').attr('title');
                     if (dTitle != null) {
                        $(div).dialog("option", "title", dTitle );
                        /* $(div).attr('title', title); */
                     }
                     $(div).dialog('open');

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            }
        });
        return false;
    };

    /**
     * Close the dialog box identified by the given identifier.
     *
     * @param id the dialog box identifier
     */
    ASF.CloseDialog = function(id) {
        $('#' + id).dialog('close');
        return false;
    };

})();

<|endoftext|>


<commit_before>import * as FrontendPrefsOptions from './utils/frontend-preferences-options';

const config = {
  api:{
    host: 'http://localhost:3000',
    sentinel: null // keep always last
  },
  auth: {
    cookieDomain: 'localhost',
    tokenPrefix: 'freefeed_',
    userStorageKey: 'USER_KEY',
    sentinel: null // keep always last
  },
  captcha: {
    siteKey: '',
    sentinel: null // keep always last
  },
  search: {
    searchEngine: null,
    sentinel: null // keep always last
  },
  siteDomains: [ // for transform links in the posts, comments, etc.
    'freefeed.net',
    'gamma.freefeed.net'
  ],
  sentry: {
    publicDSN: null,
    sentinel: null // keep always last
  },
  frontendPreferences: {
    clientId: 'net.freefeed',
    defaultValues: {
      displayNames: {
        displayOption: FrontendPrefsOptions.DISPLAYNAMES_DISPLAYNAME,
        useYou: true
      },
      realtimeActive: false,
      comments: {
        omitRepeatedBubbles: true,
        highlightComments: true,
        hiddenTypes: []
      },
      allowLinksPreview: false,
      readMoreStyle: 'modern',
      homefeed: {
        hideUsers: []
      }
    }
  }
};

export default config;
<commit_msg>Change default value of displayname setting<commit_after>import * as FrontendPrefsOptions from './utils/frontend-preferences-options';

const config = {
  api:{
    host: 'http://localhost:3000',
    sentinel: null // keep always last
  },
  auth: {
    cookieDomain: 'localhost',
    tokenPrefix: 'freefeed_',
    userStorageKey: 'USER_KEY',
    sentinel: null // keep always last
  },
  captcha: {
    siteKey: '',
    sentinel: null // keep always last
  },
  search: {
    searchEngine: null,
    sentinel: null // keep always last
  },
  siteDomains: [ // for transform links in the posts, comments, etc.
    'freefeed.net',
    'gamma.freefeed.net'
  ],
  sentry: {
    publicDSN: null,
    sentinel: null // keep always last
  },
  frontendPreferences: {
    clientId: 'net.freefeed',
    defaultValues: {
      displayNames: {
        displayOption: FrontendPrefsOptions.DISPLAYNAMES_BOTH,
        useYou: true
      },
      realtimeActive: false,
      comments: {
        omitRepeatedBubbles: true,
        highlightComments: true,
        hiddenTypes: []
      },
      allowLinksPreview: false,
      readMoreStyle: 'modern',
      homefeed: {
        hideUsers: []
      }
    }
  }
};

export default config;
<|endoftext|>


<commit_before>'use strict';

//Vocablists service used to communicate Vocablists REST endpoints
angular.module('vocabs').factory('Vocab', ['$resource',
  function($resource) {
    return $resource(
      'vocabs/:vocabId',
      {
        vocabId: '@_id'
      },
      {
        updateMultiple: {
          method: 'PUT',
          url: 'vocabs/updateMultiple',
          isArray: true
        }
      }
    );
  }
]);
<commit_msg>Fixes typo<commit_after>'use strict';

//Vocablists service used to communicate Vocablists REST endpoints
angular.module('vocabs').factory('Vocabs', ['$resource',
  function($resource) {
    return $resource(
      'vocabs/:vocabId',
      {
        vocabId: '@_id'
      },
      {
        updateMultiple: {
          method: 'PUT',
          url: 'vocabs/updateMultiple',
          isArray: true
        }
      }
    );
  }
]);
<|endoftext|>


<commit_before>var $url = '/cms/editor/editor';
var $urlInsert = $url + '/actions/insert';
var $urlUpdate = $url + '/actions/update';
var $urlPreview = $url + '/actions/preview';
var $urlCensor = $url + '/actions/censor';
var $urlTags = $url + '/actions/tags';

var data = utils.init({
  siteId: utils.getQueryInt('siteId'),
  channelId: utils.getQueryInt('channelId'),
  contentId: utils.getQueryInt('contentId'),
  page: utils.getQueryInt('page'),
  tabName: utils.getQueryString('tabName'),
  reloadChannelId: utils.getQueryInt('reloadChannelId'),
  mainHeight: '',
  isSettings: true,
  sideType: 'first',
  collapseSettings: ['checkedLevel', 'addDate'],
  collapseMore: ['templateId', 'translates'],

  csrfToken: null,
  site: null,
  siteUrl: null,
  channel: null,
  groupNames: null,
  tagNames: null,
  checkedLevels: null,
  isCensorTextEnabled: null,
  siteOptions: null,
  channelOptions: null,
  styles: null,
  templates: null,
  form: null,

  translates: [],
  isPreviewSaving: false,

  dialogCensor: false,
  isCensorSave: false,
  textResult: null
});

var methods = {
  runFormLayerImageUploadText: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerImageUploadEditor: function(attributeName, html) {
    this.insertEditor(attributeName, html);
  },

  runMaterialLayerImageSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerFileUpload: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runMaterialLayerFileSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerVideoUpload: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runMaterialLayerVideoSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runEditorLayerImage: function(attributeName, html) {
    this.insertEditor(attributeName, html);
  },

  insertText: function(attributeName, no, text) {
    var count = this.form[utils.getCountName(attributeName)] || 0;
    if (count <= no) {
      this.form[utils.getCountName(attributeName)] = no;
    }
    this.form[utils.getExtendName(attributeName, no)] = text;
    this.form = _.assign({}, this.form);
  },

  insertEditor: function(attributeName, html) {
    if (!attributeName) attributeName = 'Body';
    if (!html) return;
    utils.getEditor(attributeName).execCommand('insertHTML', html);
  },

  addTranslation: function(targetSiteId, targetChannelId, translateType, summary) {
    this.translates.push({
      siteId: this.siteId,
      channelId: this.channelId,
      targetSiteId: targetSiteId,
      targetChannelId: targetChannelId,
      translateType: translateType,
      summary: summary
    });
  },

  updateGroups: function(res, message) {
    this.groupNames = res.groupNames;
    utils.success(message);
  },

  apiGet: function() {
    var $this = this;

    window.onresize = function() {
      $this.mainHeight = ($(window).height() - 70) + 'px';
    };
    window.onresize();

    $api.get($url, {
      params: {
        siteId: $this.siteId,
        channelId: $this.channelId,
        contentId: $this.contentId
      }
    }).then(function(response) {
      var res = response.data;

      $this.csrfToken = res.csrfToken;

      $this.site = res.site;
      $this.siteUrl = res.siteUrl;
      $this.channel = res.channel;
      $this.groupNames = res.groupNames;
      $this.tagNames = res.tagNames;
      $this.checkedLevels = res.checkedLevels;
      $this.isCensorTextEnabled = res.isCensorTextEnabled;

      $this.siteOptions = res.siteOptions;
      $this.channelOptions = res.channelOptions;

      $this.styles = res.styles;
      $this.templates = res.templates;
      $this.form = _.assign({}, res.content);

      if (!$this.form.addDate) {
        $this.form.addDate = new Date();
      } else {
        $this.form.addDate = new Date($this.form.addDate);
      }

      if ($this.form.checked) {
        $this.form.checkedLevel = $this.site.checkContentLevel;
      }
      if ($this.checkedLevels.indexOf($this.form.checkedLevel) === -1) {
        $this.form.checkedLevel = res.checkedLevel;
      }
      if ($this.form.top || $this.form.recommend || $this.form.hot || $this.form.color) {
        $this.collapseSettings.push('attributes');
      }
      if ($this.form.groupNames && $this.form.groupNames.length > 0) {
        $this.collapseSettings.push('groupNames');
      } else {
        $this.form.groupNames = [];
      }
      if ($this.form.tagNames && $this.form.tagNames.length > 0) {
        $this.collapseSettings.push('tagNames');
      } else {
        $this.form.tagNames = [];
      }
      if ($this.form.linkUrl) {
        $this.collapseSettings.push('linkUrl');
      }

      for (var i = 0; i < $this.styles.length; i++) {
        var style = $this.styles[i];
        if (style.inputType === 'CheckBox' || style.inputType === 'SelectMultiple') {
          var value = $this.form[utils.toCamelCase(style.attributeName)];
          if (!Array.isArray(value)) {
            if (!value) {
              $this.form[utils.toCamelCase(style.attributeName)] = [];
            } else {
              $this.form[utils.toCamelCase(style.attributeName)] = utils.toArray(value);
            }
          }
        } else if (style.inputType === 'Image' || style.inputType === 'File' || style.inputType === 'Video') {
          $this.form[utils.getCountName(style.attributeName)] = utils.toInt($this.form[utils.getCountName(style.attributeName)]);
        } else if (style.inputType === 'Text' || style.inputType === 'TextArea' || style.inputType === 'TextEditor') {
          if ($this.contentId === 0) {
            $this.form[utils.toCamelCase(style.attributeName)] = style.defaultValue;
          }
        }
      }

      setTimeout(function () {
        for (var i = 0; i < $this.styles.length; i++) {
          var style = $this.styles[i];
          var attributeName = utils.toCamelCase(style.attributeName);
          if (style.inputType === 'TextEditor') {
            var editor = utils.getEditor(style.attributeName);
            editor.styleIndex = i;
            editor.ready(function () {
              this.addListener("contentChange", function () {
                var style = $this.styles[this.styleIndex];
                $this.form[utils.toCamelCase(style.attributeName)] = this.getContent();
              });
            });
          } else if (style.inputType === 'Date' || style.inputType === 'DateTime') {
            if (!$this.form[attributeName]) {
              $this.form[attributeName] = new Date();
            } else {
              $this.form[attributeName] = new Date($this.form[attributeName]);
            }
          }
        }
      }, 100);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  syncEditors: function () {
    var $this = this;
    if (UE) {
      $.each(UE.instants, function (index, editor) {
        editor.sync();
        var style = $this.styles[editor.styleIndex];
        $this.form[utils.toCamelCase(style.attributeName)] = editor.getContent();
      });
    }
  },

  apiInsert: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlInsert, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form,
      translates: this.translates
    }).then(function(response) {
      var res = response.data;

      $this.closeAndRedirect(false);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiCensor: function(isSave) {
    this.isCensorSave = isSave;
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlCensor, {
      siteId: this.siteId,
      channelId: this.channelId,
      content: this.form
    }).then(function(response) {
      var res = response.data;

      if (res.success) {
        if (isSave) {
          $this.btnCensorSaveClick();
        } else {
          utils.success('内容审查通过！');
        }
      } else {
        $this.textResult = res.textResult;
        $this.dialogCensor = true;
      }
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiTags: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlTags, {
      siteId: this.siteId,
      channelId: this.channelId,
      content: this.form.body
    }).then(function(response) {
      var res = response.data;

      if (res.tags && res.tags.length > 0) {
        $this.form.tagNames = _.union($this.form.tagNames, res.tags);
        utils.success('成功提取标签！');
      }
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiPreview: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlPreview, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form
    }).then(function(response) {
      var res = response.data;

      $this.isPreviewSaving = false;
      window.open(res.url);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiUpdate: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlUpdate, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form,
      translates: this.translates
    }).then(function(response) {
      var res = response.data;

      $this.closeAndRedirect(true);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  btnCensorSaveClick: function() {
    if (this.contentId === 0) {
      this.apiInsert();
    } else {
      this.apiUpdate();
    }
  },

  closeAndRedirect: function(isEdit) {
    var tabVue = utils.getTabVue(this.tabName);
    if (tabVue) {
      if (isEdit) {
        tabVue.apiList(this.reloadChannelId > 0 ? this.reloadChannelId : this.channelId, this.page, '内容编辑成功！');
      } else {
        tabVue.apiList(this.channelId, this.page, '内容新增成功！', true);
      }
    }
    utils.removeTab();
    utils.openTab(this.tabName);
  },

  btnLayerClick: function(options) {
    var query = {
      siteId: this.siteId,
      channelId: this.channelId,
      editorAttributeName: 'Body'
    };

    if (options.contentId) {
      query.contentId = options.contentId;
    }
    if (options.attributeName) {
      query.attributeName = options.attributeName;
    }
    if (options.no) {
      query.no = options.no;
    }

    var args = {
      title: options.title,
      url: utils.getCommonUrl(options.name, query)
    };
    if (!options.full) {
      args.width = options.width ? options.width : 700;
      args.height = options.height ? options.height : 500;
    }

    utils.openLayer(args);
  },

  handleTranslationClose: function(summary) {
    this.translates = _.remove(this.translates, function(n) {
      return summary !== n.summary;
    });
  },

  btnSaveClick: function() {
    var $this = this;
    this.syncEditors();
    this.$refs.form.validate(function(valid) {
      if (valid) {
        if ($this.site.isAutoCheckKeywords && $this.isCensorTextEnabled) {
          $this.apiCensor(true);
        } else {
          $this.btnCensorSaveClick();
        }
      } else {
        utils.error('保存失败，请检查表单值是否正确');
      }
    });
  },

  btnCensorClick: function() {
    this.syncEditors();
    this.apiCensor(false);
  },

  btnTagsClick: function() {
    this.syncEditors();
    if (!this.form.body) return;
    this.apiTags();
  },

  btnPreviewClick: function() {
    var $this = this;
    if (this.isPreviewSaving) return;
    this.syncEditors();
    this.$refs.form.validate(function(valid) {
      if (valid) {
        $this.apiPreview();
      } else {
        utils.error('预览失败，请检查表单值是否正确');
      }
    });
  },

  btnCloseClick: function() {
    utils.removeTab();
  },

  btnGroupAddClick: function() {
    utils.openLayer({
      title: '新增内容组',
      url: utils.getCommonUrl('groupContentLayerAdd', {siteId: this.siteId}),
      width: 500,
      height: 300
    });
  },

  btnTranslateAddClick: function() {
    utils.openLayer({
      title: "选择转移栏目",
      url: utils.getCmsUrl('editorLayerTranslate', {
        siteId: this.siteId,
        channelId: this.channelId
      }),
      width: 620,
      height: 400
    });
  },

  btnExtendAddClick: function(style) {
    var no = this.form[utils.getCountName(style.attributeName)] + 1;
    this.form[utils.getCountName(style.attributeName)] = no;
    this.form[utils.getExtendName(style.attributeName, no)] = '';
    this.form = _.assign({}, this.form);
  },

  btnExtendRemoveClick: function(style) {
    var no = this.form[utils.getCountName(style.attributeName)];
    this.form[utils.getCountName(style.attributeName)] = no - 1;
    this.form[utils.getExtendName(style.attributeName, no)] = '';
    this.form = _.assign({}, this.form);
  },

  btnExtendPreviewClick: function(attributeName, no) {
    var count = this.form[utils.getCountName(attributeName)];
    var data = [];
    for (var i = 0; i <= count; i++) {
      var imageUrl = this.form[utils.getExtendName(attributeName, i)];
      imageUrl = utils.getUrl(this.siteUrl, imageUrl);
      data.push({
        "src": imageUrl
      });
    }
    layer.photos({
      photos: {
        "start": no,
        "data": data
      }
      ,anim: 5
    });
  }
};

var $vue = new Vue({
  el: "#main",
  data: data,
  methods: methods,
  created: function() {
    this.apiGet();
  }
});
<commit_msg>bugfix<commit_after>var $url = '/cms/editor/editor';
var $urlInsert = $url + '/actions/insert';
var $urlUpdate = $url + '/actions/update';
var $urlPreview = $url + '/actions/preview';
var $urlCensor = $url + '/actions/censor';
var $urlTags = $url + '/actions/tags';

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                   // 月份
    "d+": this.getDate(),                        // 日
    "h+": this.getHours(),                       // 时
    "m+": this.getMinutes(),                     // 分
    "s+": this.getSeconds(),                     // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds()                  // 毫秒
  };

  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

  return fmt;
};

var data = utils.init({
  siteId: utils.getQueryInt('siteId'),
  channelId: utils.getQueryInt('channelId'),
  contentId: utils.getQueryInt('contentId'),
  page: utils.getQueryInt('page'),
  tabName: utils.getQueryString('tabName'),
  reloadChannelId: utils.getQueryInt('reloadChannelId'),
  mainHeight: '',
  isSettings: true,
  sideType: 'first',
  collapseSettings: ['checkedLevel', 'addDate'],
  collapseMore: ['templateId', 'translates'],

  csrfToken: null,
  site: null,
  siteUrl: null,
  channel: null,
  groupNames: null,
  tagNames: null,
  checkedLevels: null,
  isCensorTextEnabled: null,
  siteOptions: null,
  channelOptions: null,
  styles: null,
  templates: null,
  form: null,

  translates: [],
  isPreviewSaving: false,

  dialogCensor: false,
  isCensorSave: false,
  textResult: null
});

var methods = {
  runFormLayerImageUploadText: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerImageUploadEditor: function(attributeName, html) {
    this.insertEditor(attributeName, html);
  },

  runMaterialLayerImageSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerFileUpload: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runMaterialLayerFileSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runFormLayerVideoUpload: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runMaterialLayerVideoSelect: function(attributeName, no, text) {
    this.insertText(attributeName, no, text);
  },

  runEditorLayerImage: function(attributeName, html) {
    this.insertEditor(attributeName, html);
  },

  insertText: function(attributeName, no, text) {
    var count = this.form[utils.getCountName(attributeName)] || 0;
    if (count <= no) {
      this.form[utils.getCountName(attributeName)] = no;
    }
    this.form[utils.getExtendName(attributeName, no)] = text;
    this.form = _.assign({}, this.form);
  },

  insertEditor: function(attributeName, html) {
    if (!attributeName) attributeName = 'Body';
    if (!html) return;
    utils.getEditor(attributeName).execCommand('insertHTML', html);
  },

  addTranslation: function(targetSiteId, targetChannelId, translateType, summary) {
    this.translates.push({
      siteId: this.siteId,
      channelId: this.channelId,
      targetSiteId: targetSiteId,
      targetChannelId: targetChannelId,
      translateType: translateType,
      summary: summary
    });
  },

  updateGroups: function(res, message) {
    this.groupNames = res.groupNames;
    utils.success(message);
  },

  apiGet: function() {
    var $this = this;

    window.onresize = function() {
      $this.mainHeight = ($(window).height() - 70) + 'px';
    };
    window.onresize();

    $api.get($url, {
      params: {
        siteId: $this.siteId,
        channelId: $this.channelId,
        contentId: $this.contentId
      }
    }).then(function(response) {
      var res = response.data;

      $this.csrfToken = res.csrfToken;

      $this.site = res.site;
      $this.siteUrl = res.siteUrl;
      $this.channel = res.channel;
      $this.groupNames = res.groupNames;
      $this.tagNames = res.tagNames;
      $this.checkedLevels = res.checkedLevels;
      $this.isCensorTextEnabled = res.isCensorTextEnabled;

      $this.siteOptions = res.siteOptions;
      $this.channelOptions = res.channelOptions;

      $this.styles = res.styles;
      $this.templates = res.templates;
      $this.form = _.assign({}, res.content);

      if (!$this.form.addDate) {
        $this.form.addDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
      } else {
        $this.form.addDate = new Date($this.form.addDate).Format("yyyy-MM-dd hh:mm:ss");
      }

      if ($this.form.checked) {
        $this.form.checkedLevel = $this.site.checkContentLevel;
      }
      if ($this.checkedLevels.indexOf($this.form.checkedLevel) === -1) {
        $this.form.checkedLevel = res.checkedLevel;
      }
      if ($this.form.top || $this.form.recommend || $this.form.hot || $this.form.color) {
        $this.collapseSettings.push('attributes');
      }
      if ($this.form.groupNames && $this.form.groupNames.length > 0) {
        $this.collapseSettings.push('groupNames');
      } else {
        $this.form.groupNames = [];
      }
      if ($this.form.tagNames && $this.form.tagNames.length > 0) {
        $this.collapseSettings.push('tagNames');
      } else {
        $this.form.tagNames = [];
      }
      if ($this.form.linkUrl) {
        $this.collapseSettings.push('linkUrl');
      }

      for (var i = 0; i < $this.styles.length; i++) {
        var style = $this.styles[i];
        if (style.inputType === 'CheckBox' || style.inputType === 'SelectMultiple') {
          var value = $this.form[utils.toCamelCase(style.attributeName)];
          if (!Array.isArray(value)) {
            if (!value) {
              $this.form[utils.toCamelCase(style.attributeName)] = [];
            } else {
              $this.form[utils.toCamelCase(style.attributeName)] = utils.toArray(value);
            }
          }
        } else if (style.inputType === 'Image' || style.inputType === 'File' || style.inputType === 'Video') {
          $this.form[utils.getCountName(style.attributeName)] = utils.toInt($this.form[utils.getCountName(style.attributeName)]);
        } else if (style.inputType === 'Text' || style.inputType === 'TextArea' || style.inputType === 'TextEditor') {
          if ($this.contentId === 0) {
            $this.form[utils.toCamelCase(style.attributeName)] = style.defaultValue;
          }
        }
      }

      setTimeout(function () {
        for (var i = 0; i < $this.styles.length; i++) {
          var style = $this.styles[i];
          var attributeName = utils.toCamelCase(style.attributeName);
          if (style.inputType === 'TextEditor') {
            var editor = utils.getEditor(style.attributeName);
            editor.styleIndex = i;
            editor.ready(function () {
              this.addListener("contentChange", function () {
                var style = $this.styles[this.styleIndex];
                $this.form[utils.toCamelCase(style.attributeName)] = this.getContent();
              });
            });
          } else if (style.inputType === 'Date' || style.inputType === 'DateTime') {
            if (!$this.form[attributeName]) {
              $this.form[attributeName] = new Date();
            } else {
              $this.form[attributeName] = new Date($this.form[attributeName]);
            }
          }
        }
      }, 100);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  syncEditors: function () {
    var $this = this;
    if (UE) {
      $.each(UE.instants, function (index, editor) {
        editor.sync();
        var style = $this.styles[editor.styleIndex];
        $this.form[utils.toCamelCase(style.attributeName)] = editor.getContent();
      });
    }
  },

  apiInsert: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlInsert, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form,
      translates: this.translates
    }).then(function(response) {
      var res = response.data;

      $this.closeAndRedirect(false);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiCensor: function(isSave) {
    this.isCensorSave = isSave;
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlCensor, {
      siteId: this.siteId,
      channelId: this.channelId,
      content: this.form
    }).then(function(response) {
      var res = response.data;

      if (res.success) {
        if (isSave) {
          $this.btnCensorSaveClick();
        } else {
          utils.success('内容审查通过！');
        }
      } else {
        $this.textResult = res.textResult;
        $this.dialogCensor = true;
      }
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiTags: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlTags, {
      siteId: this.siteId,
      channelId: this.channelId,
      content: this.form.body
    }).then(function(response) {
      var res = response.data;

      if (res.tags && res.tags.length > 0) {
        $this.form.tagNames = _.union($this.form.tagNames, res.tags);
        utils.success('成功提取标签！');
      }
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiPreview: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlPreview, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form
    }).then(function(response) {
      var res = response.data;

      $this.isPreviewSaving = false;
      window.open(res.url);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  apiUpdate: function() {
    var $this = this;

    utils.loading(this, true);
    $api.csrfPost(this.csrfToken, $urlUpdate, {
      siteId: this.siteId,
      channelId: this.channelId,
      contentId: this.contentId,
      content: this.form,
      translates: this.translates
    }).then(function(response) {
      var res = response.data;

      $this.closeAndRedirect(true);
    }).catch(function(error) {
      utils.error(error);
    }).then(function() {
      utils.loading($this, false);
    });
  },

  btnCensorSaveClick: function() {
    if (this.contentId === 0) {
      this.apiInsert();
    } else {
      this.apiUpdate();
    }
  },

  closeAndRedirect: function(isEdit) {
    var tabVue = utils.getTabVue(this.tabName);
    if (tabVue) {
      if (isEdit) {
        tabVue.apiList(this.reloadChannelId > 0 ? this.reloadChannelId : this.channelId, this.page, '内容编辑成功！');
      } else {
        tabVue.apiList(this.channelId, this.page, '内容新增成功！', true);
      }
    }
    utils.removeTab();
    utils.openTab(this.tabName);
  },

  btnLayerClick: function(options) {
    var query = {
      siteId: this.siteId,
      channelId: this.channelId,
      editorAttributeName: 'Body'
    };

    if (options.contentId) {
      query.contentId = options.contentId;
    }
    if (options.attributeName) {
      query.attributeName = options.attributeName;
    }
    if (options.no) {
      query.no = options.no;
    }

    var args = {
      title: options.title,
      url: utils.getCommonUrl(options.name, query)
    };
    if (!options.full) {
      args.width = options.width ? options.width : 700;
      args.height = options.height ? options.height : 500;
    }

    utils.openLayer(args);
  },

  handleTranslationClose: function(summary) {
    this.translates = _.remove(this.translates, function(n) {
      return summary !== n.summary;
    });
  },

  btnSaveClick: function() {
    var $this = this;
    this.syncEditors();
    this.$refs.form.validate(function(valid) {
      if (valid) {
        if ($this.site.isAutoCheckKeywords && $this.isCensorTextEnabled) {
          $this.apiCensor(true);
        } else {
          $this.btnCensorSaveClick();
        }
      } else {
        utils.error('保存失败，请检查表单值是否正确');
      }
    });
  },

  btnCensorClick: function() {
    this.syncEditors();
    this.apiCensor(false);
  },

  btnTagsClick: function() {
    this.syncEditors();
    if (!this.form.body) return;
    this.apiTags();
  },

  btnPreviewClick: function() {
    var $this = this;
    if (this.isPreviewSaving) return;
    this.syncEditors();
    this.$refs.form.validate(function(valid) {
      if (valid) {
        $this.apiPreview();
      } else {
        utils.error('预览失败，请检查表单值是否正确');
      }
    });
  },

  btnCloseClick: function() {
    utils.removeTab();
  },

  btnGroupAddClick: function() {
    utils.openLayer({
      title: '新增内容组',
      url: utils.getCommonUrl('groupContentLayerAdd', {siteId: this.siteId}),
      width: 500,
      height: 300
    });
  },

  btnTranslateAddClick: function() {
    utils.openLayer({
      title: "选择转移栏目",
      url: utils.getCmsUrl('editorLayerTranslate', {
        siteId: this.siteId,
        channelId: this.channelId
      }),
      width: 620,
      height: 400
    });
  },

  btnExtendAddClick: function(style) {
    var no = this.form[utils.getCountName(style.attributeName)] + 1;
    this.form[utils.getCountName(style.attributeName)] = no;
    this.form[utils.getExtendName(style.attributeName, no)] = '';
    this.form = _.assign({}, this.form);
  },

  btnExtendRemoveClick: function(style) {
    var no = this.form[utils.getCountName(style.attributeName)];
    this.form[utils.getCountName(style.attributeName)] = no - 1;
    this.form[utils.getExtendName(style.attributeName, no)] = '';
    this.form = _.assign({}, this.form);
  },

  btnExtendPreviewClick: function(attributeName, no) {
    var count = this.form[utils.getCountName(attributeName)];
    var data = [];
    for (var i = 0; i <= count; i++) {
      var imageUrl = this.form[utils.getExtendName(attributeName, i)];
      imageUrl = utils.getUrl(this.siteUrl, imageUrl);
      data.push({
        "src": imageUrl
      });
    }
    layer.photos({
      photos: {
        "start": no,
        "data": data
      }
      ,anim: 5
    });
  }
};

var $vue = new Vue({
  el: "#main",
  data: data,
  methods: methods,
  created: function() {
    this.apiGet();
  }
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var join = require( 'path' ).join;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var contains = require( '@stdlib/assert/contains' );
var isJSON = require( '@stdlib/assert/is-json' );
var rtrim = require( '@stdlib/string/right-trim' );
var replace = require( '@stdlib/string/replace' );
var isObject = require( '@stdlib/assert/is-object' );
var isString = require( '@stdlib/assert/is-string' );
var hasOwn = require( '@stdlib/assert/has-own-property' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;
var dir = join( __dirname, 'fixtures' );
var before = replace( readFileSync( join( dir, 'before.txt' ), 'utf8' ), '\'', '"' );
var code = replace( readFileSync( join( dir, 'code.txt' ), 'utf8' ), '\'', '"' );
var codeAsync = replace( readFileSync( join( dir, 'code.async.txt' ), 'utf8' ), '\'', '"' );
var after = replace( readFileSync( join( dir, 'after.txt' ), 'utf8' ), '\'', '"' );

// FUNCTIONS //

/**
* Tests whether a value is a timing result object.
*
* @param {*} val - input value
* @returns {boolean} boolean indicating whether a value is a timing result
*/
function isResultsObject( val ) {
	return (
		isObject( val ) &&
		hasOwn( val, 'iterations' ) &&
		hasOwn( val, 'repeats' ) &&
		hasOwn( val, 'min' ) &&
		hasOwn( val, 'elapsed' ) &&
		hasOwn( val, 'rate' ) &&
		hasOwn( val, 'times' )
	);
} // end FUNCTION isResultsObject()

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing an asynchronous code snippet (json)', opts, function test( t ) {
	var cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \'var x = Math.pow( Math.random(), 3 ); setTimeout( next, 0 );\'; process.argv[ 3 ] = \'--format=json\'; process.argv[ 4 ] = \'--async\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (pretty)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=pretty\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = stdout.toString();
			t.strictEqual( isString( results ), true, 'prints pretty-printed result to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (csv)', opts, function test( t ) {
	var before;
	var header;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=csv\'; require( \''+fpath+'\' );"'
	];

	// Column names:
	header = 'seconds,nanoseconds';

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = stdout.toString();
			t.strictEqual( contains( results, header ), true, 'prints csv to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json, iterations)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; process.argv[ 5 ] = \'--iterations=1000\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( results.iterations, 1000, 'expected number of iterations' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json, repeats)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; process.argv[ 5 ] = \'--repeats=5\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( results.repeats, 5, 'expected number of repetitions' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports use as a standard stream', opts, function test( t ) {
	var cmd = [
		'echo -n \''+code+'\'',
		'|',
		process.execPath,
		fpath,
		'--before \''+before+'\'',
		'--after \''+after+'\'',
		'--format json'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var str;
		if ( error ) {
			t.fail( error.message );
		} else {
			str = rtrim( stdout.toString() );
			t.strictEqual( isJSON( str ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports use as a standard stream (asynchronous code snippet)', opts, function test( t ) {
	var cmd = [
		'echo -n \''+codeAsync+'\'',
		'|',
		process.execPath,
		fpath,
		'--format json',
		'--async',
		'--iteration=10',
		'--repeats=2'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var str;
		if ( error ) {
			t.fail( error.message );
		} else {
			str = rtrim( stdout.toString() );
			t.strictEqual( isJSON( str ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});
<commit_msg>Add missing private annotation<commit_after>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var join = require( 'path' ).join;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var contains = require( '@stdlib/assert/contains' );
var isJSON = require( '@stdlib/assert/is-json' );
var rtrim = require( '@stdlib/string/right-trim' );
var replace = require( '@stdlib/string/replace' );
var isObject = require( '@stdlib/assert/is-object' );
var isString = require( '@stdlib/assert/is-string' );
var hasOwn = require( '@stdlib/assert/has-own-property' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;
var dir = join( __dirname, 'fixtures' );
var before = replace( readFileSync( join( dir, 'before.txt' ), 'utf8' ), '\'', '"' );
var code = replace( readFileSync( join( dir, 'code.txt' ), 'utf8' ), '\'', '"' );
var codeAsync = replace( readFileSync( join( dir, 'code.async.txt' ), 'utf8' ), '\'', '"' );
var after = replace( readFileSync( join( dir, 'after.txt' ), 'utf8' ), '\'', '"' );

// FUNCTIONS //

/**
* Tests whether a value is a timing result object.
*
* @private
* @param {*} val - input value
* @returns {boolean} boolean indicating whether a value is a timing result
*/
function isResultsObject( val ) {
	return (
		isObject( val ) &&
		hasOwn( val, 'iterations' ) &&
		hasOwn( val, 'repeats' ) &&
		hasOwn( val, 'min' ) &&
		hasOwn( val, 'elapsed' ) &&
		hasOwn( val, 'rate' ) &&
		hasOwn( val, 'times' )
	);
} // end FUNCTION isResultsObject()

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing an asynchronous code snippet (json)', opts, function test( t ) {
	var cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \'var x = Math.pow( Math.random(), 3 ); setTimeout( next, 0 );\'; process.argv[ 3 ] = \'--format=json\'; process.argv[ 4 ] = \'--async\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (pretty)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=pretty\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = stdout.toString();
			t.strictEqual( isString( results ), true, 'prints pretty-printed result to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (csv)', opts, function test( t ) {
	var before;
	var header;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=csv\'; require( \''+fpath+'\' );"'
	];

	// Column names:
	header = 'seconds,nanoseconds';

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = stdout.toString();
			t.strictEqual( contains( results, header ), true, 'prints csv to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json, iterations)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; process.argv[ 5 ] = \'--iterations=1000\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( results.iterations, 1000, 'expected number of iterations' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints the results of timing a code snippet (json, repeats)', opts, function test( t ) {
	var before;
	var code;
	var cmd;

	before = 'var x = 12;';
	code = 'var y = x*x;';

	cmd = [
		process.execPath,
		'-e',
		'"process.stdin.isTTY = true; process.argv[ 2 ] = \''+code+'\'; process.argv[ 3 ] = \'--before='+before+'\'; process.argv[ 4 ] = \'--format=json\'; process.argv[ 5 ] = \'--repeats=5\'; require( \''+fpath+'\' );"'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var results;
		if ( error ) {
			t.fail( error.message );
		} else {
			results = JSON.parse( stdout.toString() );
			t.strictEqual( isResultsObject( results ), true, 'prints results to `stdout`' );
			t.strictEqual( results.repeats, 5, 'expected number of repetitions' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports use as a standard stream', opts, function test( t ) {
	var cmd = [
		'echo -n \''+code+'\'',
		'|',
		process.execPath,
		fpath,
		'--before \''+before+'\'',
		'--after \''+after+'\'',
		'--format json'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var str;
		if ( error ) {
			t.fail( error.message );
		} else {
			str = rtrim( stdout.toString() );
			t.strictEqual( isJSON( str ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports use as a standard stream (asynchronous code snippet)', opts, function test( t ) {
	var cmd = [
		'echo -n \''+codeAsync+'\'',
		'|',
		process.execPath,
		fpath,
		'--format json',
		'--async',
		'--iteration=10',
		'--repeats=2'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var str;
		if ( error ) {
			t.fail( error.message );
		} else {
			str = rtrim( stdout.toString() );
			t.strictEqual( isJSON( str ), true, 'prints results to `stdout`' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});
<|endoftext|>


<commit_before>// OS Monitoring for Node.js

// Copyright (c) 2012-2015 lfortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    stream   = require('readable-stream'),
    _        = require('underscore'),
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0,
      uptime    : 0,
      silent    : false,
      stream    : false,
      immediate : false
    };

// constructor
var Monitor = function() {

  stream.Readable.call(this, {highWaterMark: 102400});

  this._monitorState = {
    running: false,
    ended: false,
    streamBuffering: true,
    interval: undefined,
    config: _.clone(defaults)
  };
};

util.inherits(Monitor, stream.Readable);

Monitor.prototype.version = '1.0.4';

// readable stream implementation requirement
Monitor.prototype._read = function() {
  this._monitorState.streamBuffering = true;
};

Monitor.prototype.sendEvent = function(event, obj) {

  var eventObject = _.extend({timestamp: Math.floor(_.now() / 1000)}, obj);

  // for EventEmitter
  this.emit(event, eventObject);
  // for readable Stream
  if(this.config().stream && this._monitorState.streamBuffering) {
    var prettyJSON = os.EOL + JSON.stringify(eventObject, null, 2);
    if( !this.push(new Buffer(prettyJSON)) ) {
      this._monitorState.streamBuffering = false;
    }
  }
};

Monitor.prototype.start = function(options) {

  var self = this;

  if(this._isEnded()) {
    throw new Error("monitor has been ended by .destroy() method");
  }

  self.stop()
      .config(options);

  var cycle = function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    config = self.config(),
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    if(!config.silent) {
      self.sendEvent('monitor', _.extend({type: 'monitor'}, info));
    }
    if(info.loadavg[0] > config.critical1) {
      self.sendEvent('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.sendEvent('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.sendEvent('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.sendEvent('freemem', _.extend({type: 'freemem'}, info));
    }
    if(Number(config.uptime) && info.uptime > Number(config.uptime)) {
      self.sendEvent('uptime', _.extend({type: 'uptime'}, info));
    }
  };

  if(self.config().immediate) {
    process.nextTick(cycle);
  }
  self._monitorState.interval = setInterval(cycle, self.config().delay);

  if(!self.isRunning()) {
    self._monitorState.running = true;
    self.sendEvent('start', {type: 'start'});
  }

  return self;
};

Monitor.prototype.stop = function() {

  clearInterval(this._monitorState.interval);

  if(this.isRunning()) {
    this._monitorState.running = false;
    this.sendEvent('stop', {type: 'stop'});
  }

  return this;
};

Monitor.prototype.reset = function() {
  this.sendEvent('reset', {type: 'reset'});
  this[this.isRunning() ? 'start' : 'config'](_.clone(defaults));
  return this;
};

Monitor.prototype.destroy = function() {

  if(!this._isEnded()) {
    this.sendEvent('destroy', {type: 'destroy'});
    this.stop();
    if(this instanceof stream.Readable) {
      this.emit('close');
      this.push(null);
    }
    this._monitorState.ended = true;
  }

  return this;
};

Monitor.prototype.config = function(options) {

  if(_.isObject(options)) {
    _.extend(this._monitorState.config, options);
    this.sendEvent('config', {
                               type: 'config',
                               options: _.clone(options)
                             });
  }

  return this._monitorState.config;
};

Monitor.prototype.isRunning = function() {
  return !!this._monitorState.running;
};

Monitor.prototype._isEnded = function() {
  return !!this._monitorState.ended;
};

Monitor.prototype.throttle = function(event, handler, wait) {
  var self     = this,
      _handler = _.wrap(handler, function(fn) {
                   if(self.isRunning()) {
                     fn.apply(this, _.toArray(arguments).slice(1));
                   }
                 });
  return self.on.call(self, event, _.throttle(_handler, wait || self.config().throttle));
};

/*
 * convenience methods
 */

Monitor.prototype._sanitizeNumber = function(n) {
  if(!_.isNumber(n)) {
    throw new Error("Number expected");
  }
  if(!n || n < 0) {
    throw new Error("Number must be greater than 0");
  }
  // Math.pow(2, 31);
  if(n >= 2147483648) {
    throw new Error("Number must be smaller than 2147483648");
  }
  return n;
};

Monitor.prototype.seconds = function(n) {
  return this._sanitizeNumber(n * 1000);
};

Monitor.prototype.minutes = function(n) {
  return this._sanitizeNumber(n * this.seconds(60));
};

Monitor.prototype.hours = function(n) {
  return this._sanitizeNumber(n * this.minutes(60));
};

Monitor.prototype.days = function(n) {
  return this._sanitizeNumber(n * this.hours(24));
};

// expose OS module
Monitor.prototype.os = os;

// expose Underscore
Monitor.prototype._ = _;

// expose main class
Monitor.prototype.Monitor = Monitor;

module.exports = new Monitor();

<commit_msg>don't use Buffer when pushing data to stream<commit_after>// OS Monitoring for Node.js

// Copyright (c) 2012-2015 lfortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var util     = require('util'),
    os       = require('os'),
    stream   = require('readable-stream'),
    _        = require('underscore'),
    critical = os.cpus().length,
    defaults = {
      delay     : 3000,
      critical1 : critical,
      critical5 : critical,
      critical15: critical,
      freemem   : 0,
      uptime    : 0,
      silent    : false,
      stream    : false,
      immediate : false
    };

// constructor
var Monitor = function() {

  stream.Readable.call(this, {highWaterMark: 102400});

  this._monitorState = {
    running: false,
    ended: false,
    streamBuffering: true,
    interval: undefined,
    config: _.clone(defaults)
  };
};

util.inherits(Monitor, stream.Readable);

Monitor.prototype.version = '1.0.4';

// readable stream implementation requirement
Monitor.prototype._read = function() {
  this._monitorState.streamBuffering = true;
};

Monitor.prototype.sendEvent = function(event, obj) {

  var eventObject = _.extend({timestamp: Math.floor(_.now() / 1000)}, obj);

  // for EventEmitter
  this.emit(event, eventObject);
  // for readable Stream
  if(this.config().stream && this._monitorState.streamBuffering) {
    var prettyJSON = os.EOL + JSON.stringify(eventObject, null, 2);
    if( !this.push(prettyJSON) ) {
      this._monitorState.streamBuffering = false;
    }
  }
};

Monitor.prototype.start = function(options) {

  var self = this;

  if(this._isEnded()) {
    throw new Error("monitor has been ended by .destroy() method");
  }

  self.stop()
      .config(options);

  var cycle = function() {
    var info = {
      loadavg  : os.loadavg(),
      uptime   : os.uptime(),
      freemem  : os.freemem(),
      totalmem : os.totalmem()
    },
    config = self.config(),
    freemem  = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem;

    if(!config.silent) {
      self.sendEvent('monitor', _.extend({type: 'monitor'}, info));
    }
    if(info.loadavg[0] > config.critical1) {
      self.sendEvent('loadavg1', _.extend({type: 'loadavg1'}, info));
    }
    if(info.loadavg[1] > config.critical5) {
      self.sendEvent('loadavg5', _.extend({type: 'loadavg5'}, info));
    }
    if(info.loadavg[2] > config.critical15) {
      self.sendEvent('loadavg15', _.extend({type: 'loadavg15'}, info));
    }
    if(info.freemem < freemem) {
      self.sendEvent('freemem', _.extend({type: 'freemem'}, info));
    }
    if(Number(config.uptime) && info.uptime > Number(config.uptime)) {
      self.sendEvent('uptime', _.extend({type: 'uptime'}, info));
    }
  };

  if(self.config().immediate) {
    process.nextTick(cycle);
  }
  self._monitorState.interval = setInterval(cycle, self.config().delay);

  if(!self.isRunning()) {
    self._monitorState.running = true;
    self.sendEvent('start', {type: 'start'});
  }

  return self;
};

Monitor.prototype.stop = function() {

  clearInterval(this._monitorState.interval);

  if(this.isRunning()) {
    this._monitorState.running = false;
    this.sendEvent('stop', {type: 'stop'});
  }

  return this;
};

Monitor.prototype.reset = function() {
  this.sendEvent('reset', {type: 'reset'});
  this[this.isRunning() ? 'start' : 'config'](_.clone(defaults));
  return this;
};

Monitor.prototype.destroy = function() {

  if(!this._isEnded()) {
    this.sendEvent('destroy', {type: 'destroy'});
    this.stop();
    if(this instanceof stream.Readable) {
      this.emit('close');
      this.push(null);
    }
    this._monitorState.ended = true;
  }

  return this;
};

Monitor.prototype.config = function(options) {

  if(_.isObject(options)) {
    _.extend(this._monitorState.config, options);
    this.sendEvent('config', {
                               type: 'config',
                               options: _.clone(options)
                             });
  }

  return this._monitorState.config;
};

Monitor.prototype.isRunning = function() {
  return !!this._monitorState.running;
};

Monitor.prototype._isEnded = function() {
  return !!this._monitorState.ended;
};

Monitor.prototype.throttle = function(event, handler, wait) {
  var self     = this,
      _handler = _.wrap(handler, function(fn) {
                   if(self.isRunning()) {
                     fn.apply(this, _.toArray(arguments).slice(1));
                   }
                 });
  return self.on.call(self, event, _.throttle(_handler, wait || self.config().throttle));
};

/*
 * convenience methods
 */

Monitor.prototype._sanitizeNumber = function(n) {
  if(!_.isNumber(n)) {
    throw new Error("Number expected");
  }
  if(!n || n < 0) {
    throw new Error("Number must be greater than 0");
  }
  // Math.pow(2, 31);
  if(n >= 2147483648) {
    throw new Error("Number must be smaller than 2147483648");
  }
  return n;
};

Monitor.prototype.seconds = function(n) {
  return this._sanitizeNumber(n * 1000);
};

Monitor.prototype.minutes = function(n) {
  return this._sanitizeNumber(n * this.seconds(60));
};

Monitor.prototype.hours = function(n) {
  return this._sanitizeNumber(n * this.minutes(60));
};

Monitor.prototype.days = function(n) {
  return this._sanitizeNumber(n * this.hours(24));
};

// expose OS module
Monitor.prototype.os = os;

// expose Underscore
Monitor.prototype._ = _;

// expose main class
Monitor.prototype.Monitor = Monitor;

module.exports = new Monitor();

<|endoftext|>


<commit_before>
app.controller('AdminReportsController', ['$firebaseAuth','$http','$location', function ($firebaseAuth, $http, $location){
  var self = this;
  var auth = $firebaseAuth();
  var ctx = document.getElementById("myChart");
  var wardChart = [];
  var countChart = [];
  var allUsers = {list:[]};

  auth.$onAuthStateChanged(function(firebaseUser) {
   if (firebaseUser) {
     console.log('we are still logged in!');
     self.email = firebaseUser.email;
     // go reload idea data....
     getUserChart();
   } else {
     console.log('boooo');
     // redirect
     self.email = '';
    //  self.logout();
   }
  });

  function getUserChart() {
    var auth = $firebaseAuth();
    var firebaseUser = auth.$getAuth();
    if(firebaseUser){
      firebase.auth().currentUser.getToken().then(function(idToken) {
    $http({
      method: 'GET',
      url: '/admin/userChart',
      headers: {
        id_token: idToken
      }
    }).then(function(response) {
      for (var i = 0; i < response.data.length; i++) {
        wardChart.push(response.data[i].ward);
        countChart.push(response.data[i].count)
      }

      var data = {
        datasets: [{
          data:countChart
          // [11,16,7,3,14,17,2,11,17,9,2,1,7,8]
          ,
          backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB",
            "rgb(74, 236, 110)",
            "rgb(237, 60, 65)",
            "rgb(121, 22, 113)",
            "rgb(01, 12, 153)",
            "rgb(221, 22, 13)",
            "rgb(101, 312, 53)",
            "rgb(221, 133, 133)",
            "rgb(77, 12, 153)",
          ],
          label: 'My dataset' // for legend
        }],
        labels: wardChart
      }

      new Chart(ctx, {
        data: data,
        type: "bar",
        options: {
          // legend:{
          //   labels: generateLabels:{ function(data)
          // }},

          // },
          defaultFontSize:90,
          display: true,
          defaultFontSize: 44,
          fontSize:44,
          title: {
            display: true,
            fontSize:44,
            text: 'Wards Chart'
          },

          elements: {
            arc: {
              borderColor: "#000000"
            }
          }
        }
      });
    });
  });
  }
  }//end of getAllUsers()

  function getIdeaChart() {
    var auth = $firebaseAuth();
    var firebaseUser = auth.$getAuth();
    if(firebaseUser){
      firebase.auth().currentUser.getToken().then(function(idToken) {
    $http({
      method: 'GET',
      url: '/admin/ideaChart',
      headers: {
        id_token: idToken
      }
    }).then(function(response) {
      for (var i = 0; i < response.data.length; i++) {
        wardChart.push(response.data[i].ward);
        countChart.push(response.data[i].count)
      }

});
});
}
};

}]);
//CHRIS
<commit_msg>goin home<commit_after>
app.controller('AdminReportsController', ['$firebaseAuth','$http','$location', function ($firebaseAuth, $http, $location){
  var self = this;
  var auth = $firebaseAuth();
  var ctx = document.getElementById("myChart");
  var wardChart = [];
  var countChart = [];
  var allUsers = {list:[]};

  auth.$onAuthStateChanged(function(firebaseUser) {
   if (firebaseUser) {
     console.log('we are still logged in!');
     self.email = firebaseUser.email;
     // go reload idea data....
     getUserChart();
   } else {
     console.log('boooo');
     // redirect
     self.email = '';
    //  self.logout();
   }
  });

  function getUserChart() {
    var auth = $firebaseAuth();
    var firebaseUser = auth.$getAuth();
    if(firebaseUser){
      firebase.auth().currentUser.getToken().then(function(idToken) {
    $http({
      method: 'GET',
      url: '/admin/userChart',
      headers: {
        id_token: idToken
      }
    }).then(function(response) {
      for (var i = 0; i < response.data.length; i++) {
        wardChart.push(response.data[i].ward);
        countChart.push(response.data[i].count)
      }

      var data = {
        datasets: [{
          data:countChart
          // [11,16,7,3,14,17,2,11,17,9,2,1,7,8]
          ,
          backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB",
            "rgb(74, 236, 110)",
            "rgb(237, 60, 65)",
            "rgb(121, 22, 113)",
            "rgb(01, 12, 153)",
            "rgb(221, 22, 13)",
            "rgb(101, 312, 53)",
            "rgb(221, 133, 133)",
            "rgb(77, 12, 153)",
          ],
          label: 'My dataset' // for legend
        }],
        labels: wardChart
      }

      new Chart(ctx, {
        data: data,
        type: "bar",
        options: {
          // legend:{
          //   labels: generateLabels:{ function(data)
          // }},

          // },
          defaultFontSize:90,
          display: true,
          defaultFontSize: 44,
          fontSize:44,
          title: {
            display: true,
            fontSize:44,
            text: 'Wards Chart'
          },

          elements: {
            arc: {
              borderColor: "#000000"
            }
          }
        }
      });
    });
  });
  }
  }//end of getAllUsers()

  function getIdeaChart() {
    var auth = $firebaseAuth();
    var firebaseUser = auth.$getAuth();
    if(firebaseUser){
      firebase.auth().currentUser.getToken().then(function(idToken) {
    $http({
      method: 'GET',
      url: '/admin/ideaChart',
      headers: {
        id_token: idToken
      }
    }).then(function(response) {
      for (var i = 0; i < response.data.length; i++) {
        wardChart.push(response.data[i].ward);
        countChart.push(response.data[i].count)
      }

});
});
}
};

}]);
//CHRIS
<|endoftext|>