<commit_before>/*!
  Copyright (C) 2016 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

(function (GGRC, can) {
  'use strict';

/**
   * A component that takes care of adding comments with attachments
   *
   */
  GGRC.Components('addComment', {
    tag: 'add-comment',
    template: can.view('/static/mustache/base_templates/add_comment.mustache'),
    scope: {
      attachments: new can.List(),
      parent_instance: null,
      instance: null,
      instance_attr: '@',
      source_mapping: null,
      source_mapping_source: '@',
      mapping: '@',
      deferred: '@',
      isSaving: false,  // is there a save operation currently in progress
      attributes: {},
      list: [],
      // the following are just for the case when we have no object to start with,
      changes: [],
      removePending: function (scope, el, ev) {
        var joins = this.instance._pending_joins;
        var model = scope.what;
        var index = _.findIndex(joins.serialize(), function (join) {
          return join.what.id === model.id &&
            join.what.type === model.type;
        });

        model.refresh().then(function () {
          model.destroy();
          joins.splice(index, 1);
        });
      },
      get_assignee_type: can.compute(function () {
        // TODO: We prioritize order V > A > R
        var types = {
          related_verifiers: 'verifier',
          related_assignees: 'assignee',
          related_requesters: 'requester',
          related_creators: 'creator'
        };
        var instance = this.attr('parent_instance');
        var user = GGRC.current_user;
        var user_type;

        if (!instance || !user) {
          return;
        }
        _.each(types, function (type, mapping) {
          var mappings = instance.get_mapping(mapping);
          if (!mappings.length) {
            return;
          }
          if (_.filter(mappings, function (mapping) {
            return mapping.instance.id === user.id;
          }).length) {
            type = can.capitalize(type);
            user_type = user_type ? (user_type + ',' + type) : type;
          }
        });
        return user_type;
      })
    },
    events: {
      init: function () {
        if (!this.scope.attr('source_mapping')) {
          this.scope.attr('source_mapping', GGRC.page_instance());
        }
        this.newInstance();
      },
      newInstance: function () {
        var instance = CMS.Models.Comment();
        instance._source_mapping = this.scope.attr('source_mapping');
        instance.attr('context', this.scope.attr('parent_instance.context'));
        this.scope.attr('instance', instance);
      },
      cleanPanel: function () {
        this.scope.attachments.replace([]);
        this.element.find('textarea').val('');
      },
      /**
       * The component's click event (happens when the user clicks add comment),
       * takes care of saving the comment with appended evidence.
       */
      '.btn-success click': function (el, ev) {
        var $textarea = this.element.find('.add-comment textarea');
        var description = $.trim($textarea.val());
        var attachments = this.scope.attachments;
        var source = this.scope.source_mapping;
        var instance = this.scope.instance;
        var data;
        var $sendNotification = this.element.find('[name=send_notification]');
        var sendNotification = $sendNotification[0].checked;

        if (!description.length && !attachments.length) {
          return;
        }
        data = {
          description: description,
          send_notification: sendNotification,
          context: source.context,
          assignee_type: this.scope.attr('get_assignee_type')
        };

        this.scope.attr('isSaving', true);

        instance.attr(data).save()
          .then(function () {
            return instance.constructor.resolve_deferred_bindings(instance);
          })
          .then(function () {
            this.newInstance();
            this.cleanPanel();
          }.bind(this))
          .always(function () {
            this.scope.attr('isSaving', false);
          }.bind(this));
      }
    }
  });
})(window.GGRC, window.can);
<commit_msg>Add Assessor to the comment role list<commit_after>/*!
  Copyright (C) 2016 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

(function (GGRC, can) {
  'use strict';

/**
   * A component that takes care of adding comments with attachments
   *
   */
  GGRC.Components('addComment', {
    tag: 'add-comment',
    template: can.view('/static/mustache/base_templates/add_comment.mustache'),
    scope: {
      attachments: new can.List(),
      parent_instance: null,
      instance: null,
      instance_attr: '@',
      source_mapping: null,
      source_mapping_source: '@',
      mapping: '@',
      deferred: '@',
      isSaving: false,  // is there a save operation currently in progress
      attributes: {},
      list: [],
      // the following are just for the case when we have no object to start with,
      changes: [],
      removePending: function (scope, el, ev) {
        var joins = this.instance._pending_joins;
        var model = scope.what;
        var index = _.findIndex(joins.serialize(), function (join) {
          return join.what.id === model.id &&
            join.what.type === model.type;
        });

        model.refresh().then(function () {
          model.destroy();
          joins.splice(index, 1);
        });
      },
      get_assignee_type: can.compute(function () {
        // TODO: We prioritize order V > A > R
        var types = {
          related_verifiers: 'verifier',
          related_assessors: 'assessor',
          related_assignees: 'assignee',
          related_requesters: 'requester',
          related_creators: 'creator'
        };
        var instance = this.attr('parent_instance');
        var user = GGRC.current_user;
        var user_type;

        if (!instance || !user) {
          return;
        }
        _.each(types, function (type, mapping) {
          var mappings = instance.get_mapping(mapping);
          if (!mappings.length) {
            return;
          }
          if (_.filter(mappings, function (mapping) {
            return mapping.instance.id === user.id;
          }).length) {
            type = can.capitalize(type);
            user_type = user_type ? (user_type + ',' + type) : type;
          }
        });
        return user_type;
      })
    },
    events: {
      init: function () {
        if (!this.scope.attr('source_mapping')) {
          this.scope.attr('source_mapping', GGRC.page_instance());
        }
        this.newInstance();
      },
      newInstance: function () {
        var instance = CMS.Models.Comment();
        instance._source_mapping = this.scope.attr('source_mapping');
        instance.attr('context', this.scope.attr('parent_instance.context'));
        this.scope.attr('instance', instance);
      },
      cleanPanel: function () {
        this.scope.attachments.replace([]);
        this.element.find('textarea').val('');
      },
      /**
       * The component's click event (happens when the user clicks add comment),
       * takes care of saving the comment with appended evidence.
       */
      '.btn-success click': function (el, ev) {
        var $textarea = this.element.find('.add-comment textarea');
        var description = $.trim($textarea.val());
        var attachments = this.scope.attachments;
        var source = this.scope.source_mapping;
        var instance = this.scope.instance;
        var data;
        var $sendNotification = this.element.find('[name=send_notification]');
        var sendNotification = $sendNotification[0].checked;

        if (!description.length && !attachments.length) {
          return;
        }
        data = {
          description: description,
          send_notification: sendNotification,
          context: source.context,
          assignee_type: this.scope.attr('get_assignee_type')
        };

        this.scope.attr('isSaving', true);

        instance.attr(data).save()
          .then(function () {
            return instance.constructor.resolve_deferred_bindings(instance);
          })
          .then(function () {
            this.newInstance();
            this.cleanPanel();
          }.bind(this))
          .always(function () {
            this.scope.attr('isSaving', false);
          }.bind(this));
      }
    }
  });
})(window.GGRC, window.can);
<|endoftext|>


<commit_before>{
    "tpls":[],
    "filelist":[
        "/js/react/browser.min.js",
        "/js/react/react.min.js",
        "/js/react/react-dom.min.js"
      ]
}
<commit_msg>Update react.js<commit_after>{
    "tpls":["/jsx/hw.jsx"],
    "filelist":[
        "/js/react/browser.min.js",
        "/js/react/react.min.js",
        "/js/react/react-dom.min.js"
      ]
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var webpack = require('webpack');

// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();

// **Little Hacky**: Infer the filename and library name from the package name.
//
// Assumptions:
// - `package.json`'s `name` field is name of dist files.
// - PascalCased version of that name is exported class name.
var PKG = require(path.join(ROOT, 'package.json'));
var libPath = (PKG.name || '').toLowerCase();
if (!libPath) { throw new Error('Need package.json:name field'); }
// PascalCase (with first character capitalized).
var libName = libPath
  .replace(/^\s+|\s+$/g, '')
  .replace(/(^|[-_ ])+(.)/g, function(match, first, second) {
    // Second match group is the character we want to change. Throw away first.
    return second.toUpperCase();
  });

module.exports = {
  cache: true,
  entry: path.join(ROOT, 'src/index.js'),
  externals: [
    {
      'react': {
        root: 'React',
        commonjs2: 'react',
        commonjs: 'react',
        amd: 'react'
      }
    }
  ],
  output: {
    path: path.join(ROOT, 'dist'),
    filename: libPath + '.min.js',
    library: libName,
    libraryTarget: 'umd'
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        // **Note**: Cannot use shorthand `'babel-loader'` or `'babel'` when
        // we are playing around with `NODE_PATH` in builder. Manually
        // resolve path.
        loader: require.resolve('babel-loader'),
        query: {
          babelrc: false,
          presets: ['es2015-webpack', 'stage-2', 'react'],
          plugins: [
            'syntax-class-properties',
            'syntax-decorators',
            'transform-class-properties',
            'transform-decorators-legacy'
          ]
        }
      }, {
        test: /\.css$/,
        loader: require.resolve('style-loader') + '!' + require.resolve('css-loader')
      }, {
        test: /\.(png|jpg)$/,
        loader: require.resolve('url-loader') + '?limit=8192'
      }
    ]
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      // Signal production, so that webpack removes non-production code that
      // is in condtionals like: `if (process.env.NODE_ENV === 'production')`
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.SourceMapDevToolPlugin({filename: '[file].map'})
  ]
};
<commit_msg>Match webpack config of builder-victory-component<commit_after>'use strict';

var path = require('path');
var webpack = require('webpack');

// Replace with `__dirname` if using in project root.
var ROOT = process.cwd();
var SRC = path.join(ROOT, "src");

// **Little Hacky**: Infer the filename and library name from the package name.
//
// Assumptions:
// - `package.json`'s `name` field is name of dist files.
// - PascalCased version of that name is exported class name.
var PKG = require(path.join(ROOT, 'package.json'));
var libPath = (PKG.name || '').toLowerCase();
if (!libPath) { throw new Error('Need package.json:name field'); }
// PascalCase (with first character capitalized).
var libName = libPath
  .replace(/^\s+|\s+$/g, '')
  .replace(/(^|[-_ ])+(.)/g, function(match, first, second) {
    // Second match group is the character we want to change. Throw away first.
    return second.toUpperCase();
  });

module.exports = {
  cache: true,
  context: SRC,
  entry: path.join(ROOT, 'src/index.js'),
  externals: [
    {
      'react': {
        root: 'React',
        commonjs2: 'react',
        commonjs: 'react',
        amd: 'react'
      }
    }
  ],
  output: {
    path: path.join(ROOT, 'dist'),
    filename: libPath + '.min.js',
    library: libName,
    libraryTarget: 'umd'
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        // Use include specifically of our sources.
        // Do _not_ use an `exclude` here.
        include: [SRC],
        // **Note**: Cannot use shorthand `'babel-loader'` or `'babel'` when
        // we are playing around with `NODE_PATH` in builder. Manually
        // resolve path.
        loader: require.resolve('babel-loader'),
      }, {
        test: /\.css$/,
        loader: require.resolve('style-loader') + '!' + require.resolve('css-loader')
      }, {
        test: /\.(png|jpg)$/,
        loader: require.resolve('url-loader') + '?limit=8192'
      }
    ]
  },
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      // Signal production, so that webpack removes non-production code that
      // is in condtionals like: `if (process.env.NODE_ENV === "production")`
      "process.env.NODE_ENV": JSON.stringify("production")
    }),
    new webpack.SourceMapDevToolPlugin({filename: "[file].map"})
  ]
};
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2018-2021 Camptocamp SA
//
// 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.

module.exports = {
  entry: {
    desktop: './contribs/gmf/apps/desktop_alt/Controller.js',
    mobile: './contribs/gmf/apps/mobile/Controller.js',
    iframe_api: './contribs/gmf/apps/iframe_api/Controller.js',
  },
};
<commit_msg>Fix public path<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2018-2021 Camptocamp SA
//
// 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.

module.exports = {
  entry: {
    desktop: './contribs/gmf/apps/desktop_alt/Controller.js',
    mobile: './contribs/gmf/apps/mobile/Controller.js',
    iframe_api: './contribs/gmf/apps/iframe_api/Controller.js',
  },
  output: {
    publicPath: 'auto',
  },
};
<|endoftext|>


<commit_before>const webpack = require('webpack');
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// This is very experimental library
// There might be another favourite react-refresh webpack plugin at some point ...
// See https://github.com/facebook/react/issues/16604 for discussion
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const { join } = require('path');

const shims = require('./webpack.shims');
const basedir = join(__dirname, '../..');

const config = require('../config');

const isDevelopment = process.env.NODE_ENV === 'development';
const isProduction = process.env.NODE_ENV === 'production';

const styleLoaders = [
  isProduction ? {
    loader: MiniCssExtractPlugin.loader
  } : {
    loader: 'style-loader'
  },
  {
    loader: 'css-loader',
    options: { importLoaders: 1 }
  },
  {
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: [
        require('autoprefixer')()
      ]
    }
  }
];

module.exports = merge(shims, {
  mode: isProduction ? 'production' : 'development',
  devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
  entry: require.resolve('./entries/main'),
  output: {
    path: join(basedir, 'public/assets'),
    publicPath: '/assets/'
  },
  devServer: {
    index: '',
    port: 3001,
    contentBase: false,
    publicPath: '/assets/',
    proxy: {
      context: () => true,
      target: 'http://localhost:3000'
    },
    overlay: {
      warnings: false,
      errors: true
    }
  },
  resolve: {
    alias: {
      '@': basedir,

      // These are (mainly) to use within less/css files
      'img': join(basedir, 'public/img'),
      'less': join(basedir, 'modules/core/client/less'),
      'modules': join(basedir, 'modules')
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                corejs: 2,
                modules: 'commonjs',
                useBuiltIns: 'usage'
              }],
              ['@babel/preset-react']
            ],
            plugins: [
              '@babel/plugin-proposal-object-rest-spread',
              'angularjs-annotate',
              ...(isDevelopment ? ['react-refresh/babel'] : [])
            ]
          }
        }]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          outputPath: 'fonts/'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: '[name]-[hash:7].[ext]',
              outputPath: 'images/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: styleLoaders
      },
      {
        test: /\.less$/,
        use: [
          ...styleLoaders,
          {
            loader: 'less-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    ...(isProduction ? [new MiniCssExtractPlugin({
      filename: 'main.css'
    })] : []),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'FCM_SENDER_ID': JSON.stringify(config.fcm.senderId)
    }),
    new ReactRefreshWebpackPlugin({
      disableRefreshCheck: true
    })
  ]
});
<commit_msg>Only use ReactRefreshWebpackPlugin in dev<commit_after>const webpack = require('webpack');
const merge = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// This is very experimental library
// There might be another favourite react-refresh webpack plugin at some point ...
// See https://github.com/facebook/react/issues/16604 for discussion
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');

const { join } = require('path');

const shims = require('./webpack.shims');
const basedir = join(__dirname, '../..');

const config = require('../config');

const isDevelopment = process.env.NODE_ENV === 'development';
const isProduction = process.env.NODE_ENV === 'production';

const ifDevelopment = (...items) => {
  return isDevelopment ? items : []
}

const ifProduction = (...items) => {
  return ifProduction ? items : []
}

const styleLoaders = [
  isProduction ? {
    loader: MiniCssExtractPlugin.loader
  } : {
    loader: 'style-loader'
  },
  {
    loader: 'css-loader',
    options: { importLoaders: 1 }
  },
  {
    loader: 'postcss-loader',
    options: {
      ident: 'postcss',
      plugins: [
        require('autoprefixer')()
      ]
    }
  }
];

module.exports = merge(shims, {
  mode: isProduction ? 'production' : 'development',
  devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
  entry: require.resolve('./entries/main'),
  output: {
    path: join(basedir, 'public/assets'),
    publicPath: '/assets/'
  },
  devServer: {
    index: '',
    port: 3001,
    contentBase: false,
    publicPath: '/assets/',
    proxy: {
      context: () => true,
      target: 'http://localhost:3000'
    },
    overlay: {
      warnings: false,
      errors: true
    }
  },
  resolve: {
    alias: {
      '@': basedir,

      // These are (mainly) to use within less/css files
      'img': join(basedir, 'public/img'),
      'less': join(basedir, 'modules/core/client/less'),
      'modules': join(basedir, 'modules')
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                corejs: 2,
                modules: 'commonjs',
                useBuiltIns: 'usage'
              }],
              ['@babel/preset-react']
            ],
            plugins: [
              '@babel/plugin-proposal-object-rest-spread',
              'angularjs-annotate',
              ...ifDevelopment('react-refresh/babel')
            ]
          }
        }]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: '[name].[hash:7].[ext]',
          outputPath: 'fonts/'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: '[name]-[hash:7].[ext]',
              outputPath: 'images/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: styleLoaders
      },
      {
        test: /\.less$/,
        use: [
          ...styleLoaders,
          {
            loader: 'less-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    ...ifProduction(new MiniCssExtractPlugin({
      filename: 'main.css'
    })),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
      'FCM_SENDER_ID': JSON.stringify(config.fcm.senderId)
    }),
    ...ifDevelopment(new ReactRefreshWebpackPlugin({
      disableRefreshCheck: true
    }))
  ]
});
<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template) {

    $scope.selected = [];
    $scope.checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    $scope.feedback_status = function(feed) {
        //this sends a signal to CheckyBox
        var current = {
            id: feed.id
          , catid: Template.default_category_id
          , status: feed.status
          , origin: Template.current_inbox_state
        }

        FeedbackSignal.current_state(current);

        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.change_category = function(feedid, catid) {
        console.log("Feedback: " + feedid + " CatID: " + catid);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            for(var i=0; i < $scope.selected.length; i++) {

                var entity = $(".dashboard-feedback[feedback=" + $scope.selected[i] + "]");
                var entity_parent = $(entity).parents('.feedback-group');

                entity.hide();

                var child_count = entity_parent.children('.dashboard-feedback:visible');

                if(child_count.length == 0) {
                    entity_parent.hide();
                }

                if( $(".feed-checkbox[value=" + $scope.selected[i] + "]").is(":checked") ) {
                    $(".feed-checkbox[value=" + $scope.selected[i] + "]").click();
                }
            }

            var feed = {
                id: $scope.selected
              , status: $scope.status_select_value
              , catid: Template.default_category_id
              , origin: Template.current_inbox_state
            }

            FeedbackSignal.current_state(feed);
            FeedbackControlService.change_status(feed, true);
            $scope.selected = [];

            $(".checky-box-container").show();
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < $scope.checkboxes.length; i++) {

            var entity = $scope.checkboxes[i];
            var myparent = $(entity).parents('.dashboard-feedback');
            var score = myparent.attr('score');
            var permission = myparent.attr('permission');
            var mode = $scope.status_select_value;

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!$(entity).is(":checked")) {
                    $(entity).click();
                }
            } else {
                $(entity).click();
            }

            console.log(mode);

            if(score >= 3 && permission == 1) {
                update_selected(action, parseInt($(entity).val(), 10));
            }
        }
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<commit_msg>bitch mother<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template) {

    $scope.selected = [];
    $scope.checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    $scope.feedback_status = function(feed) {
        //this sends a signal to CheckyBox
        var current = {
            id: feed.id
          , catid: Template.default_category_id
          , status: feed.status
          , origin: Template.current_inbox_state
        }

        FeedbackSignal.current_state(current);

        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.reply_feedback = function(id) {
        console.log("reply id:" + id);
    }

    $scope.change_category = function(feedid, catid) {
        console.log("Feedback: " + feedid + " CatID: " + catid);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            for(var i=0; i < $scope.selected.length; i++) {

                var entity = $(".dashboard-feedback[feedback=" + $scope.selected[i] + "]");
                var entity_parent = $(entity).parents('.feedback-group');
                var mode = $scope.status_select_value;
                var score = entity_parent.attr('score');
                var permission = entity_parent.attr('permission');

                if(   (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {
                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    if( $(".feed-checkbox[value=" + $scope.selected[i] + "]").is(":checked") ) {
                        $(".feed-checkbox[value=" + $scope.selected[i] + "]").click();
                    }
                }
            }

            var feed = {
                id: $scope.selected
              , status: $scope.status_select_value
              , catid: Template.default_category_id
              , origin: Template.current_inbox_state
            }

            FeedbackSignal.current_state(feed);
            FeedbackControlService.change_status(feed, true);
            $scope.selected = [];

            $(".checky-box-container").show();
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < $scope.checkboxes.length; i++) {

            var entity = $scope.checkboxes[i];
            var myparent = $(entity).parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!$(entity).is(":checked")) {
                    $(entity).click();
                }
            } else {
                $(entity).click();
            }

            update_selected(action, parseInt($(entity).val(), 10));
        }
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';

let App;

Ember.MODEL_FACTORY_INJECTIONS = true;

App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<commit_msg>Fixed deprecation warning<commit_after>import Ember from 'ember';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';

let App;

App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;
<|endoftext|>


<commit_before>'use strict';

angular.module('brewApp.controllers')
	.controller('NavSidebarCtrl', navSidebarController);

function navSidebarController() {
	/* jshint validthis: true */
	var self = this;

	self.actions = [{
			title: 'Enter a new recipe',
			url: '/recipe'
		}
	]
}<commit_msg>Added placeholder for other nav bar actions.<commit_after>'use strict';

angular.module('brewApp.controllers')
	.controller('NavSidebarCtrl', ['notifications', navSidebarController]);

function navSidebarController(notifications) {
	/* jshint validthis: true */
	var self = this;

	self.actions = [{
			title: 'Enter a new recipe',
			url: '/recipe'
		}, {
			title: 'My recipes',
			click: function() {
				notifications.error('Eat a johnson.')
			}
		}, {
			title: 'Saved recipes',
			click: function() {
				notifications.error('Farkled it up, Farkleton.')
			}
		}
	]
}<|endoftext|>


<commit_before>import Head from "next/head";
import Link from "next/link";
import { getPage } from "../../lib/lib";
import { join } from "path";
import Meta from "../../components/Meta";
import Container from "../../components/Container";
import SingleColumn from "../../components/SingleColumn";
import ErrorPage from "../404";
import Section from "../../components/Section";
import ob from "urbit-ob";
import { decode } from "html-entities";
import Markdown from "../../components/Markdown";
import Sigil from "../../components/Sigil";
import axios from "axios";

const IdPage = ({ data, markdown, network, params }) => {
  const { id } = params;
  if (!ob.isValidPatp(id)) {
    return <ErrorPage />;
  }

  const parent = network ? network.sponsor["urbit-id"] : ob.sein(id);
  const galaxy =
    ob.clan(id) === "planet"
      ? network?.sponsor?.sponsor?.["urbit-id"] || ob.sein(parent)
      : null;

  return (
    <Container>

        <title>{id} • Urbit ID • urbit.org</title>
        {Meta(data)}

      <SingleColumn>

            {/* Avatar or sigil */}
            {data.image ? (

            ) : (

                <Sigil patp={id} size={100} />

            )}

{id}

Urbit ID

ID Type

                {ob.clan(id).slice(0, 1).toUpperCase() + ob.clan(id).slice(1)}

Status

                {network ? "Spawned/Owned" : "Unspawned"}

Parent

              <Link href={`/id/${parent}`}>
                {parent}
              </Link>

            {galaxy && (

Galaxy

                <Link href={`/id/${galaxy}`}>
                  {galaxy}
                </Link>

            )}

          {(data.description !== "An Urbit ID." || markdown) && (

Description

              {markdown ? (

              ) : (

{data.description}

              )}

          )}

              Urbit is a clean-slate, peer-to-peer operating system and network.

                Learn how get your own Urbit ID.

              {/* TODO: Joining groups guide. */}
              <button className="button-lg max-w-xs bg-green-400 text-white">
                Get an Urbit ID
              </button>

Have an Urbit ID?

            {/* TODO Submission guide. */}

              Claim and customize your Urbit.org page

          <Link href="/">
            Urbit.org
          </Link>

      </SingleColumn>
    </Container>
  );
};

export const getServerSideProps = async ({ params }) => {
  let { data, content } = getPage(
    join(process.cwd(), "content/id/", params.id.slice(1))
  ) || { data: {}, content: "" };

  if (!data.ship && ob.isValidPatp(params.id)) {
    data = { ship: params.id, description: "An Urbit ID." };
  }

  let network = await axios
    .get(
      `https://mt2aga2c5l.execute-api.us-east-2.amazonaws.com/get-node?urbit-id=${
        ob.isValidPatp(params.id) ? params.id : "~zod"
      }`
    )
    .then((res) => res.data);

  const markdown = await Markdown({ post: { content: content } }, true);

  return {
    props: {
      data,
      markdown,
      network,
      params,
    },
  };
};

export default IdPage;
<commit_msg>id: hide parent on galaxy pages<commit_after>import Head from "next/head";
import Link from "next/link";
import { getPage } from "../../lib/lib";
import { join } from "path";
import Meta from "../../components/Meta";
import Container from "../../components/Container";
import SingleColumn from "../../components/SingleColumn";
import ErrorPage from "../404";
import Section from "../../components/Section";
import ob from "urbit-ob";
import { decode } from "html-entities";
import Markdown from "../../components/Markdown";
import Sigil from "../../components/Sigil";
import axios from "axios";

const IdPage = ({ data, markdown, network, params }) => {
  const { id } = params;
  if (!ob.isValidPatp(id)) {
    return <ErrorPage />;
  }

  // Parent ID, grabbed from network or fallback to the default sponsor for that node
  const parent = network ? network.sponsor["urbit-id"] : ob.sein(id);
  // Galaxy name above that parent
  const galaxy =
    ob.clan(id) === "planet"
      ? network?.sponsor?.sponsor?.["urbit-id"] || ob.sein(parent)
      : null;
  // Galaxies shouldn't show parents, so store it as boolean here for reference.
  const isGalaxy = ob.clan(id) === "galaxy";

  return (
    <Container>

        <title>{id} • Urbit ID • urbit.org</title>
        {Meta(data)}

      <SingleColumn>

            {/* Avatar or sigil */}
            {data.image ? (

            ) : (

                <Sigil patp={id} size={100} />

            )}

{id}

Urbit ID

ID Type

                {ob.clan(id).slice(0, 1).toUpperCase() + ob.clan(id).slice(1)}

Status

                {network ? "Spawned/Owned" : "Unspawned"}

            {!isGalaxy && (

Parent

                <Link href={`/id/${parent}`}>
                  {parent}
                </Link>

            )}
            {galaxy && (

Galaxy

                <Link href={`/id/${galaxy}`}>
                  {galaxy}
                </Link>

            )}

          {(data.description !== "An Urbit ID." || markdown) && (

Description

              {markdown ? (

              ) : (

{data.description}

              )}

          )}

              Urbit is a clean-slate, peer-to-peer operating system and network.

                Learn how get your own Urbit ID.

              {/* TODO: Joining groups guide. */}
              <button className="button-lg max-w-xs bg-green-400 text-white">
                Get an Urbit ID
              </button>

Have an Urbit ID?

            {/* TODO Submission guide. */}

              Claim and customize your Urbit.org page

          <Link href="/">
            Urbit.org
          </Link>

      </SingleColumn>
    </Container>
  );
};

export const getServerSideProps = async ({ params }) => {
  let { data, content } = getPage(
    join(process.cwd(), "content/id/", params.id.slice(1))
  ) || { data: {}, content: "" };

  if (!data.ship && ob.isValidPatp(params.id)) {
    data = { ship: params.id, description: "An Urbit ID." };
  }

  let network = await axios
    .get(
      `https://mt2aga2c5l.execute-api.us-east-2.amazonaws.com/get-node?urbit-id=${
        ob.isValidPatp(params.id) ? params.id : "~zod"
      }`
    )
    .then((res) => res.data);

  const markdown = await Markdown({ post: { content: content } }, true);

  return {
    props: {
      data,
      markdown,
      network,
      params,
    },
  };
};

export default IdPage;
<|endoftext|>


<commit_before>/**
 * Retrieve stock market figures from google finance.
 *
 * @module stockGet
 *
 * @param  {String} stocksymbol
 * @return {object}

	name
	tickerSymbol
	exchange
	exchangeTimezone
	price
	priceChange
	priceChangePercent
	quoteTime
*/

//required modules
var cheerio = require('cheerio');
var https = require('https');

var baseurl="https://www.google.co.uk/finance?q=";

var timeoutProtect;

var stockGet = function() {};

//***********************************************************************
stockGet.prototype.url = function (query,callback) {
	callback(null,baseurl+query);
	return;
};
//***********************************************************************

//***********************************************************************
stockGet.prototype.query = function(symbol,attri,callback) {

	var req = https.request((baseurl+symbol), function(res){

		var body = "";

		//***********************************************
		res.setTimeout(4500, function(e){
			console.log("timed out");
			callback(new Error(e),null);
			return;
		});
		//***********************************************
		res.on('data', function (htmldata) {
			body += htmldata;

		});
		//***********************************************
		res.on('error', function() {
			console.log("sdfasfaf");
			req.abort();
			req.destroy();

			req.end();
			callback(new Error(e),null);

		});
		//***********************************************
	  	res.on('end', function() {
			//need statusCode of 200 otherwise we have an issue
			 //clearTimeout( timeout );
			if(res.statusCode !=200)
			{
				req.end();
	  			callback(new Error("error statusCode: " + res.statusCode + ""), null);
			}

// Proceed only if the timeout handler has not yet fired.
			if (timeoutProtect) {

			    // Clear the scheduled timeout handler
			    clearTimeout(timeoutProtect);
			}

	  		req.end();
	  		//manipulate DOM
			manDom(body);
		});
	});

function manDom(htmlbody)
{
	var $ = cheerio.load(htmlbody);
	var stockSymbol= {};
	if(attri=="all"){
		var k="";
		$(htmlbody).find('meta[itemprop]').each (function(){
		 	attrib = ($(this).attr('itemprop'));
		 	valuu = ($(this).attr('content'));
		 	stockSymbol[attrib] = valuu;
		 });
		callback(null,stockSymbol);
		return;
	}
	else //just return the one dom value
	{

//this below if seems to get called with all issues ? need more testing

		if($("meta[itemprop="+attri+"]").attr("content") === undefined)
		{
			//console.log("Error: missing parameters, attribute is " +attri+".");
			//dlog("error ´"+attri+"´ not found - callbacking with error");
			if(callback){
				callback(new Error("Missing Attribute ´"+attri + "´ for Symbol ´" + symbol +"´."),null);
			}
			else
			{
				console.log("Missing Attribute ´"+attri + "´ for Symbol ´" + symbol +"´.");
				return;
			}

		}
		else
		{
			var stockSymbol= {};
			stockSymbol[attri] = $("meta[itemprop="+attri+"]").attr("content");

			//success - pass back data to callback.
			callback(null,stockSymbol);
			return;
		}
	}
} //end function
//*****************************************************

	req.on('error', function(e) {
	  	//console.error(e);
	  	console.log("error req on");
	  	req.abort();
	  	req.destroy();
		req.end();

	  	callback(new Error("ss " + e),null);
	  	return;
	});

	req.on('timeout', function () {
	  // Timeout happend. Server received request, but not handled it
	  // (i.e. doesn't send any response or it took to long).
	  // You don't know what happend.
	  // It will emit 'error' message as well (with ECONNRESET code).

	  console.log("timeout req on");

	  console.log('timeout');
	  req.abort();
	  req.destroy();
	  req.end();
	  //req.finish();
	});

	req.on("socket", function (socket) {
		//  socket.emit("agentRemove");
		// socket.emit("close");
		console.log("sockets req on");
		throw new Error("ererer");
		// Setup the timeout handler
		timeoutProtect = setTimeout(function() {
			// Clear the local timer variable, indicating the timeout has been triggered.
			timeoutProtect = null;

			var err = new Error('example');
			throw err;
			// Execute the callback with an error argument.
		}, 1500);

	});

	req.end();

} //close function

module.exports = new stockGet();
<commit_msg>added emit on req<commit_after>/**
 * Retrieve stock market figures from google finance.
 *
 * @module stockGet
 *
 * @param  {String} stocksymbol
 * @return {object}

	name
	tickerSymbol
	exchange
	exchangeTimezone
	price
	priceChange
	priceChangePercent
	quoteTime
*/

//required modules
var cheerio = require('cheerio');
var https = require('https');

var baseurl="https://www.google.co.uk/finance?q=";

var timeoutProtect;

var stockGet = function() {};

//***********************************************************************
stockGet.prototype.url = function (query,callback) {
	callback(null,baseurl+query);
	return;
};
//***********************************************************************

//***********************************************************************
stockGet.prototype.query = function(symbol,attri,callback) {

	var req = https.request((baseurl+symbol), function(res){

		var body = "";

		//***********************************************
		res.setTimeout(4500, function(e){
			console.log("timed out");
			callback(new Error(e),null);
			return;
		});
		//***********************************************
		res.on('data', function (htmldata) {
			body += htmldata;

		});
		//***********************************************
		res.on('error', function() {
			console.log("res.on('error', ");
			req.abort();
			req.destroy();

			req.end();
			callback(new Error(e),null);

		});
		//***********************************************
	  	res.on('end', function() {
			//need statusCode of 200 otherwise we have an issue
			 //clearTimeout( timeout );
			if(res.statusCode !=200)
			{
				req.end();
	  			callback(new Error("error statusCode: " + res.statusCode + ""), null);
			}

// Proceed only if the timeout handler has not yet fired.
			if (timeoutProtect) {
				timeoutProtect = null;
			    // Clear the scheduled timeout handler
			    clearTimeout(timeoutProtect);
			}

	  		req.end();
	  		//manipulate DOM
			manDom(body);
		});
	});

function manDom(htmlbody)
{
	var $ = cheerio.load(htmlbody);
	var stockSymbol= {};
	if(attri=="all"){
		var k="";
		$(htmlbody).find('meta[itemprop]').each (function(){
		 	attrib = ($(this).attr('itemprop'));
		 	valuu = ($(this).attr('content'));
		 	stockSymbol[attrib] = valuu;
		 });
		callback(null,stockSymbol);
		return;
	}
	else //just return the one dom value
	{

//this below if seems to get called with all issues ? need more testing

		if($("meta[itemprop="+attri+"]").attr("content") === undefined)
		{
			//console.log("Error: missing parameters, attribute is " +attri+".");
			//dlog("error ´"+attri+"´ not found - callbacking with error");
			if(callback){
				callback(new Error("Missing Attribute ´"+attri + "´ for Symbol ´" + symbol +"´."),null);
			}
			else
			{
				console.log("Missing Attribute ´"+attri + "´ for Symbol ´" + symbol +"´.");
				return;
			}

		}
		else
		{
			var stockSymbol= {};
			stockSymbol[attri] = $("meta[itemprop="+attri+"]").attr("content");

			//success - pass back data to callback.
			callback(null,stockSymbol);
			return;
		}
	}
} //end function
//*****************************************************

	req.on('error', function(e) {
	  	//console.error(e);
	  	console.log("error req on");
	  	req.abort();
	  	req.destroy();
		req.end();

	  	callback(new Error("ss " + e),null);
	  	return;
	});

	req.on('timeout', function () {
	  // Timeout happend. Server received request, but not handled it
	  // (i.e. doesn't send any response or it took to long).
	  // You don't know what happend.
	  // It will emit 'error' message as well (with ECONNRESET code).

	  console.log("timeout req on");

	  console.log('timeout');
	  req.abort();
	  req.destroy();
	  req.end();
	  req.emit('error');

	  //req.finish();
	});

	req.on("socket", function (socket) {
		//  socket.emit("agentRemove");
		// socket.emit("close");
		console.log("sockets req on");
		//throw new Error("ererer");
		// Setup the timeout handler
		timeoutProtect = setTimeout(function() {
			// Clear the local timer variable, indicating the timeout has been triggered.
			timeoutProtect = null;

			//var err = new Error('example');
req.emit('timeout');

			//throw err;
			// Execute the callback with an error argument.
		}, 1500);

	});

	req.end();

} //close function

module.exports = new stockGet();<|endoftext|>


<commit_before>var keystone = require('arch-keystone');
var transform = require('model-transform');
var Types = keystone.Field.Types;

var WatchStore = new keystone.List('WatchStore', {
	autokey: { from: 'name', path: 'key', unique: true },
});

WatchStore.add({
	name: { label: '店名', type: String, required: true, index: true },
	address: { label: '地址', type: String, required: true },
	phone: { label: '電話', type: String, required: true },
	map: { label: 'google map url', type: Types.Url, required: true },
});

transform.toJSON(WatchStore);
WatchStore.defaultColumns = 'name, address, phone, map';
WatchStore.register();
<commit_msg>remove the required option from WatchStore address, phone<commit_after>var keystone = require('arch-keystone');
var transform = require('model-transform');
var Types = keystone.Field.Types;

var WatchStore = new keystone.List('WatchStore', {
	autokey: { from: 'name', path: 'key', unique: true },
});

WatchStore.add({
	name: { label: '店名', type: String, required: true, index: true },
	address: { label: '地址', type: String },
	phone: { label: '電話', type: String },
	map: { label: 'google map url', type: Types.Url },
});

transform.toJSON(WatchStore);
WatchStore.defaultColumns = 'name, address, phone, map';
WatchStore.register();
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

/* eslint-env es6, node */

'use strict';

const Realm = require('realm');
const TestCase = require('./asserts');
const isNodeProcess = typeof process === 'object' && process + '' === '[object process]';

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function assertIsUser(user, isAdmin) {
  TestCase.assertType(user, 'object');
  TestCase.assertType(user.token, 'string');
  TestCase.assertType(user.identity, 'string');
  TestCase.assertInstanceOf(user, Realm.Sync.User);
  if (isAdmin !== undefined) {
    TestCase.assertEqual(user.isAdmin, isAdmin);
  }
}

function assertIsSameUser(value, user) {
  assertIsUser(value);
  TestCase.assertEqual(value.token, user.token);
  TestCase.assertEqual(value.identity, user.identity);
  TestCase.assertEqual(value.isAdmin, user.isAdmin);
}

function assertIsError(error, message) {
  TestCase.assertInstanceOf(error, Error, 'The API should return an Error');
  if (message) {
    TestCase.assertEqual(error.message, message);
  }
}

function assertIsAuthError(error, code, type) {
  TestCase.assertInstanceOf(error, Realm.Sync.AuthError, 'The API should return an AuthError');
  if (code) {
    TestCase.assertEqual(error.code, code);
  }
  if (type) {
    TestCase.assertEqual(error.type, type);
  }
}

function failOnError(error) {
  if (error) {
    throw new Error(`Error ${error} was not expected`);
  }
}

// Test the given requestFunc, passing it the given callback after it's been wrapped appropriately.
// This function makes sure that errors thrown in the async callback rejects the promise (making tests actually run).
function callbackTest(requestFunc, callback) {
  return new Promise((resolve, reject) => {
    function callbackWrapper() {
      try {
        callback.apply(this, Array.from(arguments));
        resolve();
      }
      catch (e) {
        reject(e);
      }
    }
    requestFunc(callbackWrapper);
  });
}

module.exports = {

  testLogout() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      assertIsSameUser(user, Realm.Sync.User.current);
      user.logout();

      // Is now logged out.
      TestCase.assertUndefined(Realm.Sync.User.current);

      // Can we open a realm with the registered user?
      TestCase.assertThrows(function() {
        var _realm = new Realm({sync: {user: user, url: 'realm://localhost:9080/~/test'}});
      });
    })
  },

  testRegisterUser() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      // Can we open a realm with the registered user?
      var realm = new Realm({sync: {user: user, url: 'realm://localhost:9080/~/test'}});
      TestCase.assertInstanceOf(realm, Realm);
    });
  },

  testRegisterExistingUser() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      Realm.Sync.User.register('http://localhost:9080', username, 'password', (error, user) => {
        assertIsAuthError(error, 611, 'https://realm.io/docs/object-server/problems/invalid-credentials');
        TestCase.assertUndefined(user);
      });
    });
  },

  testRegisterMissingUsername() {
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.register('http://localhost:9080', undefined, 'password', () => {});
        });
        resolve();
    });
  },

  testRegisterMissingPassword() {
    var username = uuid();
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.register('http://localhost:9080', username, undefined, () => {});
        });
        resolve();
    });
  },

  testRegisterServerOffline() {
    var username = uuid();
    // Because it waits for answer this takes some time..
    return callbackTest((callback) => Realm.Sync.User.register('http://fake_host.local', username, 'password', callback), (error, user) => {
      assertIsError(error);
      TestCase.assertUndefined(user);
    });
  },

  testLogin() {
      var username = uuid();
      // Create user, logout the new user, then login
      return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
        failOnError(error);
        user.logout();

        Realm.Sync.User.login('http://localhost:9080', username, 'password', (error, user) => {
          failOnError(error);
          assertIsUser(user);

          // Can we open a realm with the logged-in user?
          var realm = new Realm({ sync: { user: user, url: 'realm://localhost:9080/~/test' } });
          TestCase.assertInstanceOf(realm, Realm);
          realm.close();
        });
      });
  },

  testLoginMissingUsername() {
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.login('http://localhost:9080', undefined, 'password', () => {});
        });
        resolve();
    });
  },

  testLoginMissingPassword() {
    var username = uuid();
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.login('http://localhost:9080', username, undefined, () => {});
        });
        resolve();
    });
  },

  testLoginNonExistingUser() {
    return callbackTest((callback) => Realm.Sync.User.login('http://localhost:9080', 'does_not', 'exist', callback), (error, user) => {
      assertIsAuthError(error, 611, 'https://realm.io/docs/object-server/problems/invalid-credentials');
      TestCase.assertUndefined(user);
    });
  },

  testLoginServerOffline() {
    var username = uuid();

    // Because it waits for answer this takes some time..
    return new Promise((resolve, reject) => {
      Realm.Sync.User.register('http://fake_host.local', username, 'password', (error, user) => {
        try {
          assertIsError(error);
          TestCase.assertUndefined(user);
          resolve();
        }
        catch (e) { reject(e) }
      });
    });
  },

  testAll() {
    return new Promise((resolve, reject) => {
      let all;
      all = Realm.Sync.User.all;
      TestCase.assertArrayLength(Object.keys(all), 0);

      callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user1) => {
        failOnError(error);

        all = Realm.Sync.User.all;
        TestCase.assertArrayLength(Object.keys(all), 1);
        assertIsSameUser(all[user1.identity], user1);

        Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', (error, user2) => {
          failOnError(error);

          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 2);
          // NOTE: the list of users is in latest-first order.
          assertIsSameUser(all[user2.identity], user2);
          assertIsSameUser(all[user1.identity], user1);

          user2.logout();
          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 1);
          assertIsSameUser(all[user1.identity], user1);

          user1.logout();
          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 0);
          resolve();
        });
      }).catch(e => reject(e));
    });
  },

  testCurrent() {
      return new Promise((resolve, reject) => {
        TestCase.assertUndefined(Realm.Sync.User.current);

        callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user1) => {
          failOnError(error);
          assertIsSameUser(Realm.Sync.User.current, user1);

          Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', (error, user2) => {
            failOnError(error);
            TestCase.assertThrows(() => Realm.Sync.User.current, 'We expect Realm.Sync.User.current to throw if > 1 user.');
            user2.logout();

            assertIsSameUser(Realm.Sync.User.current, user1);

            user1.logout();
            TestCase.assertUndefined(Realm.Sync.User.current);

            resolve();

          });
        }).catch(e => reject(e));
      });
  },

  testManagementRealm() {
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user) => {
      failOnError(error);

      let realm = user.openManagementRealm();
      TestCase.assertInstanceOf(realm, Realm);

      let objectSchemaNames = realm.schema.map(o => o.name);
      TestCase.assertArraysEqual(objectSchemaNames, [ 'PermissionChange', 'PermissionOffer', 'PermissionOfferResponse' ]);
    });
  },

  testRetrieveAccount() {
    if (!isNodeProcess) {
      return Promise.resolve()
    }
    if (!global.testAdminUserInfo) {
      return Promise.reject("Test requires an admin user");
    }
    return Realm.Sync.User.login('http://localhost:9080', global.testAdminUserInfo.username, global.testAdminUserInfo.password)
      .then(user => {
        TestCase.assertTrue(user.isAdmin, "Test requires an admin user");
        return user.retrieveAccount()
      })
      .then(account => {
        //           {
        // "provider_id": "admin",
        // "provider": "password",
        // 	"user": {
        // "id": "07ac9a0a-a97a-4ee1-b53c-b05a6542035a",
        // "isAdmin": true,
        // }
        // }
        TestCase.assertEqual(account.provider_id, global.testAdminUserInfo.username);
        TestCase.assertEqual(account.provider, 'password');
        TestCase.assertTrue(account.user);
        TestCase.assertTrue(account.user.isAdmin !== undefined);
        TestCase.assertTrue(account.user.id);
      })
      .catch(e => reject(e));
  },

  testRetrieveNotExistingAccount() {
    if (!isNodeProcess) {
      return Promise.resolve()
    }
    if (!global.testAdminUserInfo) {
      return Promise.reject("Test requires an admin user");
    }
    return Realm.Sync.User.login('http://localhost:9080', global.testAdminUserInfo.username, global.testAdminUserInfo.password)
      .then(user => {
        TestCase.assertTrue(user.isAdmin, "Test requires an admin user");
        let notExistingUsername = uuid();
        return user.retrieveAccount('password', notExistingUsername)
      })
      .then(account => {
        reject("Retrieving not existing account should fail");
      })
      .catch(e => {
        TestCase.assertEqual(e.code, 404);
        resolve()
      });
  },

  /* This test fails because of realm-object-store #243 . We should use 2 users.
  testSynchronizeChangesWithTwoClientsAndOneUser() {
    // Test Schema
    class Foo {}
    Foo.schema = {
      name:       'Foo',
      properties: {
        string: 'string',
        bars:   { type: 'list', objectType: 'Bar' },
      },
    };

    class Bar {}
    Bar.schema = {
      name:       'Bar',
      properties: { integer: 'int' },
    };

    const schema = [Foo.schema, Bar.schema];

    // Create a user, open two clients at different local paths, synchronize changes
    const username = uuid();
    return new Promise((resolve) => {
      Realm.Sync.User.register('http://localhost:9080', username, 'password', (error ,user) => {
        failOnError(error);

        const clientA = new Realm({
          path:   'testSynchronizeChangesWithTwoClientsAndOneUser_clientA.realm',
          schema: schema,
          sync:   {
            user: user,
            url:  'http://localhost:9080/~/test',
          },
        });

        const clientB = new Realm({
          path:   'testSynchronizeChangesWithTwoClientsAndOneUser_clientB.realm',
          schema: schema,
          sync:   {
            user: user,
            url:  'http://localhost:9080/~/test',
          },
        });

        clientB.addListener('change', () => {
          const foos = clientB.objects('Foo');
          if (foos.length > 0) {
            TestCase.assertEqual(foos.length, 1);
            TestCase.assertEqual(foos[0].string, 'Hello, World!');
            resolve();
          }
        });

        clientA.write(() => {
          clientA.create('Foo', { string: 'Hello, World!' });
        });
      });
    });
  }, */

};

<commit_msg>Revert user-tests to still use callbacks for login/register etc<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

/* eslint-env es6, node */

'use strict';

const Realm = require('realm');
const TestCase = require('./asserts');
const isNodeProcess = typeof process === 'object' && process + '' === '[object process]';

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function assertIsUser(user, isAdmin) {
  TestCase.assertType(user, 'object');
  TestCase.assertType(user.token, 'string');
  TestCase.assertType(user.identity, 'string');
  TestCase.assertInstanceOf(user, Realm.Sync.User);
  if (isAdmin !== undefined) {
    TestCase.assertEqual(user.isAdmin, isAdmin);
  }
}

function assertIsSameUser(value, user) {
  assertIsUser(value);
  TestCase.assertEqual(value.token, user.token);
  TestCase.assertEqual(value.identity, user.identity);
  TestCase.assertEqual(value.isAdmin, user.isAdmin);
}

function assertIsError(error, message) {
  TestCase.assertInstanceOf(error, Error, 'The API should return an Error');
  if (message) {
    TestCase.assertEqual(error.message, message);
  }
}

function assertIsAuthError(error, code, type) {
  TestCase.assertInstanceOf(error, Realm.Sync.AuthError, 'The API should return an AuthError');
  if (code) {
    TestCase.assertEqual(error.code, code);
  }
  if (type) {
    TestCase.assertEqual(error.type, type);
  }
}

function failOnError(error) {
  if (error) {
    throw new Error(`Error ${error} was not expected`);
  }
}

// Test the given requestFunc, passing it the given callback after it's been wrapped appropriately.
// This function makes sure that errors thrown in the async callback rejects the promise (making tests actually run).
function callbackTest(requestFunc, callback) {
  return new Promise((resolve, reject) => {
    function callbackWrapper() {
      try {
        callback.apply(this, Array.from(arguments));
        resolve();
      }
      catch (e) {
        reject(e);
      }
    }
    requestFunc(callbackWrapper);
  });
}

module.exports = {

  testLogout() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      assertIsSameUser(user, Realm.Sync.User.current);
      user.logout();

      // Is now logged out.
      TestCase.assertUndefined(Realm.Sync.User.current);

      // Can we open a realm with the registered user?
      TestCase.assertThrows(function() {
        var _realm = new Realm({sync: {user: user, url: 'realm://localhost:9080/~/test'}});
      });
    })
  },

  testRegisterUser() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      // Can we open a realm with the registered user?
      var realm = new Realm({sync: {user: user, url: 'realm://localhost:9080/~/test'}});
      TestCase.assertInstanceOf(realm, Realm);
    });
  },

  testRegisterExistingUser() {
    var username = uuid();
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
      failOnError(error);
      assertIsUser(user);

      Realm.Sync.User.register('http://localhost:9080', username, 'password', (error, user) => {
        assertIsAuthError(error, 611, 'https://realm.io/docs/object-server/problems/invalid-credentials');
        TestCase.assertUndefined(user);
      });
    });
  },

  testRegisterMissingUsername() {
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.register('http://localhost:9080', undefined, 'password', () => {});
        });
        resolve();
    });
  },

  testRegisterMissingPassword() {
    var username = uuid();
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.register('http://localhost:9080', username, undefined, () => {});
        });
        resolve();
    });
  },

  testRegisterServerOffline() {
    var username = uuid();
    // Because it waits for answer this takes some time..
    return callbackTest((callback) => Realm.Sync.User.register('http://fake_host.local', username, 'password', callback), (error, user) => {
      assertIsError(error);
      TestCase.assertUndefined(user);
    });
  },

  testLogin() {
      var username = uuid();
      // Create user, logout the new user, then login
      return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', username, 'password', callback), (error, user) => {
        failOnError(error);
        user.logout();

        Realm.Sync.User.login('http://localhost:9080', username, 'password', (error, user) => {
          failOnError(error);
          assertIsUser(user);

          // Can we open a realm with the logged-in user?
          var realm = new Realm({ sync: { user: user, url: 'realm://localhost:9080/~/test' } });
          TestCase.assertInstanceOf(realm, Realm);
          realm.close();
        });
      });
  },

  testLoginMissingUsername() {
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.login('http://localhost:9080', undefined, 'password', () => {});
        });
        resolve();
    });
  },

  testLoginMissingPassword() {
    var username = uuid();
    return new Promise((resolve, _reject) => {
        TestCase.assertThrows(() => {
            Realm.Sync.User.login('http://localhost:9080', username, undefined, () => {});
        });
        resolve();
    });
  },

  testLoginNonExistingUser() {
    return callbackTest((callback) => Realm.Sync.User.login('http://localhost:9080', 'does_not', 'exist', callback), (error, user) => {
      assertIsAuthError(error, 611, 'https://realm.io/docs/object-server/problems/invalid-credentials');
      TestCase.assertUndefined(user);
    });
  },

  testLoginServerOffline() {
    var username = uuid();

    // Because it waits for answer this takes some time..
    return new Promise((resolve, reject) => {
      Realm.Sync.User.register('http://fake_host.local', username, 'password', (error, user) => {
        try {
          assertIsError(error);
          TestCase.assertUndefined(user);
          resolve();
        }
        catch (e) { reject(e) }
      });
    });
  },

  testAll() {
    return new Promise((resolve, reject) => {
      let all;
      all = Realm.Sync.User.all;
      TestCase.assertArrayLength(Object.keys(all), 0);

      callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user1) => {
        failOnError(error);

        all = Realm.Sync.User.all;
        TestCase.assertArrayLength(Object.keys(all), 1);
        assertIsSameUser(all[user1.identity], user1);

        Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', (error, user2) => {
          failOnError(error);

          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 2);
          // NOTE: the list of users is in latest-first order.
          assertIsSameUser(all[user2.identity], user2);
          assertIsSameUser(all[user1.identity], user1);

          user2.logout();
          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 1);
          assertIsSameUser(all[user1.identity], user1);

          user1.logout();
          all = Realm.Sync.User.all;
          TestCase.assertArrayLength(Object.keys(all), 0);
          resolve();
        });
      }).catch(e => reject(e));
    });
  },

  testCurrent() {
      return new Promise((resolve, reject) => {
        TestCase.assertUndefined(Realm.Sync.User.current);

        callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user1) => {
          failOnError(error);
          assertIsSameUser(Realm.Sync.User.current, user1);

          Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', (error, user2) => {
            failOnError(error);
            TestCase.assertThrows(() => Realm.Sync.User.current, 'We expect Realm.Sync.User.current to throw if > 1 user.');
            user2.logout();

            assertIsSameUser(Realm.Sync.User.current, user1);

            user1.logout();
            TestCase.assertUndefined(Realm.Sync.User.current);

            resolve();

          });
        }).catch(e => reject(e));
      });
  },

  testManagementRealm() {
    return callbackTest((callback) => Realm.Sync.User.register('http://localhost:9080', uuid(), 'password', callback), (error, user) => {
      failOnError(error);

      let realm = user.openManagementRealm();
      TestCase.assertInstanceOf(realm, Realm);

      let objectSchemaNames = realm.schema.map(o => o.name);
      TestCase.assertArraysEqual(objectSchemaNames, [ 'PermissionChange', 'PermissionOffer', 'PermissionOfferResponse' ]);
    });
  },

  testRetrieveAccount() {
    return new Promise((resolve, reject) => {
      if (!isNodeProcess) {
        resolve();
      }

      if (!global.testAdminUserInfo) {
        reject("Test requires an admin user");
      }

      Realm.Sync.User.login('http://localhost:9080', global.testAdminUserInfo.username, global.testAdminUserInfo.password, (error, user) => {
        if (error) {
          reject(error);
        }

        TestCase.assertTrue(user.isAdmin, "Test requires an admin user");

        user.retrieveAccount('password', global.testAdminUserInfo.username)
          .then(account => {
            //           {
            // "provider_id": "admin",
            // "provider": "password",
            // 	"user": {
            // "id": "07ac9a0a-a97a-4ee1-b53c-b05a6542035a",
            // "isAdmin": true,
            // }
            // }

            TestCase.assertEqual(account.provider_id, global.testAdminUserInfo.username);
            TestCase.assertEqual(account.provider, 'password');
            TestCase.assertTrue(account.user);
            TestCase.assertTrue(account.user.isAdmin !== undefined);
            TestCase.assertTrue(account.user.id);
            resolve();
          })
          .catch(e => reject(e));
      })
    });
  },

  testRetrieveNotExistingAccount() {
    return new Promise((resolve, reject) => {
      if (!isNodeProcess) {
        resolve();
      }

      if (!global.testAdminUserInfo) {
        reject("Test requires an admin user");
      }

      Realm.Sync.User.login('http://localhost:9080', global.testAdminUserInfo.username, global.testAdminUserInfo.password, (error, user) => {
        if (error) {
          reject(error);
        }

        TestCase.assertTrue(user.isAdmin, "Test requires an admin user");

        let notExistingUsername = uuid();
        user.retrieveAccount('password', notExistingUsername)
          .then(account => {
            reject("Retrieving not existing account should fail");
          })
          .catch(e => {
            TestCase.assertEqual(e.code, 404);
            resolve()
          });
      })
    });
  },

  /* This test fails because of realm-object-store #243 . We should use 2 users.
  testSynchronizeChangesWithTwoClientsAndOneUser() {
    // Test Schema
    class Foo {}
    Foo.schema = {
      name:       'Foo',
      properties: {
        string: 'string',
        bars:   { type: 'list', objectType: 'Bar' },
      },
    };

    class Bar {}
    Bar.schema = {
      name:       'Bar',
      properties: { integer: 'int' },
    };

    const schema = [Foo.schema, Bar.schema];

    // Create a user, open two clients at different local paths, synchronize changes
    const username = uuid();
    return new Promise((resolve) => {
      Realm.Sync.User.register('http://localhost:9080', username, 'password', (error ,user) => {
        failOnError(error);

        const clientA = new Realm({
          path:   'testSynchronizeChangesWithTwoClientsAndOneUser_clientA.realm',
          schema: schema,
          sync:   {
            user: user,
            url:  'http://localhost:9080/~/test',
          },
        });

        const clientB = new Realm({
          path:   'testSynchronizeChangesWithTwoClientsAndOneUser_clientB.realm',
          schema: schema,
          sync:   {
            user: user,
            url:  'http://localhost:9080/~/test',
          },
        });

        clientB.addListener('change', () => {
          const foos = clientB.objects('Foo');
          if (foos.length > 0) {
            TestCase.assertEqual(foos.length, 1);
            TestCase.assertEqual(foos[0].string, 'Hello, World!');
            resolve();
          }
        });

        clientA.write(() => {
          clientA.create('Foo', { string: 'Hello, World!' });
        });
      });
    });
  }, */

};

<|endoftext|>


<commit_before>
var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,

    common = require('./common'),
    utils = require('./../utils');

var Discussion = module.exports = new Schema({
    title:{type:String, required:true},
    tooltip:String,
//        text_field:{type:Schema.Types.Html},
//        text_field_preview:{type:Schema.Types.Html},
    image_field: { type:Schema.Types.File, required:true},
    image_field_preview: { type:Schema.Types.File, require:true},
//    subject_id:[
//        {type:ObjectId, ref:'Subject', index:true, required:true, editable: false}
//    ],
    subject_id: {type:[ObjectId], ref:'Subject',required:true},
    subject_name: String,
    system_message: {type:Schema.Types.Html},
    creation_date:{type:Date, 'default':Date.now},
    last_updated:{type:Date, 'default':Date.now},
    creator_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY},
    first_name:{type:String,editable:false},
    last_name:{type:String,editable:false},
    text_field_preview: {type:Schema.Types.Text},//2-3 lines of the vision_text
    text_field:{type:Schema.Types.Text, required:true},
    vision_text_history:{type:[String]},
    replaced_text_history:[ new Schema({
        old_text: {type:String},
        new_text: {type: String}
    })],
    num_of_approved_change_suggestions: {type: Number, 'default': 0},
    is_hot_object: {type:Boolean,'default':false},
    press_items: [ {press_item_id:{type:ObjectId, ref:'PressItem'}}],
    links: [new Schema({
        title: String,
        link: String,
        text: String
    })],

    sub_branding:[ {
        image: Schema.Types.File,
        title: {type: String},
        text: {type: String},
        link: {type: String}
    }],

    is_cycle:{
        flag:{type:Boolean, 'default':false, editable:false},
        date:{type:Date, 'default':Date.now, editable:false}
    },
    is_displayed:{type: Boolean, 'deafult': false},
    tags:[String],
    //users that connected somehow to discussion for my uru
    users:[
        new Schema({user_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY}, join_date: {type:Date, 'default':Date.now}})
    ],

    //followers for my uru
    followers:[
        new Schema({user_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY}, join_date: {type:Date, 'default':Date.now}})
    ],
    view_counter: {type:Number, 'default':0},
    followers_count:{type:Number, 'default':0, editable:false},
    is_visible:{type:Boolean, 'default':true},
    is_published:{type:Boolean, 'default':false},
    /* I'm changing the min validator from 2 to 0 to avoid Blocker bug
     * TODO change this to 2 again after you'll investigate */
    threshold_for_accepting_change_suggestions: {type: Number, min: 0, max: 501, 'default': 2},
    admin_threshold_for_accepting_change_suggestions: {type: Number, max: 500, 'default': 0},
//        popular_comments: [{type: ObjectId, ref: 'Post', index: true}],
    grade:{type:Number, 'default':0},
    evaluate_counter:{type:Number, 'default':0},
    grade_sum:{type:Number, 'default':0, editable:false},
//    grades_count_thresh:{type:Number, 'default':0, editable:false},

    gamification: {has_rewarded_creator_of_turning_to_cycle: {type: Boolean, 'default': false},
        has_rewarded_creator_for_high_grading_of_min_graders: {type: String, 'default': false}, editable:false},
    is_hidden:{type:Boolean,'default':false} ,
    is_private:{type:Boolean,'default':true}
}, {strict: true});

Discussion.methods.toString = function() {
    return this.title;
};<commit_msg>replace discussion.js subject_id field<commit_after>
var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,

    common = require('./common'),
    utils = require('./../utils');

var Discussion = module.exports = new Schema({
    title:{type:String, required:true},
    tooltip:String,
//        text_field:{type:Schema.Types.Html},
//        text_field_preview:{type:Schema.Types.Html},
    image_field: { type:Schema.Types.File, required:true},
    image_field_preview: { type:Schema.Types.File, require:true},
    subject_id:[
        {type:ObjectId, ref:'Subject', index:true, required:true, editable: false}
    ],
/*
    subject_id: {type:[ObjectId], ref:'Subject',required:true},
*/
    subject_name: String,
    system_message: {type:Schema.Types.Html},
    creation_date:{type:Date, 'default':Date.now},
    last_updated:{type:Date, 'default':Date.now},
    creator_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY},
    first_name:{type:String,editable:false},
    last_name:{type:String,editable:false},
    text_field_preview: {type:Schema.Types.Text},//2-3 lines of the vision_text
    text_field:{type:Schema.Types.Text, required:true},
    vision_text_history:{type:[String]},
    replaced_text_history:[ new Schema({
        old_text: {type:String},
        new_text: {type: String}
    })],
    num_of_approved_change_suggestions: {type: Number, 'default': 0},
    is_hot_object: {type:Boolean,'default':false},
    press_items: [ {press_item_id:{type:ObjectId, ref:'PressItem'}}],
    links: [new Schema({
        title: String,
        link: String,
        text: String
    })],

    sub_branding:[ {
        image: Schema.Types.File,
        title: {type: String},
        text: {type: String},
        link: {type: String}
    }],

    is_cycle:{
        flag:{type:Boolean, 'default':false, editable:false},
        date:{type:Date, 'default':Date.now, editable:false}
    },
    is_displayed:{type: Boolean, 'deafult': false},
    tags:[String],
    //users that connected somehow to discussion for my uru
    users:[
        new Schema({user_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY}, join_date: {type:Date, 'default':Date.now}})
    ],

    //followers for my uru
    followers:[
        new Schema({user_id:{type:ObjectId, ref:'User', query:common.FIND_USER_QUERY}, join_date: {type:Date, 'default':Date.now}})
    ],
    view_counter: {type:Number, 'default':0},
    followers_count:{type:Number, 'default':0, editable:false},
    is_visible:{type:Boolean, 'default':true},
    is_published:{type:Boolean, 'default':false},
    /* I'm changing the min validator from 2 to 0 to avoid Blocker bug
     * TODO change this to 2 again after you'll investigate */
    threshold_for_accepting_change_suggestions: {type: Number, min: 0, max: 501, 'default': 2},
    admin_threshold_for_accepting_change_suggestions: {type: Number, max: 500, 'default': 0},
//        popular_comments: [{type: ObjectId, ref: 'Post', index: true}],
    grade:{type:Number, 'default':0},
    evaluate_counter:{type:Number, 'default':0},
    grade_sum:{type:Number, 'default':0, editable:false},
//    grades_count_thresh:{type:Number, 'default':0, editable:false},

    gamification: {has_rewarded_creator_of_turning_to_cycle: {type: Boolean, 'default': false},
        has_rewarded_creator_for_high_grading_of_min_graders: {type: String, 'default': false}, editable:false},
    is_hidden:{type:Boolean,'default':false} ,
    is_private:{type:Boolean,'default':true}
}, {strict: true});

Discussion.methods.toString = function() {
    return this.title;
};<|endoftext|>


<commit_before>module.exports = (function() {
  var codec = {};

  var EVE_EPOCH = Date.UTC(2003, 4, 6); // May 6th 2003

  function toMinutes(ms) {
    return Math.floor(ms / 1000 / 60);
  }

  function fromMinutes(m) {
    return m * 1000 * 60;
  }

  codec.encode = function(filter) {
    var solarSystems = filter.solarSystems
      .map(solarSystem => solarSystem.id)
      .join(',');
    var start = toMinutes(filter.from.getTime() - EVE_EPOCH);
    var duration = toMinutes(filter.to.getTime() - filter.from.getTime());
    var allianceColors = Object.keys(filter.allianceColors)
      .map(allianceID => filter.allianceColors[allianceID] + allianceID)
      .join(',');

      return `${solarSystems}-${start}+${duration}-${allianceColors}`;
  };

  codec.decode = function(str) {
    var sections = str.split('-');

    // Must have at least 2 sections (systems and time)
    if (sections.length < 2) {
      return null;
    }
    var systems = sections[0].split(',');
    if (systems.some(isNaN)) {
      return null;
    }
    var time = sections[1].split('+');
    if (time.length !== 2 || time.some(isNaN)) {
      return null;
    }

    // For some reason .map(parseInt) does not work
    var solarSystems = systems.map(n => parseInt(n));
    var from = new Date(EVE_EPOCH + fromMinutes(time[0]));
    var to = new Date(from.getTime() + fromMinutes(time[1]));
    var allianceColors = {};
    if (sections[2]) {
      sections[2].split(',').reduce((acc, e) => {
        var color = e.charAt(0);
        var allianceID = e.substring(1);
        acc[allianceID] = color;
        return acc;
      }, allianceColors);
    }
    return {
      from,
      to,
      solarSystems,
      allianceColors
    };
  };

  return codec;
})();
<commit_msg>Shortened the URL significantly by removing "padding" from alliance and solar system ids as well as converting them to radix 36.<commit_after>module.exports = (function() {
  var codec = {};

  const EVE_EPOCH = Date.UTC(2003, 4, 6); // May 6th 2003
  const ALLIANCE_ID_PADDING = 99000000;
  const SOLARSYSTEM_ID_PADDING = 30000000;
  const RADIX = 36;

  function toMinutes(ms) {
    return Math.floor(ms / 1000 / 60);
  }

  function fromMinutes(m) {
    return m * 1000 * 60;
  }

  codec.encode = function(filter) {
    var solarSystems = filter.solarSystems
      .map(solarSystem => (solarSystem.id - SOLARSYSTEM_ID_PADDING).toString(RADIX))
      .join(',');
    var start = toMinutes(filter.from.getTime() - EVE_EPOCH);
    var duration = toMinutes(filter.to.getTime() - filter.from.getTime());
    var allianceColors = Object.keys(filter.allianceColors)
      .map(allianceID => filter.allianceColors[allianceID] + (allianceID - ALLIANCE_ID_PADDING).toString(RADIX))
      .join(',');

      return `${solarSystems}-${start}+${duration}-${allianceColors}`;
  };

  codec.decode = function(str) {
    var sections = str.split('-');

    // Must have at least 2 sections (systems and time)
    if (sections.length < 2) {
      return null;
    }
    var systems = sections[0].split(',');
    if (systems.some(isNaN)) {
      return null;
    }
    var time = sections[1].split('+');
    if (time.length !== 2 || time.some(isNaN)) {
      return null;
    }

    // For some reason .map(parseInt) does not work
    var solarSystems = systems.map(n => parseInt(n, RADIX) + SOLARSYSTEM_ID_PADDING);
    var from = new Date(EVE_EPOCH + fromMinutes(time[0]));
    var to = new Date(from.getTime() + fromMinutes(time[1]));
    var allianceColors = {};
    if (sections[2]) {
      // Joining index 2+ in case thare are negative numbers
      sections.slice(2).join('-').split(',').reduce((acc, e) => {
        var color = e.charAt(0);
        var allianceID = parseInt(e.substring(1), RADIX) + ALLIANCE_ID_PADDING;
        acc[allianceID] = color;
        return acc;
      }, allianceColors);
    }
    return {
      from,
      to,
      solarSystems,
      allianceColors
    };
  };

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


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import { List } from 'immutable'

const TransactionList = ({ transactions, ntransactions, actions, filter }) => {
	if (transactions.size === 0) {
		return (

 No recent transactions

		)
	}
	const prettyTimestamp = (timestamp) => {
		const pad = (n) => String('0' + n).slice(-2)

		const yesterday = new Date()
		yesterday.setHours(yesterday.getHours() - 24)
		if (timestamp > yesterday) {
			return (
				'Today at ' +
				pad(timestamp.getHours()) +
				':' +
				pad(timestamp.getMinutes())
			)
		}
		return (
			timestamp.getFullYear() +
			'-' +
			pad(timestamp.getMonth() + 1) +
			'-' +
			pad(timestamp.getDate()) +
			' ' +
			pad(timestamp.getHours()) +
			':' +
			pad(timestamp.getMinutes())
		)
	}
	const transactionComponents = transactions
		.take(ntransactions)
		.filter((txn) => {
			if (!filter) {
				return true
			}
			return txn.transactionsums.totalSiacoin.abs().gt(0) || txn.transactionsums.totalSiafund.abs().gt(0) || txn.transactionsums.totalMiner.abs().gt(0)
		})
		.map((txn, key) => {
			let valueData = ''
			if (txn.transactionsums.totalSiacoin.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalSiacoin
						.round(4)
						.toNumber()
						.toLocaleString() + ' SC '
			}
			if (txn.transactionsums.totalSiafund.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalSiafund
						.round(4)
						.toNumber()
						.toLocaleString() + ' SF '
			}
			if (txn.transactionsums.totalMiner.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalMiner.round(4).toNumber().toLocaleString() +
					' SC (miner) '
			}
			if (valueData === '') {
				valueData = '0 SC'
			}
			return (

						{txn.confirmed
							? prettyTimestamp(txn.confirmationtimestamp)
							: 'Not Confirmed'}

					{valueData}
					{txn.transactionid}

						{txn.confirmed
							?  Confirmed
							:  Unconfirmed }

			)
		})
	const onMoreClick = () => actions.showMoreTransactions()
	const onToggleFilter = () => actions.toggleFilter()
	return (

 Recent Transactions

					<input type="checkbox" onClick={onToggleFilter} checked={filter} />Hide 0SC Transactions

						Date
						Net Value
						Transaction ID
						Confirmation Status

					{transactionComponents}

			{transactions.size > ntransactions
				?

					<button className="load-more-button" onClick={onMoreClick}>
						More Transactions
            </button>

				: null}

	)
}

TransactionList.propTypes = {
	transactions: PropTypes.instanceOf(List).isRequired,
	ntransactions: PropTypes.number.isRequired,
	filter: PropTypes.bool.isRequired,
}

export default TransactionList
<commit_msg>fix indent<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import { List } from 'immutable'

const TransactionList = ({ transactions, ntransactions, actions, filter }) => {
	if (transactions.size === 0) {
		return (

 No recent transactions

		)
	}
	const prettyTimestamp = (timestamp) => {
		const pad = (n) => String('0' + n).slice(-2)

		const yesterday = new Date()
		yesterday.setHours(yesterday.getHours() - 24)
		if (timestamp > yesterday) {
			return (
				'Today at ' +
				pad(timestamp.getHours()) +
				':' +
				pad(timestamp.getMinutes())
			)
		}
		return (
			timestamp.getFullYear() +
			'-' +
			pad(timestamp.getMonth() + 1) +
			'-' +
			pad(timestamp.getDate()) +
			' ' +
			pad(timestamp.getHours()) +
			':' +
			pad(timestamp.getMinutes())
		)
	}
	const transactionComponents = transactions
		.take(ntransactions)
		.filter((txn) => {
			if (!filter) {
				return true
			}
			return txn.transactionsums.totalSiacoin.abs().gt(0) || txn.transactionsums.totalSiafund.abs().gt(0) || txn.transactionsums.totalMiner.abs().gt(0)
		})
		.map((txn, key) => {
			let valueData = ''
			if (txn.transactionsums.totalSiacoin.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalSiacoin
						.round(4)
						.toNumber()
						.toLocaleString() + ' SC '
			}
			if (txn.transactionsums.totalSiafund.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalSiafund
						.round(4)
						.toNumber()
						.toLocaleString() + ' SF '
			}
			if (txn.transactionsums.totalMiner.abs().gt(0)) {
				valueData +=
					txn.transactionsums.totalMiner.round(4).toNumber().toLocaleString() +
					' SC (miner) '
			}
			if (valueData === '') {
				valueData = '0 SC'
			}
			return (

						{txn.confirmed
							? prettyTimestamp(txn.confirmationtimestamp)
							: 'Not Confirmed'}

					{valueData}
					{txn.transactionid}

						{txn.confirmed
							?  Confirmed
							:  Unconfirmed }

			)
		})
	const onMoreClick = () => actions.showMoreTransactions()
	const onToggleFilter = () => actions.toggleFilter()
	return (

 Recent Transactions

					<input type="checkbox" onClick={onToggleFilter} checked={filter} />Hide 0SC Transactions

						Date
						Net Value
						Transaction ID
						Confirmation Status

					{transactionComponents}

			{transactions.size > ntransactions
				?

					<button className="load-more-button" onClick={onMoreClick}>
						More Transactions
					</button>

				: null}

	)
}

TransactionList.propTypes = {
	transactions: PropTypes.instanceOf(List).isRequired,
	ntransactions: PropTypes.number.isRequired,
	filter: PropTypes.bool.isRequired,
}

export default TransactionList
<|endoftext|>


<commit_before>/**
 * @author daniel.joppi
 * @since 2/12/14.
 */
module.exports = function(mongoose, Schema) {

    var schema_ = new Schema({
        name: { type: String },
        lastName: { type: String },
        birthday: { type: Date },
        fullName: { type: String },
        photo: { type: String }, // id to image
        email: { type: String },
        location: { type: String },
        locationRange: { type: Number },
        facebookConnect: { type: Boolean },
        linkedinConnect: { type: Boolean }
    });

    mongoose.model('user', schema_);
};<commit_msg>file upload<commit_after>/**
 * @author daniel.joppi
 * @since 2/12/14.
 */
module.exports = function(mongoose, Schema) {

    var schema_ = new Schema({
        name: { type: String },
        lastName: { type: String },
        birthday: { type: Date },
        fullName: { type: String },
        email: { type: String },
        location: { type: String },
        locationRange: { type: Number },
        facebookConnect: { type: Boolean },
        linkedinConnect: { type: Boolean },
        photo: { type: String } // id to image
    });

    mongoose.model('user', schema_);
};<|endoftext|>


<commit_before>/*
 * Reply posts
 */

let main = require('../main'),
	postCommon = require('./common'),
	{_, Backbone, options, state} = main;

var Article = module.exports = Backbone.View.extend({
	tagName: 'article',
	render() {
		this.setElement(main.oneeSama.article(this.model.attributes));
		return this;
	},
	insertIntoDOM() {
		main.$threads.children('#p' + this.model.get('op'))
			.children('blockquote, .omit, form, article[id]:last')
			.last()
			.after(this.$el);
		this.autoExpandImage().fun();
	}
});

// Extend with common mixins
_.extend(Article.prototype, postCommon);
<commit_msg>Port article.js to new post DOM<commit_after>/*
 * Reply posts
 */

const main = require('../main'),
	postCommon = require('./common'),
	{_, Backbone} = main;

const Article = module.exports = Backbone.View.extend({
	tagName: 'article',
	render() {
		this.setElement(main.oneeSama.article(this.model.attributes));
		return this;
	},
	insertIntoDOM() {
		const last = _.last(document.query('#p' + this.model.get('op'))
			.queryAll('article[id]'));
		last.after(this.el);
		this.autoExpandImage().fun();
	}
});

// Extend with common mixins
_.extend(Article.prototype, postCommon);
<|endoftext|>


<commit_before>/*
 * OP and thread related logic
 */

var $ = require('jquery'),
	_ = require('underscore'),
	Backbone = require('backbone'),
	imager = require('./imager'),
	main = require('../main'),
	postCommon = require('./common'),
	state = require('../state');

var Section = module.exports = Backbone.View.extend({
	tagName: 'section',

	initialize: function () {
		// On the live page only
		if (this.$el.is(':empty') && state.page.get('page') === -1)
			this.render();
		this.listenTo(this.model, {
			'change:locked': this.renderLocked,
			destroy: this.remove
		});
		this.listenToOnce(this.model, {
			'add': this.renderRelativeTime
		});
		this.initCommon();
	},

	render: function() {
		main.oneeSama.links = this.model.get('links');
		this.setElement(main.oneeSama.monomono(this.model.attributes).join(''));
		this.$el.insertAfter(main.$threads.children('hr:first'));
		this.$el.after('
');
		return this;
	},

	renderHide: function (model, hide) {
		this.$el.next('hr').andSelf().toggle(!hide);
	},

	renderLocked: function (model, locked) {
		this.$el.toggleClass('locked', !!locked);
	},

	remove: function () {
		this.$el.next('hr').andSelf().remove();
		this.stopListening();
		return this;
	},

	/*
	 Remove the top reply on board pages, if over limit, when a new reply is
	 added
	 */
	shiftReplies: function() {

	}
});

// Extend with common mixins
_.extend(Section.prototype, imager.Hidamari, postCommon);
<commit_msg>Keep new thread box on top of the page<commit_after>/*
 * OP and thread related logic
 */

var $ = require('jquery'),
	_ = require('underscore'),
	Backbone = require('backbone'),
	imager = require('./imager'),
	main = require('../main'),
	postCommon = require('./common'),
	state = require('../state');

var Section = module.exports = Backbone.View.extend({
	tagName: 'section',

	initialize: function () {
		// On the live page only
		if (this.$el.is(':empty') && state.page.get('page') === -1)
			this.render();
		this.listenTo(this.model, {
			'change:locked': this.renderLocked,
			destroy: this.remove
		});
		this.listenToOnce(this.model, {
			'add': this.renderRelativeTime
		});
		this.initCommon();
	},

	render: function() {
		main.oneeSama.links = this.model.get('links');
		this.setElement(main.oneeSama.monomono(this.model.attributes).join(''));
		this.$el.insertAfter(main.$threads.children('aside:first'));
		this.$el.after('
');
		return this;
	},

	renderHide: function (model, hide) {
		this.$el.next('hr').andSelf().toggle(!hide);
	},

	renderLocked: function (model, locked) {
		this.$el.toggleClass('locked', !!locked);
	},

	remove: function () {
		this.$el.next('hr').andSelf().remove();
		this.stopListening();
		return this;
	},

	/*
	 Remove the top reply on board pages, if over limit, when a new reply is
	 added
	 */
	shiftReplies: function() {

	}
});

// Extend with common mixins
_.extend(Section.prototype, imager.Hidamari, postCommon);
<|endoftext|>