<commit_before>import React, {PropTypes} from 'react';
// TODO: move this to a higher level package than chronograf?
import FlashMessages from 'shared/components/FlashMessages';
import LayoutRenderer from '../components/LayoutRenderer';
import {fetchLayouts} from '../apis';
import _ from 'lodash';

export const HostPage = React.createClass({
  propTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
    params: PropTypes.shape({
      hostID: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {layouts: []};
  },

  componentDidMount() {
    fetchLayouts().then((ls) => {
      this.setState({layouts: ls.data.layouts});
    });
  },

  render() {
    const autoRefreshMs = 15000;
    const source = this.props.source.links.proxy;
    const hostID = this.props.params.hostID;

    const layout = _.head(this.state.layouts);

    let layoutComponent;
    if (layout) {
      layout.cells.forEach((cell) => {
        cell.queries.forEach((q) => {
          q.text = q.query;
          q.database = q.db;
        });
      });

      layoutComponent = (
        <LayoutRenderer
          cells={layout.cells}
          autoRefreshMs={autoRefreshMs}
          source={source}
          host={this.props.params.hostID}
        />
      );
    } else {
      layoutComponent =
;
    }

    return (

{hostID}

Uptime: 2d 4h 33m

            {layoutComponent}

    );
  },
});

export default HostPage;
<commit_msg>Satisfy build errors<commit_after>import React, {PropTypes} from 'react';
// TODO: move this to a higher level package than chronograf?
import LayoutRenderer from '../components/LayoutRenderer';
import {fetchLayouts} from '../apis';
import _ from 'lodash';

export const HostPage = React.createClass({
  propTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
    params: PropTypes.shape({
      hostID: PropTypes.string.isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {layouts: []};
  },

  componentDidMount() {
    fetchLayouts().then((ls) => {
      this.setState({layouts: ls.data.layouts});
    });
  },

  render() {
    const autoRefreshMs = 15000;
    const source = this.props.source.links.proxy;
    const hostID = this.props.params.hostID;

    const layout = _.head(this.state.layouts);

    let layoutComponent;
    if (layout) {
      layout.cells.forEach((cell) => {
        cell.queries.forEach((q) => {
          q.text = q.query;
          q.database = q.db;
        });
      });

      layoutComponent = (
        <LayoutRenderer
          cells={layout.cells}
          autoRefreshMs={autoRefreshMs}
          source={source}
          host={this.props.params.hostID}
        />
      );
    } else {
      layoutComponent =
;
    }

    return (

{hostID}

Uptime: 2d 4h 33m

            {layoutComponent}

    );
  },
});

export default HostPage;
<|endoftext|>


<commit_before>db.failed_logins.createIndex({timestamp : 1})
db.logs.createIndex({timestamp : 1})
db.logs.createIndex({realm : 1})
db.logs.createIndex({visinst : 1})
db.logs.createIndex({pn : 1})
db.realms.createIndex({realm : 1})
db.mac_count.createIndex({timestamp : 1})
db.roaming.createIndex({timestamp : 1})
db.users_mac.createIndex({username : 1})
db.shared_mac.createIndex({mac_address : 1})
db.heat_map.createIndex({timestamp : 1})
db.heat_map.createIndex({realm : 1})
<commit_msg>update indexes<commit_after>db.failed_logins.createIndex({timestamp : 1})
db.logs.createIndex({timestamp : 1})
db.logs.createIndex({realm : 1})
db.logs.createIndex({visinst : 1})
db.logs.createIndex({pn : 1})
db.realms.createIndex({realm : 1})
db.mac_count.createIndex({timestamp : 1})
db.roaming.createIndex({timestamp : 1})
db.users_mac.createIndex({username : 1})
db.shared_mac.createIndex({mac_address : 1})
db.heat_map.createIndex({timestamp : 1})
db.heat_map.createIndex({realm : 1})
db.succ_logins.createIndex({timestamp : 1})
db.succ_logins.createIndex({username : 1})
<|endoftext|>


<commit_before>'use strict';

describe('Service: uint', function () {

  // load the service's module
  beforeEach(module('flowsimUiApp'));

  // instantiate service
  var UInt;
  beforeEach(inject(function (_UInt_) {
    UInt = _UInt_;
  }));

  it('UInt Import', function () {
    expect(!!UInt).toBe(true);
  });

  it('howMany_, maxFrom_', function () {
    var tmp;

    expect(UInt.howManyBits(0)).toBe(1);
    expect(UInt.howManyBits(0x0)).toBe(1);
    expect(UInt.howManyBytes(0)).toBe(1);
    expect(UInt.howManyBytes(0x0)).toBe(1);

    expect(UInt.howManyBits(0)).toBe(1);

    tmp = 1;
    _.each(_.range(31), function(i) {
      expect(UInt.howManyBits(tmp)).toBe(i+1);
      tmp <<= 1;
    });
    expect(UInt.howManyBytes(0)).toBe(1);

    tmp = 1;
    _.each(_.range(31), function(i) {
      expect(UInt.howManyBytes(tmp)).toBe(Math.ceil((i+1)/8));
      tmp <<= 1;
    });

    _.each(_.range(31), function(i) {
      expect(UInt.maxFromBits(i+1)).toBe(Math.pow(2, i+1)-1);
    });

    _.each(_.range(4), function(i) {
      expect(UInt.maxFromBytes(i+1)).toBe(Math.pow(2, (8*(i+1)))-1);
    });
  });

  it('UInt(null, 0x1ffff, 2) should fail', function() {
    expect(function() {
      new UInt.UInt(null, 0x1ffff, 2)
    }).toThrow();
  });

  it('UInt(null, "0x1ffff", 2) should fail', function() {
    expect(function() {
      new UInt.UInt(null, '0x1ffff', 2)
    }).toThrow();
  });

  it('UInt(null, 0x800, 2).toString()', function() {
    var v = new UInt.UInt(null, '0x800', 2);
    expect(v.toString(16)).toBe('0x0800');
  });

  it('UInt(null, "0xx0000", 2)', function() {
    expect(function() {
      new UInt.UInt(null, '0xx0000', 2);
    }).toThrow();
  });

  it('UInt Construction', function() {
    expect(function() {
      new UInt.UInt(null, 'q');
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, '0xx00');
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, 1.2);
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, null, 0);
    }).toThrow();
  });

  it('UInt No-Throw Construction', function() {
    var type_ip  = new UInt.UInt(null, 0x0800, 2);
    var type_arp = new UInt.UInt(null, 0x0806, 2);
    var type     = new UInt.UInt(null, null, 2);

    var inval  = new UInt.UInt(null, 0x0a0101f0, 4);
    var outval = new UInt.UInt(null, 0x0b0101f0, 4);
  });

  it('UInt Match - Ethernet Type', function() {
    var type1 = new UInt.UInt(null, 0x0800, 2);
    var type2 = new UInt.UInt(null, 0x0806, 2);

    var exact1 = new UInt.Match(null,
        new UInt.UInt(null, 0x0800, 2),
        new UInt.UInt(null, 0xffff, 2));

    var exact2 = new UInt.Match.mkExact(type1);

    var wildcard1 = new UInt.Match(null,
        new UInt.UInt(null, 0x0000, 2),
        new UInt.UInt(null, 0x0000, 2));

    var wildcard2 = new UInt.Match.mkWildcard(type1);
    var wildcard3 = new UInt.Match.mkWildcard(2);

    expect(exact1.match(type1)).toBe(true);
    expect(exact2.match(type1)).toBe(true);
    expect(wildcard1.match(type1)).toBe(true);
    expect(wildcard2.match(type1)).toBe(true);
    expect(wildcard3.match(type1)).toBe(true);

    expect(exact1.match(type2)).toBe(false);
    expect(exact2.match(type2)).toBe(false);
    expect(wildcard1.match(type2)).toBe(true);
    expect(wildcard2.match(type2)).toBe(true);
    expect(wildcard3.match(type2)).toBe(true);

  });

  it('UInt Match - Ethernet MAC', function() {
    var empty     = new UInt.UInt(null, null, 6);
    var broadcast = (new UInt.UInt(null, null, 6)).neg();

    var mac1 = new UInt.UInt(null, [0, 1, 2, 3, 4, 5], 6);
    var mac2 = new UInt.UInt(null, [0, 1, 2, 3, 4, 6], 6);

    var exact1_mac1 = new UInt.Match(null,
        new UInt.UInt(null, [0, 1, 2, 3, 4, 5], 6),
        new UInt.UInt(null, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 6));
    var exact2_mac1 = new UInt.Match.mkExact(mac1);

    var exact1_mac2 = new UInt.Match(null,
        new UInt.UInt(null, [0, 1, 2, 3, 4, 6], 6),
        new UInt.UInt(null, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 6));
    var exact2_mac2 = new UInt.Match.mkExact(mac2);

    var wildcard1_mac1 = new UInt.Match(null,
        new UInt.UInt(null, null, 6),
        new UInt.UInt(null, null, 6));
    var wildcard2_mac1 = new UInt.Match.mkWildcard(mac1);
    var wildcard3_mac1 = new UInt.Match.mkWildcard(6);

    var wildcard1_mac2 = new UInt.Match(null,
        new UInt.UInt(null, null, 6),
        new UInt.UInt(null, null, 6));
    var wildcard2_mac2 = new UInt.Match.mkWildcard(mac2);
    var wildcard3_mac2 = new UInt.Match.mkWildcard(6);

    expect(exact1_mac1.match(mac1)).toBe(true);
    expect(exact2_mac1.match(mac1)).toBe(true);
    expect(wildcard1_mac1.match(mac1)).toBe(true);
    expect(wildcard2_mac1.match(mac1)).toBe(true);
    expect(wildcard3_mac1.match(mac1)).toBe(true);

    expect(exact1_mac1.match(mac2)).toBe(false);
    expect(exact2_mac1.match(mac2)).toBe(false);
    expect(wildcard1_mac1.match(mac2)).toBe(true);
    expect(wildcard2_mac1.match(mac2)).toBe(true);
    expect(wildcard3_mac1.match(mac2)).toBe(true);
  });

  it('UInt Match', function() {
    var left = new UInt.UInt(null, 0xffffffff);
    var mask = new UInt.UInt(null, 0x0000ff00);
    var right = new UInt.UInt(null, 0x11223344);

    var r = UInt.or(UInt.and(mask, right), UInt.and(UInt.neg(mask), left));
  });

});
<commit_msg>latest<commit_after>'use strict';

describe('Service: uint', function () {

  // load the service's module
  beforeEach(module('flowsimUiApp'));

  // instantiate service
  var UInt;
  beforeEach(inject(function (_UInt_) {
    UInt = _UInt_;
  }));

  it('UInt Import', function () {
    expect(!!UInt).toBe(true);
  });

  it('howMany_, maxFrom_', function () {
    var tmp;

    expect(UInt.howManyBits(0)).toBe(1);
    expect(UInt.howManyBits(0x0)).toBe(1);
    expect(UInt.howManyBytes(0)).toBe(1);
    expect(UInt.howManyBytes(0x0)).toBe(1);

    expect(UInt.howManyBits(0)).toBe(1);

    tmp = 1;
    _.each(_.range(31), function(i) {
      expect(UInt.howManyBits(tmp)).toBe(i+1);
      tmp <<= 1;
    });
    expect(UInt.howManyBytes(0)).toBe(1);

    tmp = 1;
    _.each(_.range(31), function(i) {
      expect(UInt.howManyBytes(tmp)).toBe(Math.ceil((i+1)/8));
      tmp <<= 1;
    });

    _.each(_.range(31), function(i) {
      expect(UInt.maxFromBits(i+1)).toBe(Math.pow(2, i+1)-1);
    });

    _.each(_.range(4), function(i) {
      expect(UInt.maxFromBytes(i+1)).toBe(Math.pow(2, (8*(i+1)))-1);
    });
  });

  it('UInt(null, 0x1ffff, 2) should fail', function() {
    expect(function() {
      new UInt.UInt(null, 0x1ffff, 2)
    }).toThrow();
  });

  it('UInt(null, "0x1ffff", 2) should fail', function() {
    expect(function() {
      new UInt.UInt(null, '0x1ffff', 2)
    }).toThrow();
  });

  it('UInt(null, 0x800, 2).toString()', function() {
    var v = new UInt.UInt(null, '0x800', 2);
    expect(v.toString(16)).toBe('0x0800');
  });

  it('UInt(null, "0xx0000", 2)', function() {
    expect(function() {
      new UInt.UInt(null, '0xx0000', 2);
    }).toThrow();
  });

  it('UInt Construction', function() {
    expect(function() {
      new UInt.UInt(null, 'q');
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, '0xx00');
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, 1.2);
    }).toThrow();
    expect(function() {
      new UInt.UInt(null, null, 0);
    }).toThrow();
  });

  it('UInt No-Throw Construction', function() {
    var type_ip  = new UInt.UInt(null, 0x0800, 2);
    var type_arp = new UInt.UInt(null, 0x0806, 2);
    var type     = new UInt.UInt(null, null, 2);

    var inval  = new UInt.UInt(null, 0x0a0101f0, 4);
    var outval = new UInt.UInt(null, 0x0b0101f0, 4);
  });

  it('UInt Match - Ethernet Type', function() {
    var type1 = new UInt.UInt(null, 0x0800, 2);
    var type2 = new UInt.UInt(null, 0x0806, 2);

    var exact1 = new UInt.Match(null,
        new UInt.UInt(null, 0x0800, 2),
        new UInt.UInt(null, 0xffff, 2));

    var exact2 = new UInt.Match.mkExact(type1);

    var wildcard1 = new UInt.Match(null,
        new UInt.UInt(null, 0x0000, 2),
        new UInt.UInt(null, 0x0000, 2));

    var wildcard2 = new UInt.Match.mkWildcard(type1);
    var wildcard3 = new UInt.Match.mkWildcard(2);

    expect(exact1.match(type1)).toBe(true);
    expect(exact2.match(type1)).toBe(true);
    expect(wildcard1.match(type1)).toBe(true);
    expect(wildcard2.match(type1)).toBe(true);
    expect(wildcard3.match(type1)).toBe(true);

    expect(exact1.match(type2)).toBe(false);
    expect(exact2.match(type2)).toBe(false);
    expect(wildcard1.match(type2)).toBe(true);
    expect(wildcard2.match(type2)).toBe(true);
    expect(wildcard3.match(type2)).toBe(true);

  });

  it('UInt Match - Ethernet MAC', function() {
    var empty     = new UInt.UInt(null, null, 6);
    var broadcast = (new UInt.UInt(null, null, 6)).neg();

    var mac1 = new UInt.UInt(null, [0, 1, 2, 3, 4, 5], 6);
    var mac2 = new UInt.UInt(null, [0, 1, 2, 3, 4, 6], 6);

    var exact1_mac1 = new UInt.Match(null,
        new UInt.UInt(null, [0, 1, 2, 3, 4, 5], 6),
        new UInt.UInt(null, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 6));
    var exact2_mac1 = new UInt.Match.mkExact(mac1);

    var exact1_mac2 = new UInt.Match(null,
        new UInt.UInt(null, [0, 1, 2, 3, 4, 6], 6),
        new UInt.UInt(null, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 6));
    var exact2_mac2 = new UInt.Match.mkExact(mac2);

    var wildcard1_mac1 = new UInt.Match(null,
        new UInt.UInt(null, null, 6),
        new UInt.UInt(null, null, 6));
    var wildcard2_mac1 = new UInt.Match.mkWildcard(mac1);
    var wildcard3_mac1 = new UInt.Match.mkWildcard(6);

    var wildcard1_mac2 = new UInt.Match(null,
        new UInt.UInt(null, null, 6),
        new UInt.UInt(null, null, 6));
    var wildcard2_mac2 = new UInt.Match.mkWildcard(mac2);
    var wildcard3_mac2 = new UInt.Match.mkWildcard(6);

    expect(exact1_mac1.match(mac1)).toBe(true);
    expect(exact2_mac1.match(mac1)).toBe(true);
    expect(wildcard1_mac1.match(mac1)).toBe(true);
    expect(wildcard2_mac1.match(mac1)).toBe(true);
    expect(wildcard3_mac1.match(mac1)).toBe(true);
    expect(exact1_mac1.match(mac2)).toBe(false);
    expect(exact2_mac1.match(mac2)).toBe(false);
    expect(wildcard1_mac1.match(mac2)).toBe(true);
    expect(wildcard2_mac1.match(mac2)).toBe(true);
    expect(wildcard3_mac1.match(mac2)).toBe(true);

    expect(exact1_mac2.match(mac1)).toBe(false);
    expect(exact2_mac2.match(mac1)).toBe(false);
    expect(wildcard1_mac2.match(mac1)).toBe(true);
    expect(wildcard2_mac2.match(mac1)).toBe(true);
    expect(wildcard3_mac2.match(mac1)).toBe(true);
    expect(exact1_mac2.match(mac2)).toBe(true);
    expect(exact2_mac2.match(mac2)).toBe(true);
    expect(wildcard1_mac2.match(mac2)).toBe(true);
    expect(wildcard2_mac2.match(mac2)).toBe(true);
    expect(wildcard3_mac2.match(mac2)).toBe(true);
  });

  it('UInt Match', function() {
    var left = new UInt.UInt(null, 0xffffffff);
    var mask = new UInt.UInt(null, 0x0000ff00);
    var right = new UInt.UInt(null, 0x11223344);

    var r = UInt.or(UInt.and(mask, right), UInt.and(UInt.neg(mask), left));
  });

});
<|endoftext|>


<commit_before>const argv = require('yargs').argv
const path = require('path')
const fs = require('fs')
const Config = require('webpack-configurator')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const env = process.env.NODE_ENV || 'development'
const config = new Config()
const directory = process.cwd()
const isDev = (!argv.production && env === 'development')
const fontsPrefix = 'fonts'

const myPackage = require(directory + '/package.json')

const modulesDirectories = [
  `${directory}/node_modules`,
  `${__dirname}/node_modules`,
  'node_modules'
]

const hasModules = fs.existsSync(path.join(__dirname, 'node_modules'))

const resolveBabelPackages = packages => {
  const modulePath = hasModules ? 'node_modules' : '../../node_modules'
  return packages.map(p => { return path.resolve(__dirname, modulePath, p) })
}

const entry = {
  app: [ argv.entry || './src' ],
  theme: `skypager-themes!${directory}/package.json`,
  vendor: [
    'history',
    'jquery',
    'react',
    'react-dom',
    'react-redux',
    'react-router',
    'react-bootstrap',
    'redux',
    'redux-thunk',
    'redux-actions',
    'redux-simple-router'
  ]
}

if (isDev) { entry.app.unshift('webpack-hot-middleware/client') }

const platform = argv.platform || 'web'

config
  .merge({
    entry: entry,
    output: {
      path: path.join(directory, argv.outputPath || 'public'),
      filename: (argv.contentHash === false || isDev ? '[name].js' : '[name]-[hash].js'),
      publicPath: argv.publicPath === false ? '' : '/'
    },
    resolveLoader: {
      modulesDirectories: modulesDirectories.concat([ require.resolve('skypager-themes') ])
    },
    resolve: {
      modulesDirectories
    },
    devtool: 'eval'
  })

  .loader('js', {
    test: /\.jsx?$/,
    loader: 'babel',
    exclude: /(node_modules|bower_components)/,
    query: {
      presets: resolveBabelPackages(['babel-preset-react', 'babel-preset-es2015', 'babel-preset-stage-0']),
      plugins: resolveBabelPackages(['babel-plugin-transform-decorators-legacy']),
      env: {
        development: {
          presets: resolveBabelPackages(['babel-preset-react-hmre'])
        }
      }
    }
  })

  .loader('less', {
    test: /\.less$/,
    loader: isDev ? 'style!css?modules&localIdentName=[path]-[local]-[hash:base64:5]!postcss!less'
                    : ExtractTextPlugin.extract('style-loader', 'css-loader?modules&sourceMap!postcss-loader!less')

  })

  .loader('url-1', { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' })
  .loader('url-2', { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' })
  .loader('url-3', { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' })
  .loader('file', { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=' + fontsPrefix + '/&name=[path][name].[ext]' })
  .loader('url-4', { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' })
  .loader('url-5', { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' })

  .plugin('webpack-define', webpack.DefinePlugin, [{
    'process.env': {
      NODE_ENV: JSON.stringify(env)
    }
  }])

  .plugin('webpack-order', webpack.optimize.OccurenceOrderPlugin)
  .plugin('webpack-noerrors', webpack.NoErrorsPlugin)

  .plugin('common-chunks', webpack.optimize.CommonsChunkPlugin, [{ names: ['vendor'] }])

  .plugin('webpack-html', HtmlWebpackPlugin, [{
    template: `${__dirname}/templates/index.html`,
    hash: true,
    inject: 'body',
    filename: argv.outputFile || 'index.html'
  }])

// development
if (env == 'development') {
  config.plugin('webpack-hmr', webpack.HotModuleReplacementPlugin)
}

// production
if (env == 'production') {
  console.log('Were in production')

  config
    .merge({devtool: 'source-map'})

    .plugin('extract-text', ExtractTextPlugin, ['[name].[contenthash].css',{
      allChunks: true
    }])

    .plugin('webpack-uglify', webpack.optimize.UglifyJsPlugin, [{
      compress: {
        unused: true,
        dead_code: true
      },
      compressor: { warnings: false }
    }])
}

const userConfig = path.resolve(directory, './webpack.config.js')
if (fs.existsSync(userConfig)) {
  config.merge(require(userConfig))
}

if (argv.project) {
  config.merge({
    resolve: {
      alias: {
        'skypager-project-src': path.resolve(argv.project)
      }
    }
  })
}

if (argv.projectSnapshot) {
  config.merge({
    resolve: {
      alias: {
        'skypager-project-dist': path.resolve(argv.projectSnapshot)
      }
    }
  })
}

module.exports = config
<commit_msg>adding some additional argv<commit_after>const argv = require('yargs').argv
const path = require('path')
const fs = require('fs')

const assign = Object.assign
const Config = require('webpack-configurator')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const env = process.env.NODE_ENV || 'development'
const config = new Config()
const directory = process.cwd()
const isDev = (!argv.production && env === 'development')
const fontsPrefix = 'fonts'

const myPackage = require(directory + '/package.json')

const modulesDirectories = [
  `${directory}/node_modules`,
  `${__dirname}/node_modules`,
  'node_modules'
]

const hasModules = fs.existsSync(path.join(__dirname, 'node_modules'))

const resolveBabelPackages = packages => {
  const modulePath = hasModules ? 'node_modules' : '../../node_modules'
  return packages.map(p => { return path.resolve(__dirname, modulePath, p) })
}

const entry = {
  app: [ argv.entry || './src' ],
  theme: `skypager-themes!${directory}/package.json`
}

if (isDev) { entry.app.unshift('webpack-hot-middleware/client') }

const platform = argv.platform || 'web'

config
  .merge({
    entry: entry,
    output: {
      path: path.join(directory, argv.outputFolder || 'public'),
      filename: (argv.contentHash === false || isDev ? '[name].js' : '[name]-[hash].js'),
      publicPath: platform === 'electron' ? '' : '/'
    },
    resolveLoader: {
      modulesDirectories: modulesDirectories.concat([ require.resolve('skypager-themes') ])
    },
    resolve: {
      modulesDirectories
    },
    devtool: 'eval'
  })

  .loader('js', {
    test: /\.jsx?$/,
    loader: 'babel',
    exclude: /(node_modules|bower_components)/,
    query: {
      presets: resolveBabelPackages(['babel-preset-react', 'babel-preset-es2015', 'babel-preset-stage-0']),
      plugins: resolveBabelPackages(['babel-plugin-transform-decorators-legacy']),
      env: {
        development: {
          presets: resolveBabelPackages(['babel-preset-react-hmre'])
        }
      }
    }
  })

  .loader('less', {
    test: /\.less$/,
    loader: isDev ? 'style!css?modules&localIdentName=[path]-[local]-[hash:base64:5]!postcss!less'
                    : ExtractTextPlugin.extract('style-loader', 'css-loader?modules&sourceMap!postcss-loader!less')

  })

  .loader('url-1', { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' })
  .loader('url-2', { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' })
  .loader('url-3', { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' })
  .loader('file', { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=' + fontsPrefix + '/&name=[path][name].[ext]' })
  .loader('url-4', { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=' + fontsPrefix + '/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' })
  .loader('url-5', { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' })

  .plugin('webpack-define', webpack.DefinePlugin, [{
    'process.env': {
      NODE_ENV: JSON.stringify(env)
    }
  }])

  .plugin('webpack-order', webpack.optimize.OccurenceOrderPlugin)
  .plugin('webpack-noerrors', webpack.NoErrorsPlugin)

  .plugin('webpack-html', HtmlWebpackPlugin, [{
    template: argv.htmlTemplatePath || `${__dirname}/templates/index.html`,
    hash: false,
    inject: 'body',
    filename: argv.htmlFilename || (platform === 'web' ? '200.html' : 'index.html')
  }])

// development
if (env == 'development') {
  config.plugin('webpack-hmr', webpack.HotModuleReplacementPlugin)
}

// production
if (env == 'production') {
  config
    .merge({
      devtool: 'source-map'
    })

    .plugin('extract-text', ExtractTextPlugin, [{
      allChunks: true
    }])

    .plugin('webpack-uglify', webpack.optimize.UglifyJsPlugin, [{
      compressor: { warnings: false },
      compress: {
        unused: true,
        dead_code: true
      }
    }])
}

if (argv.vendorLibraries !== false && !argv.useExternalVendorLibraries) {
  config.merge({
    entry: assign(entry, {
      vendor: [
        'history',
        'jquery',
        'react',
        'react-dom',
        'react-redux',
        'react-router',
        'react-bootstrap',
        'redux',
        'redux-thunk',
        'redux-actions',
        'redux-simple-router'
      ]
    })
  }).plugin('common-chunks', webpack.optimize.CommonsChunkPlugin, [{ names: ['vendor'] }])
}

if (argv.useExternalVendorLibraries) {
  config.merge({
    externals: {
      'jquery': 'jQuery',
      'react': 'React',
      'react-dom': 'ReactDOM',
      'react-bootstrap': 'ReactBootstrap',
      'redux': 'Redux',
      'react-router': 'Router',
      'redux-actions': 'ReduxActions',
      'redux-thunk': 'ReduxThunk',
      'redux-simple-router': 'ReduxSimpleRouter',
      'history': 'History'
    }
  })
}

const userConfig = path.resolve(directory, './webpack.config.js')
if (fs.existsSync(userConfig)) {
  config.merge(require(userConfig))
}

if (argv.project) {
  config.merge({
    resolve: {
      alias: {
        'skypager-project-src': path.resolve(argv.project)
      }
    }
  })
}

if (argv.projectSnapshot) {
  config.merge({
    resolve: {
      alias: {
        'skypager-project-dist': path.resolve(argv.projectSnapshot)
      }
    }
  })
}

module.exports = config
<|endoftext|>


<commit_before>/*
  Copyright (c) Microsoft. All rights reserved.
  Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
// Module dependencies
var fs = require('fs'),
    path = require('path'),
    Q = require('q'),
    glob = require('glob'),
    semver = require('semver'),
    utilities = require('./lib/ttb-util.js'),
    cache = require('./lib/ttb-cache.js'),
    exec = Q.nfbind(require('child_process').exec);

// Constants
var SUPPORT_PLUGIN_PATH = path.resolve(__dirname, 'cordova-plugin-vs-taco-support'),
    SUPPORT_PLUGIN_ID = 'cordova-plugin-vs-taco-support';

// Global vars
var defaultConfig = {
        projectPath: process.cwd(),
        addSupportPlugin: true,
        nodePackageName: cache.CORDOVA,
        moduleVersion: undefined
    };

// Method to set options
function configure(config) {
    defaultConfig = utilities.parseConfig(config, defaultConfig);
}

// Gets and/or downloads the appropriate cordova node module for use based on options or taco.json
// Also installs support plugin if not already in the project
function setupCordova(config) {
    config = utilities.parseConfig(config, defaultConfig);

    // Check if Cordova already loaded
    var cdv = cache.getLoadedModule(config);
    if(cdv) return Q(cdv);

    return cache.cacheModule(config).then(function(result) {
            process.chdir(config.projectPath);
            config.moduleVersion = result.version;
            return cache.loadModule(result.path);
        });
}

function addSupportPluginIfRequested(cachedModule, config) {
    if (cachedModule.cordova) {
        cachedModule = cachedModule.cordova;
    }

    // Unless the user very specifically asked to not get it, we should add the support plugin
    var addSupportPlugin = config.addSupportPlugin !== false;
    if (addSupportPlugin && config.projectPath && !utilities.fileExistsSync(path.join(config.projectPath, 'plugins', SUPPORT_PLUGIN_ID))) {
        process.chdir(config.projectPath);
        console.log('Adding support plugin.');
        return cachedModule.raw.plugin('add', SUPPORT_PLUGIN_PATH).then(function () { return cachedModule; });
    }

    return Q(cachedModule);
}

// It's possible that checking in the platforms folder on Windows and then checking out and building
// the project on OSX can cause the eXecution bit on the platform version files to be cleared,
// resulting in errors when performing project operations. This method restores it if needed.
function applyExecutionBitFix(platforms) {
    // Only bother if we're on OSX and are after platform add for iOS itself (still need to run for other platforms)
    if (process.platform !=="darwin") {
        return Q();
    }

    // Generate the script to set execute bits for installed platforms
    var script ="";
    platforms.forEach(function(platform) {
        var platformCordovaDir = "platforms/" + platform + "/cordova";

        if (tu.fileExistsSync(platformCordovaDir)) {
            script += "find -E " + platformCordovaDir + " -type f -regex \"[^.(LICENSE)]*\" -exec chmod +x {} +\n"
        }
    });

    // Run script
    return exec(script);
}

// Main build method
function buildProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == 'string') {
        cordovaPlatforms = [cordovaPlatforms];
    }

    if(!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig);
    if (appendedVersion) {
        appendedVersion = '@' + appendedVersion;
    } else {
        appendedVersion = '';
    }

    return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) {
            switch (compatibilityResult) {
                case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios:
                    throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
                case utilities.NodeCompatibilityResult.IncompatibleVersion5:
                    throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
            }

            return setupCordova();
        }).then(function(cordova) {
            return applyExecutionBitFix(cordovaPlatforms).then(function() {
                 return Q(cordova);
             }, function(err) {
                 return Q(cordova);
             });
        }).then(function(cordova) {
            return addSupportPluginIfRequested(cordova, defaultConfig);
        }).then(function (cordova) {
        // Add platforms if not done already
        var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova);
        //Build each platform with args in args object
        cordovaPlatforms.forEach(function (platform) {
            promise = promise.then(function () {
                // Build app with platform specific args if specified
                var callArgs = utilities.getCallArgs(platform, args);
                console.log('Queueing build for platform ' + platform + ' w/options: ' + callArgs.options || 'none');
                return cordova.raw.build(callArgs);
            });
        });

        return promise;
    });
}

// Prep for build by adding platforms and setting environment variables
function _addPlatformsToProject(cordovaPlatforms, projectPath, cordova) {
    var promise = Q();
    cordovaPlatforms.forEach(function (platform) {
        if (!utilities.fileExistsSync(path.join(projectPath, 'platforms', platform))) {
            promise = promise.then(function () { return cordova.raw.platform('add', platform); });
        } else {
            console.log('Platform ' + platform + ' already added.');
        }
    });

    return promise;
}

// Package project method - Just for iOS currently
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == 'string') {
        cordovaPlatforms = [cordovaPlatforms];
    }
    if(!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    return setupCordova().then(function (cordova) {
        var promise = Q(cordova);
        cordovaPlatforms.forEach(function (platform) {
            if (platform == 'ios') {
                promise = promise.then(function() { return _createIpa(projectPath, args); });
            } else {
                console.log('Platform ' + platform + ' does not require a separate package step.');
            }
        });

        return promise;
    });
}

// Find the .app folder and use exec to call xcrun with the appropriate set of args
function _createIpa(projectPath, args) {

    return utilities.getInstalledPlatformVersion(projectPath, 'ios').then(function(version) {
        if(semver.lt(version, '3.9.0')) {
            var deferred = Q.defer();
            glob(projectPath + '/platforms/ios/build/device/*.app', function (err, matches) {
                if (err) {
                    deferred.reject(err);
                } else {
                    if (matches.length != 1) {
                        console.warn( 'Skipping packaging. Expected one device .app - found ' + matches.length);
                    } else {
                        var cmdString = 'xcrun -sdk iphoneos PackageApplication \'' + matches[0] + '\' -o \'' +
                            path.join(path.dirname(matches[0]), path.basename(matches[0], '.app')) + '.ipa\' ';

                        // Add additional command line args passed
                        var callArgs = utilities.getCallArgs('ios', args);
                        callArgs.options.forEach(function (arg) {
                            cmdString += ' ' + arg;
                        });

                        console.log('Exec: ' + cmdString);
                        return exec(cmdString)
                            .then(utilities.handleExecReturn)
                            .fail(function(err) {
                                deferred.reject(err);
                            })
                            .done(function() {
                                deferred.resolve();
                            });
                    }
                }
            });

            return deferred.promise;
        } else {
            console.log('Skipping packaging. Detected cordova-ios verison that auto-creates ipa.');
        }
    });
}

// Public methods
module.exports = {
    configure: configure,
    setupCordova: setupCordova,
    buildProject: buildProject,
    packageProject: packageProject,
    getInstalledPlatformVersion: utilities.getInstalledPlatformVersion,
    getVersionForNpmPackage: function(config) {
        var version = cache.getModuleVersionFromConfig(config);
        return utilities.getVersionForNpmPackage(config.nodePackageName + (version ? ('@' + version) : ''));
    },
    cacheModule: function(config) {
        config = utilities.parseConfig(config, defaultConfig);
        return cache.cacheModule(config);
    }
};
<commit_msg>Fix missed rename<commit_after>/*
  Copyright (c) Microsoft. All rights reserved.
  Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
// Module dependencies
var fs = require('fs'),
    path = require('path'),
    Q = require('q'),
    glob = require('glob'),
    semver = require('semver'),
    utilities = require('./lib/ttb-util.js'),
    cache = require('./lib/ttb-cache.js'),
    exec = Q.nfbind(require('child_process').exec);

// Constants
var SUPPORT_PLUGIN_PATH = path.resolve(__dirname, 'cordova-plugin-vs-taco-support'),
    SUPPORT_PLUGIN_ID = 'cordova-plugin-vs-taco-support';

// Global vars
var defaultConfig = {
        projectPath: process.cwd(),
        addSupportPlugin: true,
        nodePackageName: cache.CORDOVA,
        moduleVersion: undefined
    };

// Method to set options
function configure(config) {
    defaultConfig = utilities.parseConfig(config, defaultConfig);
}

// Gets and/or downloads the appropriate cordova node module for use based on options or taco.json
// Also installs support plugin if not already in the project
function setupCordova(config) {
    config = utilities.parseConfig(config, defaultConfig);

    // Check if Cordova already loaded
    var cdv = cache.getLoadedModule(config);
    if(cdv) return Q(cdv);

    return cache.cacheModule(config).then(function(result) {
            process.chdir(config.projectPath);
            config.moduleVersion = result.version;
            return cache.loadModule(result.path);
        });
}

function addSupportPluginIfRequested(cachedModule, config) {
    if (cachedModule.cordova) {
        cachedModule = cachedModule.cordova;
    }

    // Unless the user very specifically asked to not get it, we should add the support plugin
    var addSupportPlugin = config.addSupportPlugin !== false;
    if (addSupportPlugin && config.projectPath && !utilities.fileExistsSync(path.join(config.projectPath, 'plugins', SUPPORT_PLUGIN_ID))) {
        process.chdir(config.projectPath);
        console.log('Adding support plugin.');
        return cachedModule.raw.plugin('add', SUPPORT_PLUGIN_PATH).then(function () { return cachedModule; });
    }

    return Q(cachedModule);
}

// It's possible that checking in the platforms folder on Windows and then checking out and building
// the project on OSX can cause the eXecution bit on the platform version files to be cleared,
// resulting in errors when performing project operations. This method restores it if needed.
function applyExecutionBitFix(platforms) {
    // Only bother if we're on OSX and are after platform add for iOS itself (still need to run for other platforms)
    if (process.platform !=="darwin") {
        return Q();
    }

    // Generate the script to set execute bits for installed platforms
    var script ="";
    platforms.forEach(function(platform) {
        var platformCordovaDir = "platforms/" + platform + "/cordova";

        if (utilities.fileExistsSync(platformCordovaDir)) {
            script += "find -E " + platformCordovaDir + " -type f -regex \"[^.(LICENSE)]*\" -exec chmod +x {} +\n"
        }
    });

    // Run script
    return exec(script);
}

// Main build method
function buildProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == 'string') {
        cordovaPlatforms = [cordovaPlatforms];
    }

    if(!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig);
    if (appendedVersion) {
        appendedVersion = '@' + appendedVersion;
    } else {
        appendedVersion = '';
    }

    return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) {
            switch (compatibilityResult) {
                case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios:
                    throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
                case utilities.NodeCompatibilityResult.IncompatibleVersion5:
                    throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
            }

            return setupCordova();
        }).then(function(cordova) {
            return applyExecutionBitFix(cordovaPlatforms).then(function() {
                 return Q(cordova);
             }, function(err) {
                 return Q(cordova);
             });
        }).then(function(cordova) {
            return addSupportPluginIfRequested(cordova, defaultConfig);
        }).then(function (cordova) {
        // Add platforms if not done already
        var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova);
        //Build each platform with args in args object
        cordovaPlatforms.forEach(function (platform) {
            promise = promise.then(function () {
                // Build app with platform specific args if specified
                var callArgs = utilities.getCallArgs(platform, args);
                console.log('Queueing build for platform ' + platform + ' w/options: ' + callArgs.options || 'none');
                return cordova.raw.build(callArgs);
            });
        });

        return promise;
    });
}

// Prep for build by adding platforms and setting environment variables
function _addPlatformsToProject(cordovaPlatforms, projectPath, cordova) {
    var promise = Q();
    cordovaPlatforms.forEach(function (platform) {
        if (!utilities.fileExistsSync(path.join(projectPath, 'platforms', platform))) {
            promise = promise.then(function () { return cordova.raw.platform('add', platform); });
        } else {
            console.log('Platform ' + platform + ' already added.');
        }
    });

    return promise;
}

// Package project method - Just for iOS currently
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == 'string') {
        cordovaPlatforms = [cordovaPlatforms];
    }
    if(!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    return setupCordova().then(function (cordova) {
        var promise = Q(cordova);
        cordovaPlatforms.forEach(function (platform) {
            if (platform == 'ios') {
                promise = promise.then(function() { return _createIpa(projectPath, args); });
            } else {
                console.log('Platform ' + platform + ' does not require a separate package step.');
            }
        });

        return promise;
    });
}

// Find the .app folder and use exec to call xcrun with the appropriate set of args
function _createIpa(projectPath, args) {

    return utilities.getInstalledPlatformVersion(projectPath, 'ios').then(function(version) {
        if(semver.lt(version, '3.9.0')) {
            var deferred = Q.defer();
            glob(projectPath + '/platforms/ios/build/device/*.app', function (err, matches) {
                if (err) {
                    deferred.reject(err);
                } else {
                    if (matches.length != 1) {
                        console.warn( 'Skipping packaging. Expected one device .app - found ' + matches.length);
                    } else {
                        var cmdString = 'xcrun -sdk iphoneos PackageApplication \'' + matches[0] + '\' -o \'' +
                            path.join(path.dirname(matches[0]), path.basename(matches[0], '.app')) + '.ipa\' ';

                        // Add additional command line args passed
                        var callArgs = utilities.getCallArgs('ios', args);
                        callArgs.options.forEach(function (arg) {
                            cmdString += ' ' + arg;
                        });

                        console.log('Exec: ' + cmdString);
                        return exec(cmdString)
                            .then(utilities.handleExecReturn)
                            .fail(function(err) {
                                deferred.reject(err);
                            })
                            .done(function() {
                                deferred.resolve();
                            });
                    }
                }
            });

            return deferred.promise;
        } else {
            console.log('Skipping packaging. Detected cordova-ios verison that auto-creates ipa.');
        }
    });
}

// Public methods
module.exports = {
    configure: configure,
    setupCordova: setupCordova,
    buildProject: buildProject,
    packageProject: packageProject,
    getInstalledPlatformVersion: utilities.getInstalledPlatformVersion,
    getVersionForNpmPackage: function(config) {
        var version = cache.getModuleVersionFromConfig(config);
        return utilities.getVersionForNpmPackage(config.nodePackageName + (version ? ('@' + version) : ''));
    },
    cacheModule: function(config) {
        config = utilities.parseConfig(config, defaultConfig);
        return cache.cacheModule(config);
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var loadRoleBasedActionURL = function (action, rolename) {
    href = $("#ast-container").data("app-context") + "role/" + action + "/?rolename=" + encodeURIComponent(rolename);
    $(location).attr('href', href);
};

$(function () {
    var sortableElem = '.wr-sortable';
    $(sortableElem).sortable({
        beforeStop: function () {
            $(this).sortable('toArray');
        }
    });
    $(sortableElem).disableSelection();
});

var apiBasePath = "/api/device-mgt/v1.0";
var modalPopup = ".modal";
var modalPopupContainer = modalPopup + " .modal-content";
var modalPopupContent = modalPopup + " .modal-content";
var body = "body";
var isInit = true;

/**
 *
 * Fires the res_text when ever a data table redraw occurs making
 * the font icons change the size to respective screen resolution.
 *
 */
$(document).on('draw.dt', function () {
    $(".icon .text").res_text(0.2);
});

/*
 * set popup maximum height function.
 */
function setPopupMaxHeight() {
    $(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
    $(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}

/*
 * show popup function.
 */
function showPopup() {
    $(modalPopup).modal('show');
    //setPopupMaxHeight();
}

/*
 * hide popup function.
 */
function hidePopup() {
    $(modalPopupContent).html('');
    $(modalPopup).modal('hide');
    $('body').removeClass('modal-open').css('padding-right','0px');
    $('.modal-backdrop').remove();
}

/**
 * Following function would execute
 * when a user clicks on the list item
 * initial mode and with out select mode.
 */
function InitiateViewOption() {
    // $(location).attr('href', $(this).data("url"));
}

function loadRoles() {
    var loadingContent = $("#loading-content");
    loadingContent.show();

    var dataFilter = function (data) {
        data = JSON.parse(data);

        var objects = [];

        $(data.roles).each(function (index) {
            objects.push(
                {
                    name: data.roles[index],
                    DT_RowId: "role-" + data.roles[index]
                }
            )
        });

        var json = {
            "recordsTotal": data.count,
            "recordsFiltered": data.count,
            "data": objects
        };

        return JSON.stringify(json);
    };

    //noinspection JSUnusedLocalSymbols
    var fnCreatedRow = function (nRow, aData, iDataIndex) {
        $(nRow).attr('data-type', 'selectable');
    };

    //noinspection JSUnusedLocalSymbols
    var columns = [
        {
            class: "remove-padding icon-only content-fill",
            data: null,
            defaultContent: "
" +
            "" +
            "
"
        },
        {
            class: "fade-edge",
            data: "name",
            render: function (name, type, row, meta) {
                return '
' + name + 'role
';
            }
        },
        {
            class: "text-right content-fill text-left-on-grid-view no-wrap",
            data: null,
            render: function (data, type, row, meta) {
                return '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Edit' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Edit Permission' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Remove' +
                    '';
            }
        }
    ];

    var options = {
        "placeholder": "Search By Role Name",
        "searchKey": "filter"
    };
    var settings = {
        "sorting": false
    };

    $('#role-grid').datatables_extended_serverside_paging(settings, '/api/device-mgt/v1.0/roles?user-store=all', dataFilter, columns, fnCreatedRow, null, options);
    loadingContent.hide();

}

/**
 * Following click function would execute
 * when a user clicks on "Remove" link
 * on Role Listing page in WSO2 Devicemgt Console.
 */
$("#role-grid").on("click", ".remove-role-link", function () {
    var role = $(this).data("role");
    var userStore;
    if (role.indexOf('/') > 0) {
        userStore = role.substr(0, role.indexOf('/'));
        role = role.substr(role.indexOf('/') + 1);
    }
    var removeRoleAPI = apiBasePath + "/roles/" + encodeURIComponent(role);
    if (userStore) {
        removeRoleAPI += "?user-store=" + encodeURIComponent(userStore);
    }
    modalDialog.header('Do you really want to remove this role ?');
    modalDialog.footer('
Remove' +
        'Cancel
');
    modalDialog.show();

    $("a#remove-role-yes-link").click(function () {
        invokerUtil.delete(
            removeRoleAPI,
            function () {
                if (userStore) {
                    role = userStore + '/' + role;
                }
                $('[id="role-' + role + '"]').remove();
                modalDialog.header('Done. Role was successfully removed.');
                modalDialog.footer('
Ok
');
                $("a#remove-role-success-link").click(function () {
                    modalDialog.hide();
                });
            },
            function () {
                // $(modalPopupContent).html($('#remove-role-error-content').html());
                modalDialog.header('An unexpected error occurred. Please try again later.');
                modalDialog.footer('
Ok
');
                modalDialog.showAsError();
                $("a#remove-role-error-link").click(function () {
                    modalDialog.hide();
                });
            }
        );
    });

    $("a#remove-role-cancel-link").click(function () {
        modalDialog.hide();
    });
});

$(document).ready(function () {
    loadRoles();
});
<commit_msg>Removed 'role' suffix from roles listing page<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var loadRoleBasedActionURL = function (action, rolename) {
    href = $("#ast-container").data("app-context") + "role/" + action + "/?rolename=" + encodeURIComponent(rolename);
    $(location).attr('href', href);
};

$(function () {
    var sortableElem = '.wr-sortable';
    $(sortableElem).sortable({
        beforeStop: function () {
            $(this).sortable('toArray');
        }
    });
    $(sortableElem).disableSelection();
});

var apiBasePath = "/api/device-mgt/v1.0";
var modalPopup = ".modal";
var modalPopupContainer = modalPopup + " .modal-content";
var modalPopupContent = modalPopup + " .modal-content";
var body = "body";
var isInit = true;

/**
 *
 * Fires the res_text when ever a data table redraw occurs making
 * the font icons change the size to respective screen resolution.
 *
 */
$(document).on('draw.dt', function () {
    $(".icon .text").res_text(0.2);
});

/*
 * set popup maximum height function.
 */
function setPopupMaxHeight() {
    $(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
    $(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}

/*
 * show popup function.
 */
function showPopup() {
    $(modalPopup).modal('show');
    //setPopupMaxHeight();
}

/*
 * hide popup function.
 */
function hidePopup() {
    $(modalPopupContent).html('');
    $(modalPopup).modal('hide');
    $('body').removeClass('modal-open').css('padding-right','0px');
    $('.modal-backdrop').remove();
}

/**
 * Following function would execute
 * when a user clicks on the list item
 * initial mode and with out select mode.
 */
function InitiateViewOption() {
    // $(location).attr('href', $(this).data("url"));
}

function loadRoles() {
    var loadingContent = $("#loading-content");
    loadingContent.show();

    var dataFilter = function (data) {
        data = JSON.parse(data);

        var objects = [];

        $(data.roles).each(function (index) {
            objects.push(
                {
                    name: data.roles[index],
                    DT_RowId: "role-" + data.roles[index]
                }
            )
        });

        var json = {
            "recordsTotal": data.count,
            "recordsFiltered": data.count,
            "data": objects
        };

        return JSON.stringify(json);
    };

    //noinspection JSUnusedLocalSymbols
    var fnCreatedRow = function (nRow, aData, iDataIndex) {
        $(nRow).attr('data-type', 'selectable');
    };

    //noinspection JSUnusedLocalSymbols
    var columns = [
        {
            class: "remove-padding icon-only content-fill",
            data: null,
            defaultContent: "
" +
            "" +
            "
"
        },
        {
            class: "fade-edge",
            data: "name",
            render: function (name, type, row, meta) {
                return '
' + name + '
';
            }
        },
        {
            class: "text-right content-fill text-left-on-grid-view no-wrap",
            data: null,
            render: function (data, type, row, meta) {
                return '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Edit' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Edit Permission' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    '' +
                    'Remove' +
                    '';
            }
        }
    ];

    var options = {
        "placeholder": "Search By Role Name",
        "searchKey": "filter"
    };
    var settings = {
        "sorting": false
    };

    $('#role-grid').datatables_extended_serverside_paging(settings, '/api/device-mgt/v1.0/roles?user-store=all', dataFilter, columns, fnCreatedRow, null, options);
    loadingContent.hide();

}

/**
 * Following click function would execute
 * when a user clicks on "Remove" link
 * on Role Listing page in WSO2 Devicemgt Console.
 */
$("#role-grid").on("click", ".remove-role-link", function () {
    var role = $(this).data("role");
    var userStore;
    if (role.indexOf('/') > 0) {
        userStore = role.substr(0, role.indexOf('/'));
        role = role.substr(role.indexOf('/') + 1);
    }
    var removeRoleAPI = apiBasePath + "/roles/" + encodeURIComponent(role);
    if (userStore) {
        removeRoleAPI += "?user-store=" + encodeURIComponent(userStore);
    }
    modalDialog.header('Do you really want to remove this role ?');
    modalDialog.footer('
Remove' +
        'Cancel
');
    modalDialog.show();

    $("a#remove-role-yes-link").click(function () {
        invokerUtil.delete(
            removeRoleAPI,
            function () {
                if (userStore) {
                    role = userStore + '/' + role;
                }
                $('[id="role-' + role + '"]').remove();
                modalDialog.header('Done. Role was successfully removed.');
                modalDialog.footer('
Ok
');
                $("a#remove-role-success-link").click(function () {
                    modalDialog.hide();
                });
            },
            function () {
                // $(modalPopupContent).html($('#remove-role-error-content').html());
                modalDialog.header('An unexpected error occurred. Please try again later.');
                modalDialog.footer('
Ok
');
                modalDialog.showAsError();
                $("a#remove-role-error-link").click(function () {
                    modalDialog.hide();
                });
            }
        );
    });

    $("a#remove-role-cancel-link").click(function () {
        modalDialog.hide();
    });
});

$(document).ready(function () {
    loadRoles();
});
<|endoftext|>


<commit_before>import {NEUTRALS, BLUES} from 'src/shared/constants/influxColors'

// Styles for all things Annotations
const annotationColor = '255,255,255'
const annotationDragColor = '107,223,255'
const zIndexWindow = '1'
const zIndexAnnotation = '3'
const zIndexAnnotationActive = '4'
const timestampFontSize = '14px'
const timestampFontWeight = '600'

export const flagStyle = (mouseOver, dragging, hasDuration, isEndpoint) => {
  const baseStyle = {
    position: 'absolute',
    zIndex: '2',
  }
  let style = {
    ...baseStyle,
    top: '-3px',
    left: '-2px',
    width: '6px',
    height: '6px',
    backgroundColor: `rgb(${annotationColor})`,
    borderRadius: '50%',
    transition: 'background-color 0.25s ease, transform 0.25s ease',
  }

  if (hasDuration) {
    style = {
      ...baseStyle,
      top: '-6px',
      width: '0',
      height: '0',
      left: '0',
      border: '6px solid transparent',
      borderLeftColor: `rgb(${annotationColor})`,
      borderRadius: '0',
      background: 'none',
      transition: 'border-left-color 0.25s ease, transform 0.25s ease',
      transformOrigin: '0% 50%',
    }
  }

  if (isEndpoint) {
    style = {
      ...baseStyle,
      top: '-6px',
      width: '0',
      height: '0',
      left: 'initial',
      right: '0',
      border: '6px solid transparent',
      borderRightColor: `rgb(${annotationColor})`,
      borderRadius: '0',
      background: 'none',
      transition: 'border-right-color 0.25s ease, transform 0.25s ease',
      transformOrigin: '100% 50%',
    }
  }

  if (dragging) {
    if (hasDuration) {
      return {
        ...style,
        transform: 'scale(1.5,1.5)',
        borderLeftColor: `rgb(${annotationDragColor})`,
      }
    }

    if (isEndpoint) {
      return {
        ...style,
        transform: 'scale(1.5,1.5)',
        borderRightColor: `rgb(${annotationDragColor})`,
      }
    }

    return {
      ...style,
      transform: 'scale(1.5,1.5)',
      backgroundColor: `rgb(${annotationDragColor})`,
    }
  }

  if (mouseOver) {
    return {...style, transform: 'scale(1.5,1.5)'}
  }

  return style
}

export const clickAreaStyle = (dragging, editing) => {
  const style = {
    position: 'absolute',
    top: '-8px',
    left: editing ? '-5px' : '-7px',
    width: editing ? '12px' : '16px',
    height: editing ? 'calc(100% + 8px)' : '16px',
    zIndex: '4',
    cursor: editing ? 'col-resize' : 'default',
  }

  if (dragging) {
    return {
      ...style,
      width: '10000px',
      left: '-5000px',
      height: '10000px',
      top: '-5000px',
    }
  }

  return style
}

export const tooltipStyle = annotationState => {
  const {isDragging, isMouseOver} = annotationState
  const isVisible = isDragging || isMouseOver

  return {
    position: 'absolute',
    bottom: 'calc(100% + 6px)',
    left: '50%',
    transform: 'translateX(-50%)',
    backgroundColor: NEUTRALS[0],
    zIndex: '3',
    padding: '6px 12px',
    borderRadius: '4px',
    whiteSpace: 'nowrap',
    userSelect: 'none',
    display: isVisible ? 'flex' : 'none',
    boxShadow: `0 0 10px 2px ${NEUTRALS[2]}`,
  }
}

export const tooltipItemsStyle = {
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
}
export const tooltipTimestampStyle = {
  color: NEUTRALS[20],
  display: 'block',
  fontSize: timestampFontSize,
  fontWeight: timestampFontWeight,
}
export const tooltipInputContainer = {width: '100%', marginBottom: '4px'}
export const tooltipFormStyle = {
  display: 'inline-flex',
  alignItems: 'center',
  flexWrap: 'nowrap',
  width: '100%',
}
export const tooltipInputButton = {marginLeft: '2px'}
export const tooltipInput = {flex: '1 0 0'}

export const annotationStyle = (time, dygraph, isMouseOver, isDragging) => {
  // TODO: export and test this function
  const containerLeftPadding = 16
  const left = `${dygraph.toDomXCoord(time) + containerLeftPadding}px`
  const width = 2

  return {
    left,
    position: 'absolute',
    top: '8px',
    backgroundColor: `rgb(${isDragging
      ? annotationDragColor
      : annotationColor})`,
    height: 'calc(100% - 36px)',
    width: `${width}px`,
    transition: 'background-color 0.25s ease',
    transform: `translateX(-${width / 2}px)`, // translate should always be half with width to horizontally center the annotation pole
    visibility: 'visible',
    zIndex:
      isDragging || isMouseOver ? zIndexAnnotationActive : zIndexAnnotation,
  }
}

export const annotationWindowStyle = (annotation, dygraph) => {
  // TODO: export and test this function
  const [startX, endX] = dygraph.xAxisRange()
  const containerLeftPadding = 16
  const startTime = +annotation.startTime
  const endTime = +annotation.endTime

  let windowStartXCoord = dygraph.toDomXCoord(startTime)
  let windowEndXCoord = dygraph.toDomXCoord(endTime)
  let visibility = 'visible'

  if (startTime < startX) {
    windowStartXCoord = dygraph.toDomXCoord(startX)
  }

  if (endTime > endX) {
    windowEndXCoord = dygraph.toDomXCoord(endX)
  }

  if (endTime < startX || startTime > endX) {
    visibility = 'hidden'
  }

  const windowWidth = windowEndXCoord - windowStartXCoord
  const isDurationNegative = windowWidth < 0
  const foo = isDurationNegative ? windowWidth : 0

  const left = `${windowStartXCoord + containerLeftPadding + foo}px`
  const width = `${Math.abs(windowWidth)}px`

  const gradientStartColor = `rgba(${annotationColor},0.15)`
  const gradientEndColor = `rgba(${annotationColor},0)`

  return {
    left,
    position: 'absolute',
    top: '8px',
    background: `linear-gradient(to bottom, ${gradientStartColor} 0%,${gradientEndColor} 100%)`,
    height: 'calc(100% - 36px)',
    borderTop: `2px dotted rgba(${annotationColor},0.35)`,
    width,
    zIndex: zIndexWindow,
    visibility,
  }
}

// Styles for new Annotations
export const newAnnotationContainer = {
  position: 'absolute',
  zIndex: '9999',
  top: '8px',
  left: '16px',
  width: 'calc(100% - 32px)',
  height: 'calc(100% - 16px)',
  cursor: 'pointer',
}
export const newAnnotationCrosshairStyle = left => {
  const width = 2

  return {
    position: 'absolute',
    top: '0',
    left: `${left}px`,
    height: 'calc(100% - 20px)',
    width: `${width}px`,
    transform: `translateX(-${width / 2}px)`, // translate should always be half with width to horizontally center the comment pole
    background: `linear-gradient(to bottom, ${BLUES.hydrogen} 0%,${BLUES.pool} 100%)`,
    visibility: left ? 'visible' : 'hidden',
    transition: 'opacity 0.4s ease',
    zIndex: '5',
    cursor: 'pointer',
  }
}
export const newAnnotationTooltipStyle = isMouseHovering => {
  return {
    display: isMouseHovering ? 'flex' : 'none',
    flexDirection: 'column',
    alignItems: 'center',
    background: `linear-gradient(to bottom, ${BLUES.pool} 0%,${BLUES.ocean} 100%)`,
    borderRadius: '4px',
    padding: '6px 12px',
    position: 'absolute',
    bottom: 'calc(100% + 8px)',
    left: '50%',
    transform: 'translateX(-50%)',
    zIndex: '10',
  }
}
export const newAnnotationHelperStyle = {
  whiteSpace: 'nowrap',
  fontSize: '13px',
  lineHeight: '13px',
  fontWeight: '600',
  color: BLUES.neutrino,
  marginBottom: '4px',
}
export const newAnnotationTimestampStyle = {
  whiteSpace: 'nowrap',
  fontSize: timestampFontSize,
  lineHeight: timestampFontSize,
  fontWeight: timestampFontWeight,
  color: NEUTRALS[20],
}
export const circleFlagStyle = {
  position: 'absolute',
  zIndex: '2',
  top: '-3px',
  left: '-2px',
  width: '6px',
  height: '6px',
  backgroundColor: `rgb(${annotationDragColor})`,
  borderRadius: '50%',
  transition: 'background-color 0.25s ease, transform 0.25s ease',
}

export const leftFlagStyle = {
  position: 'absolute',
  zIndex: '2',
  top: '-6px',
  width: '0',
  height: '0',
  left: '0',
  border: '6px solid transparent',
  borderLeftColor: `rgb(${annotationDragColor})`,
  borderRightColor: 'transparent',
  borderRadius: '0',
  background: 'none',
  transition: 'border-left-color 0.25s ease, transform 0.25s ease',
  transformOrigin: '0% 50%',
}
export const rightFlagStyle = {
  position: 'absolute',
  zIndex: '2',
  top: '-6px',
  width: '0',
  height: '0',
  left: 'initial',
  right: '0',
  border: '6px solid transparent',
  borderRightColor: `rgb(${annotationDragColor})`,
  borderLeftColor: 'transparent',
  borderRadius: '0',
  background: 'none',
  transition: 'border-right-color 0.25s ease, transform 0.25s ease',
  transformOrigin: '100% 50%',
}

export const newAnnotationWindowStyle = (staticX, draggingX) => {
  // TODO: export and test this function

  const width = `${Math.abs(Number(draggingX) - Number(staticX))}px`

  let left

  if (draggingX > staticX) {
    left = `${staticX}px`
  } else {
    left = `${draggingX}px`
  }

  const gradientStartColor = `rgba(${annotationDragColor},0.15)`
  const gradientEndColor = `rgba(${annotationDragColor},0)`

  return {
    left,
    position: 'absolute',
    top: '0',
    background: `linear-gradient(to bottom, ${gradientStartColor} 0%,${gradientEndColor} 100%)`,
    height: 'calc(100% - 20px)',
    borderTop: `2px dotted rgba(${annotationDragColor},0.35)`,
    width,
    zIndex: '3',
    visibility: 'visible',
  }
}
<commit_msg>Scope function names under `style`<commit_after>import {NEUTRALS, BLUES} from 'src/shared/constants/influxColors'

// Styles for all things Annotations
const annotationColor = '255,255,255'
const annotationDragColor = '107,223,255'
const zIndexWindow = '1'
const zIndexAnnotation = '3'
const zIndexAnnotationActive = '4'
const timestampFontSize = '14px'
const timestampFontWeight = '600'

export const flag = (mouseOver, dragging, hasDuration, isEndpoint) => {
  const baseStyle = {
    position: 'absolute',
    zIndex: '2',
  }
  let style = {
    ...baseStyle,
    top: '-3px',
    left: '-2px',
    width: '6px',
    height: '6px',
    backgroundColor: `rgb(${annotationColor})`,
    borderRadius: '50%',
    transition: 'background-color 0.25s ease, transform 0.25s ease',
  }

  if (hasDuration) {
    style = {
      ...baseStyle,
      top: '-6px',
      width: '0',
      height: '0',
      left: '0',
      border: '6px solid transparent',
      borderLeftColor: `rgb(${annotationColor})`,
      borderRadius: '0',
      background: 'none',
      transition: 'border-left-color 0.25s ease, transform 0.25s ease',
      transformOrigin: '0% 50%',
    }
  }

  if (isEndpoint) {
    style = {
      ...baseStyle,
      top: '-6px',
      width: '0',
      height: '0',
      left: 'initial',
      right: '0',
      border: '6px solid transparent',
      borderRightColor: `rgb(${annotationColor})`,
      borderRadius: '0',
      background: 'none',
      transition: 'border-right-color 0.25s ease, transform 0.25s ease',
      transformOrigin: '100% 50%',
    }
  }

  if (dragging) {
    if (hasDuration) {
      return {
        ...style,
        transform: 'scale(1.5,1.5)',
        borderLeftColor: `rgb(${annotationDragColor})`,
      }
    }

    if (isEndpoint) {
      return {
        ...style,
        transform: 'scale(1.5,1.5)',
        borderRightColor: `rgb(${annotationDragColor})`,
      }
    }

    return {
      ...style,
      transform: 'scale(1.5,1.5)',
      backgroundColor: `rgb(${annotationDragColor})`,
    }
  }

  if (mouseOver) {
    return {...style, transform: 'scale(1.5,1.5)'}
  }

  return style
}

export const clickArea = (dragging, editing) => {
  const style = {
    position: 'absolute',
    top: '-8px',
    left: editing ? '-5px' : '-7px',
    width: editing ? '12px' : '16px',
    height: editing ? 'calc(100% + 8px)' : '16px',
    zIndex: '4',
    cursor: editing ? 'col-resize' : 'default',
  }

  if (dragging) {
    return {
      ...style,
      width: '10000px',
      left: '-5000px',
      height: '10000px',
      top: '-5000px',
    }
  }

  return style
}

export const tooltip = annotationState => {
  const {isDragging, isMouseOver} = annotationState
  const isVisible = isDragging || isMouseOver

  return {
    position: 'absolute',
    bottom: 'calc(100% + 6px)',
    left: '50%',
    transform: 'translateX(-50%)',
    backgroundColor: NEUTRALS[0],
    zIndex: '3',
    padding: '6px 12px',
    borderRadius: '4px',
    whiteSpace: 'nowrap',
    userSelect: 'none',
    display: isVisible ? 'flex' : 'none',
    boxShadow: `0 0 10px 2px ${NEUTRALS[2]}`,
  }
}

export const tooltipItems = {
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
}
export const tooltipTimestamp = {
  color: NEUTRALS[20],
  display: 'block',
  fontSize: timestampFontSize,
  fontWeight: timestampFontWeight,
}
export const tooltipInputContainer = {width: '100%', marginBottom: '4px'}
export const tooltipForm = {
  display: 'inline-flex',
  alignItems: 'center',
  flexWrap: 'nowrap',
  width: '100%',
}
export const tooltipInputButton = {marginLeft: '2px'}
export const tooltipInput = {flex: '1 0 0'}

export const annotation = (time, dygraph, isMouseOver, isDragging) => {
  // TODO: export and test this function
  const containerLeftPadding = 16
  const left = `${dygraph.toDomXCoord(time) + containerLeftPadding}px`
  const width = 2

  return {
    left,
    position: 'absolute',
    top: '8px',
    backgroundColor: `rgb(${isDragging
      ? annotationDragColor
      : annotationColor})`,
    height: 'calc(100% - 36px)',
    width: `${width}px`,
    transition: 'background-color 0.25s ease',
    transform: `translateX(-${width / 2}px)`, // translate should always be half with width to horizontally center the annotation pole
    visibility: 'visible',
    zIndex:
      isDragging || isMouseOver ? zIndexAnnotationActive : zIndexAnnotation,
  }
}

export const window = (annotation, dygraph) => {
  // TODO: export and test this function
  const [startX, endX] = dygraph.xAxisRange()
  const containerLeftPadding = 16
  const startTime = +annotation.startTime
  const endTime = +annotation.endTime

  let windowStartXCoord = dygraph.toDomXCoord(startTime)
  let windowEndXCoord = dygraph.toDomXCoord(endTime)
  let visibility = 'visible'

  if (startTime < startX) {
    windowStartXCoord = dygraph.toDomXCoord(startX)
  }

  if (endTime > endX) {
    windowEndXCoord = dygraph.toDomXCoord(endX)
  }

  if (endTime < startX || startTime > endX) {
    visibility = 'hidden'
  }

  const windowWidth = windowEndXCoord - windowStartXCoord
  const isDurationNegative = windowWidth < 0
  const foo = isDurationNegative ? windowWidth : 0

  const left = `${windowStartXCoord + containerLeftPadding + foo}px`
  const width = `${Math.abs(windowWidth)}px`

  const gradientStartColor = `rgba(${annotationColor},0.15)`
  const gradientEndColor = `rgba(${annotationColor},0)`

  return {
    left,
    position: 'absolute',
    top: '8px',
    background: `linear-gradient(to bottom, ${gradientStartColor} 0%,${gradientEndColor} 100%)`,
    height: 'calc(100% - 36px)',
    borderTop: `2px dotted rgba(${annotationColor},0.35)`,
    width,
    zIndex: zIndexWindow,
    visibility,
  }
}

// Styles for new Annotations
export const newContainer = {
  position: 'absolute',
  zIndex: '9999',
  top: '8px',
  left: '16px',
  width: 'calc(100% - 32px)',
  height: 'calc(100% - 16px)',
  cursor: 'pointer',
}
export const newCrosshair = left => {
  const width = 2

  return {
    position: 'absolute',
    top: '0',
    left: `${left}px`,
    height: 'calc(100% - 20px)',
    width: `${width}px`,
    transform: `translateX(-${width / 2}px)`, // translate should always be half with width to horizontally center the comment pole
    background: `linear-gradient(to bottom, ${BLUES.hydrogen} 0%,${BLUES.pool} 100%)`,
    visibility: left ? 'visible' : 'hidden',
    transition: 'opacity 0.4s ease',
    zIndex: '5',
    cursor: 'pointer',
  }
}
export const newTooltip = isMouseHovering => {
  return {
    display: isMouseHovering ? 'flex' : 'none',
    flexDirection: 'column',
    alignItems: 'center',
    background: `linear-gradient(to bottom, ${BLUES.pool} 0%,${BLUES.ocean} 100%)`,
    borderRadius: '4px',
    padding: '6px 12px',
    position: 'absolute',
    bottom: 'calc(100% + 8px)',
    left: '50%',
    transform: 'translateX(-50%)',
    zIndex: '10',
  }
}
export const newHelper = {
  whiteSpace: 'nowrap',
  fontSize: '13px',
  lineHeight: '13px',
  fontWeight: '600',
  color: BLUES.neutrino,
  marginBottom: '4px',
}
export const newTimestamp = {
  whiteSpace: 'nowrap',
  fontSize: timestampFontSize,
  lineHeight: timestampFontSize,
  fontWeight: timestampFontWeight,
  color: NEUTRALS[20],
}
export const circleFlag = {
  position: 'absolute',
  zIndex: '2',
  top: '-3px',
  left: '-2px',
  width: '6px',
  height: '6px',
  backgroundColor: `rgb(${annotationDragColor})`,
  borderRadius: '50%',
  transition: 'background-color 0.25s ease, transform 0.25s ease',
}

export const leftFlag = {
  position: 'absolute',
  zIndex: '2',
  top: '-6px',
  width: '0',
  height: '0',
  left: '0',
  border: '6px solid transparent',
  borderLeftColor: `rgb(${annotationDragColor})`,
  borderRightColor: 'transparent',
  borderRadius: '0',
  background: 'none',
  transition: 'border-left-color 0.25s ease, transform 0.25s ease',
  transformOrigin: '0% 50%',
}
export const rightFlag = {
  position: 'absolute',
  zIndex: '2',
  top: '-6px',
  width: '0',
  height: '0',
  left: 'initial',
  right: '0',
  border: '6px solid transparent',
  borderRightColor: `rgb(${annotationDragColor})`,
  borderLeftColor: 'transparent',
  borderRadius: '0',
  background: 'none',
  transition: 'border-right-color 0.25s ease, transform 0.25s ease',
  transformOrigin: '100% 50%',
}

export const newWindow = (staticX, draggingX) => {
  // TODO: export and test this function

  const width = `${Math.abs(Number(draggingX) - Number(staticX))}px`

  let left

  if (draggingX > staticX) {
    left = `${staticX}px`
  } else {
    left = `${draggingX}px`
  }

  const gradientStartColor = `rgba(${annotationDragColor},0.15)`
  const gradientEndColor = `rgba(${annotationDragColor},0)`

  return {
    left,
    position: 'absolute',
    top: '0',
    background: `linear-gradient(to bottom, ${gradientStartColor} 0%,${gradientEndColor} 100%)`,
    height: 'calc(100% - 20px)',
    borderTop: `2px dotted rgba(${annotationDragColor},0.35)`,
    width,
    zIndex: '3',
    visibility: 'visible',
  }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name            GoogleMusicEnhancer (GME)
// @version         0.1.0
// @namespace       http://www.tobsch.org/
// @author          Tobias Schneider
// @homepage        http://www.tobsch.org
// @licence         http://www.gnu.org/licenses/gpl-2.0.html
// @description     Improvements and better usability for google music
//
// @include         http://music.google.com/music/listen*
// @include         https://music.google.com/music/listen*
// @include         http://play.google.com/music/listen*
// @include         https://play.google.com/music/listen*
//
// @require         http://code.jquery.com/jquery-2.1.0.min.js
// @require         https://jquery-json.googlecode.com/files/jquery.json-2.4.min.js
//
// grant            GM_addStyle
// grant            GM_xmlhttpRequest
// grant            GM_setValue
// grant            GM_getValue
// grant            GM_deleteValue
// grant            GM_listValues
// grant            GM_info
// ==/UserScript==

GM_addStyle("<!-- @import style.css -->");

$(function () {
    "use strict";

    Update.check(false);

    $('#main')
        .append(
            Build.div({attr:{class: 'lyrics-panel un-clicked', id: 'lyrics-panel', title: 'Hit to reload lyric'}})
                .append(
                    Build.div({attr: {class: 'lyrics-clip', id: 'lyrics-clip'}, text: 'Lyric'}).on('click', function () {
                        $(this).parent('div.lyrics-panel').toggleClass("clicked un-clicked");
                    })
                )
                .append(
                    Build.div({attr:{class: 'lyrics-header', id: 'lyrics-header'}, text: 'Lyrics Panel'})
                )
                .append(
                    Build.div({attr:{class: 'lyrics-body', id: 'lyrics-body'}, text: 'I can not hear a sound. Play something loud!' })
                )
        );

    // listeners
    $('.music-banner-icon').on('click', function () {
        Update.check(true);
    });

    $('#playerSongInfo').on('DOMSubtreeModified', function () {
        var title = $('#playerSongTitle').text();
        var artist = $('#player-artist').text();

        if (title && artist && parseInt($('#lyrics-header').attr('hash')) !== Util.hashCode(artist,title)) {
            try{
                lyric.search({artist: artist, title: title}, LyricsWiki);
            } catch(e){
                console.log('GME: ' + e.message);
            }
        }
    });

}); // Ready Function<commit_msg>fix typo<commit_after>// ==UserScript==
// @name            GoogleMusicEnhancer (GME)
// @version         0.1.0
// @namespace       http://www.tobsch.org/
// @author          Tobias Schneider
// @homepage        http://www.tobsch.org
// @licence         http://www.gnu.org/licenses/gpl-2.0.html
// @description     Improvements and better usability for google music
//
// @include         http://music.google.com/music/listen*
// @include         https://music.google.com/music/listen*
// @include         http://play.google.com/music/listen*
// @include         https://play.google.com/music/listen*
//
// @require         http://code.jquery.com/jquery-2.1.0.min.js
// @require         https://jquery-json.googlecode.com/files/jquery.json-2.4.min.js
//
// grant            GM_addStyle
// grant            GM_xmlhttpRequest
// grant            GM_setValue
// grant            GM_getValue
// grant            GM_deleteValue
// grant            GM_listValues
// grant            GM_info
// ==/UserScript==

GM_addStyle("<!-- @import style.css -->");

$(function () {
    "use strict";

    Update.check(false);

    $('#main')
        .append(
            Build.div({attr:{class: 'lyrics-panel un-clicked', id: 'lyrics-panel', title: 'Hit to reload lyric'}})
                .append(
                    Build.div({attr: {class: 'lyrics-clip', id: 'lyrics-clip'}, text: 'Lyric'}).on('click', function () {
                        $(this).parent('div.lyrics-panel').toggleClass("clicked un-clicked");
                    })
                )
                .append(
                    Build.div({attr:{class: 'lyrics-header', id: 'lyrics-header'}, text: 'Lyrics Panel'})
                )
                .append(
                    Build.div({attr:{class: 'lyrics-body', id: 'lyrics-body'}, text: 'I can not hear a sound. Play something loud!' })
                )
        );

    // listeners
    $('.music-banner-icon').on('click', function () {
        Update.check(true);
    });

    $('#playerSongInfo').on('DOMSubtreeModified', function () {
        var title = $('#playerSongTitle').text();
        var artist = $('#player-artist').text();

        if (title && artist && parseInt($('#lyrics-header').attr('hash')) !== Util.hashCode(artist,title)) {
            try{
                Lyric.search({artist: artist, title: title}, LyricsWiki);
            } catch(e){
                console.log('GME: ' + e.message);
            }
        }
    });

}); // Ready Function<|endoftext|>


<commit_before>var mediator = (function() {
  var subscribe = function(channel, fn) {
    if (!mediator.channels[channel]) mediator.channels[channel] = [];
    mediator.channels[channel].push({ context: this, callback: fn });
    return this;
  },

  publish = function(channel) {
    if (!mediator.channels[channel]) return false;
    var args = Array.prototype.slice.call(arguments, 1);
    for (var i = 0, l = mediator.channels[channel].length; i < l; i++) {
      var subscription = mediator.channels[channel][i];
      subscription.callback.apply(subscription.context, args);
    }
    return this;
  };

  return {
    channels: {},
    publish: publish,
    subscribe: subscribe,
    installTo: function(obj) {
      obj.subscribe = subscribe;
      obj.publish = publish;
    }
  };

}());
<commit_msg>Update mediator pattern<commit_after>var Mediator = (function(window, undefined) {

	function Mediator() {
		this._topics = {};
	}

	Mediator.prototype.subscribe = function mediatorSubscribe(topic, callback) {
		if (!this._topics.hasOwnProperty(topic)) {
			this._topics[topic] = [];
		}

		this._topics[topic].push(callback);
		return true;
	};

	Mediator.prototype.unsubscribe = function mediatorUnsubscrive(topic, callback) {
		if (!this._topics.hasOwnProperty(topic)) {
			return false;
		}

		for(var i = 0, len = this._topics[ topic ].length; i < len; i++) {
			if (this._topics[topic][i] === callback) {
				this._topics[topic].splice(i, 1);
				return true;
			}
		}

		return false;
	};

	Mediator.prototype.publish = function mediatorPublish() {
		var args = Array.prototype.slice.call(arguments);
		var topic = args.shift();

		if (!this._topics.hasOwnProperty(topic)) {
			return false;
		}

		for(var i = 0, len = this._topics[topic].length; i < len; i++) {
			this._topics[topic][i].apply(undefined, args);
		}
		return true;
	};

	return Mediator;

} )( window );

// example subscriber function
var Subscriber = function ExampleSubscriber(myVariable) {
  console.log(myVariable);
};

// example usages
var myMediator = new Mediator();
myMediator.subscribe('some event', Subscriber);
myMediator.publish('some event', 'foo bar'); // console logs "foo bar"
<|endoftext|>


<commit_before>import scrollbarWidth from 'element-ui/src/utils/scrollbar-width';

class TableLayout {
  constructor(options) {
    this.table = null;
    this.store = null;
    this.columns = null;
    this.fit = true;
    this.showHeader = true;

    this.height = null;
    this.scrollX = false;
    this.scrollY = false;
    this.bodyWidth = null;
    this.fixedWidth = null;
    this.rightFixedWidth = null;
    this.tableHeight = null;
    this.headerHeight = 44; // Table Header Height
    this.viewportHeight = null; // Table Height - Scroll Bar Height
    this.bodyHeight = null; // Table Height - Table Header Height
    this.fixedBodyHeight = null; // Table Height - Table Header Height - Scroll Bar Height
    this.gutterWidth = scrollbarWidth();

    for (let name in options) {
      if (options.hasOwnProperty(name)) {
        this[name] = options[name];
      }
    }

    if (!this.table) {
      throw new Error('table is required for Table Layout');
    }
    if (!this.store) {
      throw new Error('store is required for Table Layout');
    }
  }

  updateScrollY() {
    const height = this.height;
    if (typeof height !== 'string' && typeof height !== 'number') return;
    const bodyWrapper = this.table.bodyWrapper;
    if (this.table.$el && bodyWrapper) {
      const body = bodyWrapper.querySelector('.el-table__body');
      this.scrollY = body.offsetHeight > bodyWrapper.offsetHeight;
    }
  }

  setHeight(value, prop = 'height') {
    const el = this.table.$el;
    if (typeof value === 'string' && /^\d+$/.test(value)) {
      value = Number(value);
    }

    this.height = value;

    if (!el) return;
    if (typeof value === 'number') {
      el.style[prop] = value + 'px';

      this.updateHeight();
    } else if (typeof value === 'string') {
      this.updateHeight();
    }
  }

  setMaxHeight(value) {
    return this.setHeight(value, 'max-height');
  }

  updateHeight() {
    const height = this.tableHeight = this.table.$el.clientHeight;
    const { headerWrapper } = this.table.$refs;
    if (this.showHeader && !headerWrapper) return;
    if (!this.showHeader) {
      this.headerHeight = 0;
      if (this.height !== null && (!isNaN(this.height) || typeof this.height === 'string')) {
        this.bodyHeight = height;
      }
      this.fixedBodyHeight = this.scrollX ? height - this.gutterWidth : height;
    } else {
      const headerHeight = this.headerHeight = headerWrapper.offsetHeight;
      const bodyHeight = height - headerHeight;
      if (this.height !== null && (!isNaN(this.height) || typeof this.height === 'string')) {
        this.bodyHeight = bodyHeight;
      }
      this.fixedBodyHeight = this.scrollX ? bodyHeight - this.gutterWidth : bodyHeight;
    }
    this.viewportHeight = this.scrollX ? height - this.gutterWidth : height;
  }

  update() {
    const fit = this.fit;
    const columns = this.table.columns;
    const bodyWidth = this.table.$el.clientWidth;
    let bodyMinWidth = 0;

    const flattenColumns = [];
    columns.forEach((column) => {
      if (column.isColumnGroup) {
        flattenColumns.push.apply(flattenColumns, column.columns);
      } else {
        flattenColumns.push(column);
      }
    });

    let flexColumns = flattenColumns.filter((column) => typeof column.width !== 'number');

    if (flexColumns.length > 0 && fit) {
      flattenColumns.forEach((column) => {
        bodyMinWidth += column.width || column.minWidth || 80;
      });

      if (bodyMinWidth < bodyWidth - this.gutterWidth) { // DON'T HAVE SCROLL BAR
        this.scrollX = false;

        const totalFlexWidth = bodyWidth - this.gutterWidth - bodyMinWidth;

        if (flexColumns.length === 1) {
          flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth;
        } else {
          const allColumnsWidth = flexColumns.reduce((prev, column) => prev + (column.minWidth || 80), 0);
          const flexWidthPerPixel = totalFlexWidth / allColumnsWidth;
          let noneFirstWidth = 0;

          flexColumns.forEach((column, index) => {
            if (index === 0) return;
            const flexWidth = Math.floor((column.minWidth || 80) * flexWidthPerPixel);
            noneFirstWidth += flexWidth;
            column.realWidth = (column.minWidth || 80) + flexWidth;
          });

          flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth - noneFirstWidth;
        }
      } else { // HAVE HORIZONTAL SCROLL BAR
        this.scrollX = true;
        flexColumns.forEach(function(column) {
          column.realWidth = column.minWidth;
        });
      }

      this.bodyWidth = Math.max(bodyMinWidth, bodyWidth);
    } else {
      flattenColumns.forEach((column) => {
        if (!column.width && !column.minWidth) {
          column.realWidth = 80;
        } else {
          column.realWidth = column.width || column.minWidth;
        }

        bodyMinWidth += column.realWidth;
      });
      this.scrollX = bodyMinWidth > bodyWidth;

      this.bodyWidth = bodyMinWidth;
    }

    const fixedColumns = this.store.states.fixedColumns;

    if (fixedColumns.length > 0) {
      let fixedWidth = 0;
      fixedColumns.forEach(function(column) {
        fixedWidth += column.realWidth;
      });

      this.fixedWidth = fixedWidth;
    }

    const rightFixedColumns = this.store.states.rightFixedColumns;
    if (rightFixedColumns.length > 0) {
      let rightFixedWidth = 0;
      rightFixedColumns.forEach(function(column) {
        rightFixedWidth += column.realWidth;
      });

      this.rightFixedWidth = rightFixedWidth;
    }
  }
}

export default TableLayout;
<commit_msg>Table: fix fixed column height when empty data, fixed #2300<commit_after>import scrollbarWidth from 'element-ui/src/utils/scrollbar-width';

class TableLayout {
  constructor(options) {
    this.table = null;
    this.store = null;
    this.columns = null;
    this.fit = true;
    this.showHeader = true;

    this.height = null;
    this.scrollX = false;
    this.scrollY = false;
    this.bodyWidth = null;
    this.fixedWidth = null;
    this.rightFixedWidth = null;
    this.tableHeight = null;
    this.headerHeight = 44; // Table Header Height
    this.viewportHeight = null; // Table Height - Scroll Bar Height
    this.bodyHeight = null; // Table Height - Table Header Height
    this.fixedBodyHeight = null; // Table Height - Table Header Height - Scroll Bar Height
    this.gutterWidth = scrollbarWidth();

    for (let name in options) {
      if (options.hasOwnProperty(name)) {
        this[name] = options[name];
      }
    }

    if (!this.table) {
      throw new Error('table is required for Table Layout');
    }
    if (!this.store) {
      throw new Error('store is required for Table Layout');
    }
  }

  updateScrollY() {
    const height = this.height;
    if (typeof height !== 'string' && typeof height !== 'number') return;
    const bodyWrapper = this.table.bodyWrapper;
    if (this.table.$el && bodyWrapper) {
      const body = bodyWrapper.querySelector('.el-table__body');
      this.scrollY = body.offsetHeight > bodyWrapper.offsetHeight;
    }
  }

  setHeight(value, prop = 'height') {
    const el = this.table.$el;
    if (typeof value === 'string' && /^\d+$/.test(value)) {
      value = Number(value);
    }

    this.height = value;

    if (!el) return;
    if (typeof value === 'number') {
      el.style[prop] = value + 'px';

      this.updateHeight();
    } else if (typeof value === 'string') {
      this.updateHeight();
    }
  }

  setMaxHeight(value) {
    return this.setHeight(value, 'max-height');
  }

  updateHeight() {
    const height = this.tableHeight = this.table.$el.clientHeight;
    const noData = !this.table.data || this.table.data.length === 0;
    const { headerWrapper } = this.table.$refs;
    if (this.showHeader && !headerWrapper) return;
    if (!this.showHeader) {
      this.headerHeight = 0;
      if (this.height !== null && (!isNaN(this.height) || typeof this.height === 'string')) {
        this.bodyHeight = height;
      }
      this.fixedBodyHeight = this.scrollX ? height - this.gutterWidth : height;
    } else {
      const headerHeight = this.headerHeight = headerWrapper.offsetHeight;
      const bodyHeight = height - headerHeight;
      if (this.height !== null && (!isNaN(this.height) || typeof this.height === 'string')) {
        this.bodyHeight = bodyHeight;
      }
      this.fixedBodyHeight = this.scrollX ? bodyHeight - this.gutterWidth : bodyHeight;
    }
    this.viewportHeight = this.scrollX ? height - (noData ? 0 : this.gutterWidth) : height;
  }

  update() {
    const fit = this.fit;
    const columns = this.table.columns;
    const bodyWidth = this.table.$el.clientWidth;
    let bodyMinWidth = 0;

    const flattenColumns = [];
    columns.forEach((column) => {
      if (column.isColumnGroup) {
        flattenColumns.push.apply(flattenColumns, column.columns);
      } else {
        flattenColumns.push(column);
      }
    });

    let flexColumns = flattenColumns.filter((column) => typeof column.width !== 'number');

    if (flexColumns.length > 0 && fit) {
      flattenColumns.forEach((column) => {
        bodyMinWidth += column.width || column.minWidth || 80;
      });

      if (bodyMinWidth < bodyWidth - this.gutterWidth) { // DON'T HAVE SCROLL BAR
        this.scrollX = false;

        const totalFlexWidth = bodyWidth - this.gutterWidth - bodyMinWidth;

        if (flexColumns.length === 1) {
          flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth;
        } else {
          const allColumnsWidth = flexColumns.reduce((prev, column) => prev + (column.minWidth || 80), 0);
          const flexWidthPerPixel = totalFlexWidth / allColumnsWidth;
          let noneFirstWidth = 0;

          flexColumns.forEach((column, index) => {
            if (index === 0) return;
            const flexWidth = Math.floor((column.minWidth || 80) * flexWidthPerPixel);
            noneFirstWidth += flexWidth;
            column.realWidth = (column.minWidth || 80) + flexWidth;
          });

          flexColumns[0].realWidth = (flexColumns[0].minWidth || 80) + totalFlexWidth - noneFirstWidth;
        }
      } else { // HAVE HORIZONTAL SCROLL BAR
        this.scrollX = true;
        flexColumns.forEach(function(column) {
          column.realWidth = column.minWidth;
        });
      }

      this.bodyWidth = Math.max(bodyMinWidth, bodyWidth);
    } else {
      flattenColumns.forEach((column) => {
        if (!column.width && !column.minWidth) {
          column.realWidth = 80;
        } else {
          column.realWidth = column.width || column.minWidth;
        }

        bodyMinWidth += column.realWidth;
      });
      this.scrollX = bodyMinWidth > bodyWidth;

      this.bodyWidth = bodyMinWidth;
    }

    const fixedColumns = this.store.states.fixedColumns;

    if (fixedColumns.length > 0) {
      let fixedWidth = 0;
      fixedColumns.forEach(function(column) {
        fixedWidth += column.realWidth;
      });

      this.fixedWidth = fixedWidth;
    }

    const rightFixedColumns = this.store.states.rightFixedColumns;
    if (rightFixedColumns.length > 0) {
      let rightFixedWidth = 0;
      rightFixedColumns.forEach(function(column) {
        rightFixedWidth += column.realWidth;
      });

      this.rightFixedWidth = rightFixedWidth;
    }
  }
}

export default TableLayout;
<|endoftext|>