<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(paths.nodePaths),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    extensions: ['.js', '.json', '.jsx'],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
  },
  // @remove-on-eject-begin
  // Resolve loaders (webpack plugins for CSS, images, transpilation) from the
  // directory of `react-scripts` itself rather than the project directory.
  resolveLoader: {
    modules: [
      paths.ownNodeModules,
      // Lerna hoists everything, so we need to look in our app directory
      paths.appNodeModules,
    ],
  },
  // @remove-on-eject-end
  module: {
    rules: [
      // Disable require.ensure as it's not a standard language feature.
      { parser: { requireEnsure: false } },
      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            // @remove-on-eject-begin
            // Point ESLint to our predefined config.
            options: {
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: ['react-app'],
              },
              useEslintrc: false,
            },
            // @remove-on-eject-end
            loader: 'eslint-loader',
          },
        ],
        include: paths.appSrc,
      },
      // ** ADDING/UPDATING LOADERS **
      // The "url" loader handles all assets unless explicitly excluded.
      // The `exclude` list *must* be updated with every change to loader extensions.
      // When adding a new loader, you must add its `test`
      // as a new entry in the `exclude` list in the "url" loader.

      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.bmp$/,
          /\.gif$/,
          /\.jpe?g$/,
          /\.png$/,
        ],
        loader: 'file-loader',
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel-loader',
        // @remove-on-eject-begin
        options: {
          babelrc: false,
          presets: [require.resolve('babel-preset-react-app')],
        },
        // @remove-on-eject-end
      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          Object.assign(
            {
              fallback: 'style-loader',
              use: [
                {
                  loader: 'css-loader',
                  options: {
                    importLoaders: 1,
                  },
                },
                {
                  loader: 'postcss-loader',
                  options: {
                    ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
                    plugins: () => [
                      autoprefixer({
                        browsers: [
                          '>1%',
                          'last 4 versions',
                          'Firefox ESR',
                          'not ie < 9', // React doesn't support IE8 anyway
                        ],
                      }),
                    ],
                  },
                },
              ],
            },
            extractTextPluginOptions
          )
        ),
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // ** STOP ** Are you adding a new loader?
      // Remember to add the new extension(s) to the "url" loader exclusion list.
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      output: {
        comments: false,
      },
      sourceMap: true,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<commit_msg>Minify and map css (#2013)<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: 'source-map',
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We read `NODE_PATH` environment variable in `paths.js` and pass paths here.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(paths.nodePaths),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    extensions: ['.js', '.json', '.jsx'],
    alias: {
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
  },
  // @remove-on-eject-begin
  // Resolve loaders (webpack plugins for CSS, images, transpilation) from the
  // directory of `react-scripts` itself rather than the project directory.
  resolveLoader: {
    modules: [
      paths.ownNodeModules,
      // Lerna hoists everything, so we need to look in our app directory
      paths.appNodeModules,
    ],
  },
  // @remove-on-eject-end
  module: {
    rules: [
      // Disable require.ensure as it's not a standard language feature.
      { parser: { requireEnsure: false } },
      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            // @remove-on-eject-begin
            // Point ESLint to our predefined config.
            options: {
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: ['react-app'],
              },
              useEslintrc: false,
            },
            // @remove-on-eject-end
            loader: 'eslint-loader',
          },
        ],
        include: paths.appSrc,
      },
      // ** ADDING/UPDATING LOADERS **
      // The "url" loader handles all assets unless explicitly excluded.
      // The `exclude` list *must* be updated with every change to loader extensions.
      // When adding a new loader, you must add its `test`
      // as a new entry in the `exclude` list in the "url" loader.

      // "file" loader makes sure those assets end up in the `build` folder.
      // When you `import` an asset, you get its filename.
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.bmp$/,
          /\.gif$/,
          /\.jpe?g$/,
          /\.png$/,
        ],
        loader: 'file-loader',
        options: {
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // "url" loader works just like "file" loader but it also embeds
      // assets smaller than specified size as data URLs to avoid requests.
      {
        test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]',
        },
      },
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel-loader',
        // @remove-on-eject-begin
        options: {
          babelrc: false,
          presets: [require.resolve('babel-preset-react-app')],
        },
        // @remove-on-eject-end
      },
      // The notation here is somewhat confusing.
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader normally turns CSS into JS modules injecting <style>,
      // but unlike in development configuration, we do something different.
      // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
      // (second argument), then grabs the result CSS and puts it into a
      // separate file in our build process. This way we actually ship
      // a single CSS file in production instead of JS code injecting <style>
      // tags. If you use code splitting, however, any async bundles will still
      // use the "style" loader inside the async code so CSS from them won't be
      // in the main CSS file.
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          Object.assign(
            {
              fallback: 'style-loader',
              use: [
                {
                  loader: 'css-loader',
                  options: {
                    importLoaders: 1,
                    minimize: true,
                    sourceMap: true,
                  },
                },
                {
                  loader: 'postcss-loader',
                  options: {
                    ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
                    plugins: () => [
                      autoprefixer({
                        browsers: [
                          '>1%',
                          'last 4 versions',
                          'Firefox ESR',
                          'not ie < 9', // React doesn't support IE8 anyway
                        ],
                      }),
                    ],
                  },
                },
              ],
            },
            extractTextPluginOptions
          )
        ),
        // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
      },
      // ** STOP ** Are you adding a new loader?
      // Remember to add the new extension(s) to the "url" loader exclusion list.
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
      },
      output: {
        comments: false,
      },
      sourceMap: true,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};
<|endoftext|>


<commit_before>import _ from 'underscore';
import { timeAgo } from './helpers';

function directorySearch(config, cb) {
	return Meteor.call('browseChannels', config, (err, result) => {
		cb(result && result.results && result.results.length && result.results.map((result) => {
			if (config.type === 'channels') {
				return {
					name: result.name,
					users: result.usersCount || 0,
					createdAt: timeAgo(result.ts),
					lastMessage: result.lastMessage && timeAgo(result.lastMessage.ts),
					description: result.description,
					archived: result.archived,
					topic: result.topic,
				};
			}

			if (config.type === 'users') {
				return {
					name: result.name,
					username: result.username,
					createdAt: timeAgo(result.createdAt),
				};
			}
			return null;
		}));
	});
}

Template.directory.helpers({
	searchText() {
		return Template.instance().searchText.get();
	},
	showLastMessage() {
		return RocketChat.settings.get('Store_Last_Message');
	},
	searchResults() {
		return Template.instance().results.get();
	},
	searchType() {
		return Template.instance().searchType.get();
	},
	sortIcon(key) {
		const { sortDirection, searchSortBy } = Template.instance();

		return key === searchSortBy.get() && sortDirection.get() === 'asc'
			? 'sort-up'
			: 'sort-down';
	},
	searchSortBy(key) {
		return Template.instance().searchSortBy.get() === key;
	},
	createChannelOrGroup() {
		return RocketChat.authz.hasAtLeastOnePermission(['create-c', 'create-p']);
	},
	tabsData() {
		const {
			sortDirection,
			searchType,
			searchSortBy,
			results,
			end,
			page,
		} = Template.instance();
		return {
			tabs: [
				{
					label: t('Channels'),
					value: 'channels',
					condition() {
						return true;
					},
					active: true,
				},
				{
					label: t('Users'),
					value: 'users',
					condition() {
						return true;
					},
				},
			],
			onChange(value) {
				results.set([]);
				end.set(false);
				searchSortBy.set('name');
				sortDirection.set('asc');
				page.set(0);
				searchType.set(value);
			},
		};
	},
	onTableItemClick() {
		const { searchType } = Template.instance();
		let type;
		let routeConfig;
		return function(item) {
			if (searchType.get() === 'channels') {
				type = 'c';
				routeConfig = { name: item.name };
			} else {
				type = 'd';
				routeConfig = { name: item.username };
			}
			FlowRouter.go(RocketChat.roomTypes.getRouteLink(type, routeConfig));
		};
	},
	isLoading() {
		return Template.instance().isLoading.get();
	},
	onTableScroll() {
		const instance = Template.instance();
		if (instance.isLoading.get() || instance.end.get()) {
			return;
		}
		return function(currentTarget) {
			if (
				currentTarget.offsetHeight + currentTarget.scrollTop >=
				currentTarget.scrollHeight - 100
			) {
				return instance.page.set(instance.page.get() + 1);
			}
		};
	},
	onTableResize() {
		const { limit } = Template.instance();

		return function() {
			limit.set(Math.ceil(this.$('.table-scroll').height() / 40 + 5));
		};
	},
	onTableSort() {
		const { end, page, sortDirection, searchSortBy } = Template.instance();

		return function(type) {
			end.set(false);
			page.set(0);

			if (searchSortBy.get() === type) {
				sortDirection.set(sortDirection.get() === 'asc' ? 'desc' : 'asc');
				return;
			}

			searchSortBy.set(type);
			sortDirection.set('asc');
		};
	},
});

Template.directory.events({
	'input .js-search': _.debounce((e, t) => {
		t.end.set(false);
		t.sortDirection.set('asc');
		t.page.set(0);
		t.searchText.set(e.currentTarget.value);
	}, 300),
});

Template.directory.onRendered(function() {
	Tracker.autorun(() => {
		const searchConfig = {
			text: this.searchText.get(),
			type: this.searchType.get(),
			sortBy: this.searchSortBy.get(),
			sortDirection: this.sortDirection.get(),
			limit: this.limit.get(),
			page: this.page.get(),
		};
		if (this.end.get() || this.loading) {
			return;
		}
		this.loading = true;
		this.isLoading.set(true);
		directorySearch(searchConfig, (result) => {
			this.loading = false;
			this.isLoading.set(false);
			this.end.set(!result);

			if (!Array.isArray(result)) {
				result = [];
			}

			if (this.page.get() > 0) {
				return this.results.set([...this.results.get(), ...result]);
			}
			return this.results.set(result);
		});
	});
});

Template.directory.onCreated(function() {
	this.searchText = new ReactiveVar('');
	this.searchType = new ReactiveVar('channels');
	this.searchSortBy = new ReactiveVar('usersCount');
	this.sortDirection = new ReactiveVar('desc');
	this.limit = new ReactiveVar(0);
	this.page = new ReactiveVar(0);
	this.end = new ReactiveVar(false);

	this.results = new ReactiveVar([]);

	this.isLoading = new ReactiveVar(false);
});

Template.directory.onRendered(function() {
	$('.main-content').removeClass('rc-old');
	$('.rc-table-content').css('height', `calc(100vh - ${ document.querySelector('.rc-directory .rc-header').offsetHeight }px)`);
});
<commit_msg>[FIX] Fix links in `onTableItemClick` of the directroy page (#11543)<commit_after>import _ from 'underscore';
import { timeAgo } from './helpers';

function directorySearch(config, cb) {
	return Meteor.call('browseChannels', config, (err, result) => {
		cb(result && result.results && result.results.length && result.results.map((result) => {
			if (config.type === 'channels') {
				return {
					name: result.name,
					users: result.usersCount || 0,
					createdAt: timeAgo(result.ts),
					lastMessage: result.lastMessage && timeAgo(result.lastMessage.ts),
					description: result.description,
					archived: result.archived,
					topic: result.topic,
				};
			}

			if (config.type === 'users') {
				return {
					name: result.name,
					username: result.username,
					createdAt: timeAgo(result.createdAt),
				};
			}
			return null;
		}));
	});
}

Template.directory.helpers({
	searchText() {
		return Template.instance().searchText.get();
	},
	showLastMessage() {
		return RocketChat.settings.get('Store_Last_Message');
	},
	searchResults() {
		return Template.instance().results.get();
	},
	searchType() {
		return Template.instance().searchType.get();
	},
	sortIcon(key) {
		const { sortDirection, searchSortBy } = Template.instance();

		return key === searchSortBy.get() && sortDirection.get() === 'asc'
			? 'sort-up'
			: 'sort-down';
	},
	searchSortBy(key) {
		return Template.instance().searchSortBy.get() === key;
	},
	createChannelOrGroup() {
		return RocketChat.authz.hasAtLeastOnePermission(['create-c', 'create-p']);
	},
	tabsData() {
		const {
			sortDirection,
			searchType,
			searchSortBy,
			results,
			end,
			page,
		} = Template.instance();
		return {
			tabs: [
				{
					label: t('Channels'),
					value: 'channels',
					condition() {
						return true;
					},
					active: true,
				},
				{
					label: t('Users'),
					value: 'users',
					condition() {
						return true;
					},
				},
			],
			onChange(value) {
				results.set([]);
				end.set(false);
				searchSortBy.set('name');
				sortDirection.set('asc');
				page.set(0);
				searchType.set(value);
			},
		};
	},
	onTableItemClick() {
		const { searchType } = Template.instance();
		let type;
		let routeConfig;
		return function(item) {
			if (searchType.get() === 'channels') {
				type = 'c';
				routeConfig = { name: item.name };
			} else {
				type = 'd';
				routeConfig = { name: item.username };
			}
			RocketChat.roomTypes.openRouteLink(type, routeConfig);
		};
	},
	isLoading() {
		return Template.instance().isLoading.get();
	},
	onTableScroll() {
		const instance = Template.instance();
		if (instance.isLoading.get() || instance.end.get()) {
			return;
		}
		return function(currentTarget) {
			if (
				currentTarget.offsetHeight + currentTarget.scrollTop >=
				currentTarget.scrollHeight - 100
			) {
				return instance.page.set(instance.page.get() + 1);
			}
		};
	},
	onTableResize() {
		const { limit } = Template.instance();

		return function() {
			limit.set(Math.ceil(this.$('.table-scroll').height() / 40 + 5));
		};
	},
	onTableSort() {
		const { end, page, sortDirection, searchSortBy } = Template.instance();

		return function(type) {
			end.set(false);
			page.set(0);

			if (searchSortBy.get() === type) {
				sortDirection.set(sortDirection.get() === 'asc' ? 'desc' : 'asc');
				return;
			}

			searchSortBy.set(type);
			sortDirection.set('asc');
		};
	},
});

Template.directory.events({
	'input .js-search': _.debounce((e, t) => {
		t.end.set(false);
		t.sortDirection.set('asc');
		t.page.set(0);
		t.searchText.set(e.currentTarget.value);
	}, 300),
});

Template.directory.onRendered(function() {
	Tracker.autorun(() => {
		const searchConfig = {
			text: this.searchText.get(),
			type: this.searchType.get(),
			sortBy: this.searchSortBy.get(),
			sortDirection: this.sortDirection.get(),
			limit: this.limit.get(),
			page: this.page.get(),
		};
		if (this.end.get() || this.loading) {
			return;
		}
		this.loading = true;
		this.isLoading.set(true);
		directorySearch(searchConfig, (result) => {
			this.loading = false;
			this.isLoading.set(false);
			this.end.set(!result);

			if (!Array.isArray(result)) {
				result = [];
			}

			if (this.page.get() > 0) {
				return this.results.set([...this.results.get(), ...result]);
			}
			return this.results.set(result);
		});
	});
});

Template.directory.onCreated(function() {
	this.searchText = new ReactiveVar('');
	this.searchType = new ReactiveVar('channels');
	this.searchSortBy = new ReactiveVar('usersCount');
	this.sortDirection = new ReactiveVar('desc');
	this.limit = new ReactiveVar(0);
	this.page = new ReactiveVar(0);
	this.end = new ReactiveVar(false);

	this.results = new ReactiveVar([]);

	this.isLoading = new ReactiveVar(false);
});

Template.directory.onRendered(function() {
	$('.main-content').removeClass('rc-old');
	$('.rc-table-content').css('height', `calc(100vh - ${ document.querySelector('.rc-directory .rc-header').offsetHeight }px)`);
});
<|endoftext|>


<commit_before>import { setupDevtoolsPlugin } from '@vue/devtools-api'

/** @type {import('@vue/devtools-api').DevtoolsPluginApi} */
let devtoolsApi

export default {
  install: (app) => {
    setupDevtoolsPlugin({
      id: 'test-plugin',
      label: 'Test devtools plugin',
      app
    }, (api) => {
      devtoolsApi = api

      let time = 0

      api.on.inspectComponent((payload, ctx) => {
        if (payload.instanceData) {
          const stateType = 'extra properties (test)'
          payload.instanceData.state.push({
            type: stateType,
            key: 'foo',
            value: 'bar'
          })
          payload.instanceData.state.push({
            type: stateType,
            key: 'time',
            value: {
              _custom: {
                type: null,
                readOnly: true,
                display: `${time}s`,
                tooltip: 'Elapsed time',
                value: time
              }
            }
          })
        }
      })

      setInterval(() => {
        time += 5
        // Update component
        api.notifyComponentUpdate()
        // Update custom inspector
        api.sendInspectorTree('test-inspector')
        api.sendInspectorState('test-inspector')
      }, 5000)

      api.addTimelineLayer({
        id: 'test-layer',
        label: 'Test layer',
        color: 0x92A2BF
      })

      api.addInspector({
        id: 'test-inspector',
        label: 'Test inspector',
        icon: 'tab_unselected',
        treeFilterPlaceholder: 'Search for test...'
      })

      api.on.getInspectorTree(payload => {
        if (payload.app === app && payload.inspectorId === 'test-inspector') {
          payload.rootNodes = [
            {
              id: 'root',
              label: `Root (${time})`,
              children: [
                {
                  id: 'child',
                  label: `Child ${payload.filter}`,
                  tags: [
                    {
                      label: 'active',
                      textColor: 0x000000,
                      backgroundColor: 0xFF984F
                    },
                    {
                      label: 'test',
                      textColor: 0xffffff,
                      backgroundColor: 0x000000
                    }
                  ]
                }
              ]
            }
          ]
        }
      })

      api.on.getInspectorState(payload => {
        if (payload.app === app && payload.inspectorId === 'test-inspector') {
          if (payload.nodeId === 'root') {
            payload.state = {
              'root info': [
                {
                  key: 'foo',
                  value: 'bar'
                },
                {
                  key: 'time',
                  value: time
                }
              ]
            }
          } else {
            payload.state = {
              'child info': [
                {
                  key: 'answer',
                  value: {
                    _custom: {
                      display: '42!!!',
                      value: 42,
                      tooltip: 'The answer'
                    }
                  }
                }
              ]
            }
          }
        }
      })
    })

    // Outside of setupDevtoolsPlugin

    window.addEventListener('mouseup', event => {
      devtoolsApi.addTimelineEvent({
        layerId: 'test-layer',
        event: {
          time: Date.now(),
          data: {
            info: 'window.mouseup',
            x: event.clientX,
            y: event.clientY
          }
        }
      })
    })
  }
}
<commit_msg>chore: fix demo error<commit_after>import { setupDevtoolsPlugin } from '@vue/devtools-api'

/** @type {import('@vue/devtools-api').DevtoolsPluginApi} */
let devtoolsApi

export default {
  install: (app) => {
    setupDevtoolsPlugin({
      id: 'test-plugin',
      label: 'Test devtools plugin',
      app
    }, (api) => {
      devtoolsApi = api

      let time = 0

      api.on.inspectComponent((payload, ctx) => {
        if (payload.instanceData) {
          const stateType = 'extra properties (test)'
          payload.instanceData.state.push({
            type: stateType,
            key: 'foo',
            value: 'bar'
          })
          payload.instanceData.state.push({
            type: stateType,
            key: 'time',
            value: {
              _custom: {
                type: null,
                readOnly: true,
                display: `${time}s`,
                tooltip: 'Elapsed time',
                value: time
              }
            }
          })
        }
      })

      setInterval(() => {
        time += 5
        // Update component
        api.notifyComponentUpdate()
        // Update custom inspector
        api.sendInspectorTree('test-inspector')
        api.sendInspectorState('test-inspector')
      }, 5000)

      api.addTimelineLayer({
        id: 'test-layer',
        label: 'Test layer',
        color: 0x92A2BF
      })

      api.addInspector({
        id: 'test-inspector',
        label: 'Test inspector',
        icon: 'tab_unselected',
        treeFilterPlaceholder: 'Search for test...'
      })

      api.on.getInspectorTree(payload => {
        if (payload.app === app && payload.inspectorId === 'test-inspector') {
          payload.rootNodes = [
            {
              id: 'root',
              label: `Root (${time})`,
              children: [
                {
                  id: 'child',
                  label: `Child ${payload.filter}`,
                  tags: [
                    {
                      label: 'active',
                      textColor: 0x000000,
                      backgroundColor: 0xFF984F
                    },
                    {
                      label: 'test',
                      textColor: 0xffffff,
                      backgroundColor: 0x000000
                    }
                  ]
                }
              ]
            }
          ]
        }
      })

      api.on.getInspectorState(payload => {
        if (payload.app === app && payload.inspectorId === 'test-inspector') {
          if (payload.nodeId === 'root') {
            payload.state = {
              'root info': [
                {
                  key: 'foo',
                  value: 'bar'
                },
                {
                  key: 'time',
                  value: time
                }
              ]
            }
          } else {
            payload.state = {
              'child info': [
                {
                  key: 'answer',
                  value: {
                    _custom: {
                      display: '42!!!',
                      value: 42,
                      tooltip: 'The answer'
                    }
                  }
                }
              ]
            }
          }
        }
      })
    })

    // Outside of setupDevtoolsPlugin

    window.addEventListener('mouseup', event => {
      devtoolsApi && devtoolsApi.addTimelineEvent({
        layerId: 'test-layer',
        event: {
          time: Date.now(),
          data: {
            info: 'window.mouseup',
            x: event.clientX,
            y: event.clientY
          }
        }
      })
    })
  }
}
<|endoftext|>


<commit_before>/* eslint-env mocha */
import React from 'react'
import chai, {expect} from 'chai'
import sinon from 'sinon'
import proxyquire from 'proxyquire'
import reactAssertions, {shallowRender} from 'chai-react-assertions'

chai.use(reactAssertions)
chai.use(require('sinon-chai'))

const loopMock = {
  registerComponent: null,
  unregisterComponent: null,
}

const beatEngineMock = {
  beatBasedTweens: [],
}

let Animate

describe.only('<Animate /> component', function () {

  describe('initial state', function () {

    beforeEach(function () {
      loopMock.registerComponent = sinon.spy()
      loopMock.unregisterComponentSpy = sinon.spy()

      beatEngineMock.beatBasedTweens = []

      Animate = proxyquire('../animate', {
        './loop': loopMock,
        './beat-engine': { BeatEngine: beatEngineMock },
      }).Animate
    })

    describe('animation with duration', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{val: 50}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the component with the loop', function () {
        expect(loopMock.registerComponent).to.have.been.calledOnce
      })

      it('shouldn\'t register with the beat engine', function () {
        expect(beatEngineMock.beatBasedTweens.length).to.equal(0)
      })

      it('should create the tween filling in default props', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.val).to.contain({
          yoyo: true,
          easing: 'linear',
          duration: 500,
          to: 50,
          from: 0,
        })
      })
    })

    describe('animation with beat', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{val: { to: 50, beat: 4 }}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the component with the loop', function () {
        expect(loopMock.registerComponent).to.have.been.calledOnce
      })

      it('should register the tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.val])
      })

      it('should create the tween filling in default props', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.val).to.contain({
          yoyo: true,
          easing: 'linear',
          beat: 4,
          to: 50,
          from: 0,
        })
      })
    })

    describe('animation with multiple tweens', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{x: { to: 50, duration: 300 }, y: { to: 255, beat: 4, yoyo: false }}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the beat tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.y])
      })

      it('should create the tweens', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.x).to.contain({
          yoyo: true,
          easing: 'linear',
          to: 50,
          from: 0,
          duration: 300,
        })

        expect(instance.tweens.y).to.contain({
          yoyo: false,
          easing: 'linear',
          beat: 4,
          to: 255,
          from: 0,
        })
      })
    })

    describe('animation with multiple tweens with inheriting props', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{x: 50, y: { to: 255, beat: 4, yoyo: true }}} yoyo={false} duration={420} easing="easeInOut">
            {() => {}}
          </Animate>
        )
      })

      it('should register the beat tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.y])
      })

      it('should create the tweens', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.x).to.contain({
          yoyo: false,
          easing: 'easeInOut',
          to: 50,
          from: 0,
          duration: 420,
        })

        expect(instance.tweens.y).to.contain({
          yoyo: true,
          easing: 'easeInOut',
          beat: 4,
          to: 255,
          from: 0,
        })
      })
    })

  })

})
<commit_msg>Add tests for <Animate /> receiving new tweens via props<commit_after>/* eslint-env mocha */
import React from 'react'
import chai, {expect} from 'chai'
import sinon from 'sinon'
import proxyquire from 'proxyquire'
import reactAssertions, {shallowRender} from 'chai-react-assertions'

chai.use(reactAssertions)
chai.use(require('sinon-chai'))

const loopMock = {
  registerComponent: null,
  unregisterComponent: null,
}

const beatEngineMock = {
  beatBasedTweens: [],
}

let Animate

describe.only('<Animate /> component', function () {

  beforeEach(function () {
    loopMock.registerComponent = sinon.spy()
    loopMock.unregisterComponentSpy = sinon.spy()

    beatEngineMock.beatBasedTweens = []

    Animate = proxyquire('../animate', {
      './loop': loopMock,
      './beat-engine': { BeatEngine: beatEngineMock },
    }).Animate
  })

  describe('initial state', function () {

    describe('animation with duration', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{val: 50}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the component with the loop', function () {
        expect(loopMock.registerComponent).to.have.been.calledOnce
      })

      it('shouldn\'t register with the beat engine', function () {
        expect(beatEngineMock.beatBasedTweens.length).to.equal(0)
      })

      it('should create the tween filling in default props', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.val).to.contain({
          yoyo: true,
          easing: 'linear',
          duration: 500,
          to: 50,
          from: 0,
        })
      })
    })

    describe('animation with beat', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{val: { to: 50, beat: 4 }}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the component with the loop', function () {
        expect(loopMock.registerComponent).to.have.been.calledOnce
      })

      it('should register the tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.val])
      })

      it('should create the tween filling in default props', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.val).to.contain({
          yoyo: true,
          easing: 'linear',
          beat: 4,
          to: 50,
          from: 0,
        })
      })
    })

    describe('animation with multiple tweens', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{x: { to: 50, duration: 300 }, y: { to: 255, beat: 4, yoyo: false }}}>
            {() => {}}
          </Animate>
        )
      })

      it('should register the beat tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.y])
      })

      it('should create the tweens', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.x).to.contain({
          yoyo: true,
          easing: 'linear',
          to: 50,
          from: 0,
          duration: 300,
        })

        expect(instance.tweens.y).to.contain({
          yoyo: false,
          easing: 'linear',
          beat: 4,
          to: 255,
          from: 0,
        })
      })
    })

    describe('animation with multiple tweens with inheriting props', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate values={{x: 50, y: { to: 255, beat: 4, yoyo: true }}} yoyo={false} duration={420} easing="easeInOut">
            {() => {}}
          </Animate>
        )
      })

      it('should register the beat tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.y])
      })

      it('should create the tweens', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.x).to.contain({
          yoyo: false,
          easing: 'easeInOut',
          to: 50,
          from: 0,
          duration: 420,
        })

        expect(instance.tweens.y).to.contain({
          yoyo: true,
          easing: 'easeInOut',
          beat: 4,
          to: 255,
          from: 0,
        })
      })
    })

    describe('animation with multiple tweens with inheriting props and from values', function () {
      beforeEach(function () {
        this.tree = shallowRender(
          <Animate from={{x: 12}} values={{x: 50, y: { to: 255, beat: 4, yoyo: true }}} yoyo={false} duration={420} easing="easeInOut">
            {() => {}}
          </Animate>
        )
      })

      it('should create the tweens', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.x).to.contain({
          yoyo: false,
          easing: 'easeInOut',
          to: 50,
          from: 12,
          duration: 420,
        })

        expect(instance.tweens.y).to.contain({
          yoyo: true,
          easing: 'easeInOut',
          beat: 4,
          to: 255,
          from: 0,
        })
      })
    })

  })

  describe('receive props', function () {

    describe('adding beat animation', function () {
      beforeEach(function () {
        let values = {val: { to: 50 }}

        this.tree = shallowRender(
          <Animate values={values}>
            {() => {}}
          </Animate>
        )

        values = {
          ...values,
          newBeat: { to: 255, beat: 2 },
        }

        this.tree.getMountedInstance().componentWillReceiveProps({ values })
      })

      it('should register the component with the loop', function () {
        expect(loopMock.registerComponent).to.have.been.calledOnce
      })

      it('should register the new tween with the beat engine', function () {
        const instance = this.tree.getMountedInstance()

        expect(beatEngineMock.beatBasedTweens).to.eql([instance.tweens.newBeat])
      })

      it('should create the new tween filling in default props', function () {
        const instance = this.tree.getMountedInstance()

        expect(instance.tweens.newBeat).to.contain({
          yoyo: true,
          easing: 'linear',
          beat: 2,
          to: 255,
          from: 0,
        })
      })
    })

  })

})
<|endoftext|>


<commit_before>import debugModule from "debug";
const debug = debugModule("debugger:evm:selectors");

import { createSelectorTree, createLeaf } from "reselect-tree";

import trace from "lib/trace/selectors";

const WORD_SIZE = 0x20;

/**
 * create EVM-level selectors for a given trace step selector
 * may specify additional selectors to include
 */
function createStepSelectors(step, state = null) {
  let base = {
    /**
     * .trace
     *
     * trace step info related to next evm operation
     */
    trace: createLeaf(
      [step], ({gasCost, op, pc}) => ({gasCost, op, pc})
    ),

    /**
     * .programCounter
     */
    programCounter: createLeaf(
      ["./trace"], (step) => step.pc
    ),

    /**
     * .isJump
     */
    isJump: createLeaf(
      ["./trace"], (step) => (
        step.op != "JUMPDEST" && step.op.indexOf("JUMP") == 0
      )
    ),

    /**
     * .isCall
     *
     * whether the next opcode will switch to another calling context
     */
    isCall: createLeaf(
      ["./trace"], (step) => step.op == "CALL" || step.op == "DELEGATECALL"
    ),

    /**
     * .isCreate
     */
    isCreate: createLeaf(
      ["./trace"], (step) => step.op == "CREATE"
    ),

    /**
     * .isHalting
     *
     * whether the next instruction halts or returns from a calling context
     */
    isHalting: createLeaf(
      ["./trace"], (step) => step.op == "STOP" || step.op == "RETURN"
    )
  };

  if (state) {
    const isRelative = (path) => (
      typeof path == "string" && (
        path.startsWith("./") || path.startsWith("../")
      )
    );

    if (isRelative(state)) {
      state = `../${state}`;
    }

    Object.assign(base, {
      /**
       * .callAddress
       *
       * address transferred to by call operation
       */
      callAddress: createLeaf(
        ["./isCall", "./trace", state],

        (matches, step, {stack}) => {
          if (!matches) return null;

          let address = stack[stack.length - 2]
          address = "0x" + address.substring(24);
          return address;
        }
      ),

      /**
       * .createBinary
       *
       * binary code to execute via create operation
       */
      createBinary: createLeaf(
        ["./isCreate", "./trace", state],

        (matches, step, {stack, memory}) => {
          if (!matches) return null;

          // Get the code that's going to be created from memory.
          // Note we multiply by 2 because these offsets are in bytes.
          const offset = parseInt(stack[stack.length - 2], 16) * 2;
          const length = parseInt(stack[stack.length - 3], 16) * 2;

          return "0x" + memory.join("").substring(offset, offset + length);
        }
      )
    });
  }

  return base;
}

const evm = createSelectorTree({
  /**
   * evm.state
   */
  state: (state) => state.evm,

  /**
   * evm.info
   */
  info: {
    /**
     * evm.info.contexts
     */
    contexts: createLeaf(['/state'], (state) => state.info.contexts.byContext),

    /**
     * evm.info.instances
     */
    instances: createLeaf(['/state'], (state) => state.info.instances.byAddress),

    /**
     * evm.info.binaries
     */
    binaries: {
      _: createLeaf(['/state'], (state) => state.info.contexts.byBinary),

      /**
       * evm.info.binaries.search
       *
       * returns function (binary) => context
       */
      search: createLeaf(['./_'], (binaries) => {
        // HACK ignore link references for search
        // link references come in two forms: with underscores or all zeroes
        const toRegExp = (binary) =>
          new RegExp(`^${binary.replace(/__.{38}|0{40}/g, ".{40}")}`)

        let matchers = Object.entries(binaries)
          .map( ([binary, {context}]) => ({
            context,
            regex: toRegExp(binary)
          }))

        return (binary) => matchers
          .filter( ({ context, regex }) => binary.match(regex) )
          .map( ({ context }) => ({ context }) )
          [0] || null;
      })
    }
  },

  /**
   * evm.current
   */
  current: {

    /**
     * evm.current.callstack
     */
    callstack: (state) => state.evm.proc.callstack,

    /**
     * evm.current.call
     */
    call: createLeaf(
      ["./callstack"],

      (stack) => stack.length ? stack[stack.length - 1] : {}
    ),

    /**
     * evm.current.context
     */
    context: createLeaf(
      ["./call", "/info/instances", "/info/binaries/search", "/info/contexts"],

      ({address, binary}, instances, search, contexts) => {
        let record;
        if (address) {
          record = instances[address];
          binary = record.binary
        } else {
          record = search(binary);
        }

        let context = contexts[(record || {}).context];

        return {
          ...context,
          binary
        }
      }
    ),

    /**
     * evm.current.state
     *
     * evm state info: as of last operation, before op defined in step
     */
    state: Object.assign({}, ...(
      [
        "depth",
        "error",
        "gas",
        "memory",
        "stack",
        "storage"
      ].map( (param) => ({
        [param]: createLeaf([trace.step], (step) => step[param])
      }))
    ))
  },

  /**
   * evm.next
   */
  next: {

    /**
     * evm.next.state
     *
     * evm state as a result of next step operation
     */
    state: Object.assign({}, ...(
      [
        "depth",
        "error",
        "gas",
        "memory",
        "stack",
        "storage"
      ].map( (param) => ({
        [param]: createLeaf([trace.next], (step) => step[param])
      }))
    )),

    /**
     * evm.next.step
     */
    step: createStepSelectors(trace.step, "/current/state")
  }
});

export default evm;
<commit_msg>Add note about linkref format origins<commit_after>import debugModule from "debug";
const debug = debugModule("debugger:evm:selectors");

import { createSelectorTree, createLeaf } from "reselect-tree";

import trace from "lib/trace/selectors";

const WORD_SIZE = 0x20;

/**
 * create EVM-level selectors for a given trace step selector
 * may specify additional selectors to include
 */
function createStepSelectors(step, state = null) {
  let base = {
    /**
     * .trace
     *
     * trace step info related to next evm operation
     */
    trace: createLeaf(
      [step], ({gasCost, op, pc}) => ({gasCost, op, pc})
    ),

    /**
     * .programCounter
     */
    programCounter: createLeaf(
      ["./trace"], (step) => step.pc
    ),

    /**
     * .isJump
     */
    isJump: createLeaf(
      ["./trace"], (step) => (
        step.op != "JUMPDEST" && step.op.indexOf("JUMP") == 0
      )
    ),

    /**
     * .isCall
     *
     * whether the next opcode will switch to another calling context
     */
    isCall: createLeaf(
      ["./trace"], (step) => step.op == "CALL" || step.op == "DELEGATECALL"
    ),

    /**
     * .isCreate
     */
    isCreate: createLeaf(
      ["./trace"], (step) => step.op == "CREATE"
    ),

    /**
     * .isHalting
     *
     * whether the next instruction halts or returns from a calling context
     */
    isHalting: createLeaf(
      ["./trace"], (step) => step.op == "STOP" || step.op == "RETURN"
    )
  };

  if (state) {
    const isRelative = (path) => (
      typeof path == "string" && (
        path.startsWith("./") || path.startsWith("../")
      )
    );

    if (isRelative(state)) {
      state = `../${state}`;
    }

    Object.assign(base, {
      /**
       * .callAddress
       *
       * address transferred to by call operation
       */
      callAddress: createLeaf(
        ["./isCall", "./trace", state],

        (matches, step, {stack}) => {
          if (!matches) return null;

          let address = stack[stack.length - 2]
          address = "0x" + address.substring(24);
          return address;
        }
      ),

      /**
       * .createBinary
       *
       * binary code to execute via create operation
       */
      createBinary: createLeaf(
        ["./isCreate", "./trace", state],

        (matches, step, {stack, memory}) => {
          if (!matches) return null;

          // Get the code that's going to be created from memory.
          // Note we multiply by 2 because these offsets are in bytes.
          const offset = parseInt(stack[stack.length - 2], 16) * 2;
          const length = parseInt(stack[stack.length - 3], 16) * 2;

          return "0x" + memory.join("").substring(offset, offset + length);
        }
      )
    });
  }

  return base;
}

const evm = createSelectorTree({
  /**
   * evm.state
   */
  state: (state) => state.evm,

  /**
   * evm.info
   */
  info: {
    /**
     * evm.info.contexts
     */
    contexts: createLeaf(['/state'], (state) => state.info.contexts.byContext),

    /**
     * evm.info.instances
     */
    instances: createLeaf(['/state'], (state) => state.info.instances.byAddress),

    /**
     * evm.info.binaries
     */
    binaries: {
      _: createLeaf(['/state'], (state) => state.info.contexts.byBinary),

      /**
       * evm.info.binaries.search
       *
       * returns function (binary) => context
       */
      search: createLeaf(['./_'], (binaries) => {
        // HACK ignore link references for search
        // link references come in two forms: with underscores or all zeroes
        // the underscore format is used by Truffle to reference links by name
        // zeroes are used by solc directly, as libraries inject their own
        // address at CREATE-time
        const toRegExp = (binary) =>
          new RegExp(`^${binary.replace(/__.{38}|0{40}/g, ".{40}")}`)

        let matchers = Object.entries(binaries)
          .map( ([binary, {context}]) => ({
            context,
            regex: toRegExp(binary)
          }))

        return (binary) => matchers
          .filter( ({ context, regex }) => binary.match(regex) )
          .map( ({ context }) => ({ context }) )
          [0] || null;
      })
    }
  },

  /**
   * evm.current
   */
  current: {

    /**
     * evm.current.callstack
     */
    callstack: (state) => state.evm.proc.callstack,

    /**
     * evm.current.call
     */
    call: createLeaf(
      ["./callstack"],

      (stack) => stack.length ? stack[stack.length - 1] : {}
    ),

    /**
     * evm.current.context
     */
    context: createLeaf(
      ["./call", "/info/instances", "/info/binaries/search", "/info/contexts"],

      ({address, binary}, instances, search, contexts) => {
        let record;
        if (address) {
          record = instances[address];
          binary = record.binary
        } else {
          record = search(binary);
        }

        let context = contexts[(record || {}).context];

        return {
          ...context,
          binary
        }
      }
    ),

    /**
     * evm.current.state
     *
     * evm state info: as of last operation, before op defined in step
     */
    state: Object.assign({}, ...(
      [
        "depth",
        "error",
        "gas",
        "memory",
        "stack",
        "storage"
      ].map( (param) => ({
        [param]: createLeaf([trace.step], (step) => step[param])
      }))
    ))
  },

  /**
   * evm.next
   */
  next: {

    /**
     * evm.next.state
     *
     * evm state as a result of next step operation
     */
    state: Object.assign({}, ...(
      [
        "depth",
        "error",
        "gas",
        "memory",
        "stack",
        "storage"
      ].map( (param) => ({
        [param]: createLeaf([trace.next], (step) => step[param])
      }))
    )),

    /**
     * evm.next.step
     */
    step: createStepSelectors(trace.step, "/current/state")
  }
});

export default evm;
<|endoftext|>


<commit_before>import angular from 'angular';

export default class FacebookController {
    constructor($scope, FacebookService) {
        this.$scope = $scope;
        this.FacebookService = FacebookService;

        $scope.isLoggedIn = false;

        $scope.login = () => {
            FacebookService.login().then(() => {
                this.refresh();
            });
        };

        this.refresh();
    }

    refresh() {
        this.FacebookService.me().then(
            response => {
                this.$scope.welcomeMsg = 'Welcome ' + response.name;
                this.$scope.isLoggedIn = true;
            },
            err => {
                this.$scope.welcomeMsg = 'Please log in';
            });

    }
}

FacebookController.$inject = ['$scope', 'FacebookService'];<commit_msg>proper setter for state<commit_after>import angular from 'angular';

export default class FacebookController {
    constructor($scope, FacebookService) {
        this.$scope = $scope;
        this.FacebookService = FacebookService;

        $scope.isLoggedIn = false;

        $scope.login = () => {
            FacebookService.login().then(() => {
                this.refresh();
            });
        };

        this.refresh();
    }

    refresh() {
        this.FacebookService.me().then(
            response => {
                this.$scope.welcomeMsg = 'Welcome ' + response.name;
                this.$scope.isLoggedIn = true;
            },
            err => {
                this.$scope.welcomeMsg = 'Please log in';
            });

    }

    setLogin(isLoggedIn) {

        return this;
    }
}

FacebookController.$inject = ['$scope', 'FacebookService'];<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	AssignedActivity = mongoose.model('AssignedActivity');

/**
 * Globals
 */
var activity01, activity02;

describe('Assigned Activity Model Unit Tests:', function() {
	beforeEach(function(done) {
		activity01 = new AssignedActivity({
			_id: '5421bc631b303e101ec67747',
			year: '2014',
			semester: 'spring',
			teaching: 33,
			research: 33,
			service: 34
		});

		activity02 = new AssignedActivity({
			_id: '5421bc631b303e101ec67747',
			year: '2014',
			semester: 'spring',
			teaching: 33,
			research: 33,
			service: 34
		});

		done();
	});

	describe('Method Save', function() {
		it('should be able to save without problem', function(done) {
			activity01.save();
			done();
		});

		it('should fail to save an existing activity again', function(done) {
			activity01.save();
			return activity02.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save a year that is beyond the present year', function(done) {
			activity01.year = 2015;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should not fail to save a semester that is not spring, fall, summer', function(done) {
			activity01.semester = 'fall';
			activity01.save();
			done();
		});

		it('should fail to save a semester that is not spring, fall, summer', function(done) {
			activity01.semester = 'winter';
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if teaching that is a negative number', function(done) {
			activity01.teaching = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if research that is a negative number', function(done) {
			activity01.research = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if service that is a negative number', function(done) {
			activity01.service = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if teaching, research and service don\'t add up to 100', function(done) {
			activity01.teaching = 10;
			activity01.service = 20;
			activity01.research = 5;

			return activity01.save(function(err) {
				should.exist(err);
				console.log(err);
				done();
			});
		});
	});

	afterEach(function(done) {
		AssignedActivity.remove().exec();
		done();
	});
});<commit_msg>Removed console.log() test <commit_after>'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	AssignedActivity = mongoose.model('AssignedActivity');

/**
 * Globals
 */
var activity01, activity02;

describe('Assigned Activity Model Unit Tests:', function() {
	beforeEach(function(done) {
		activity01 = new AssignedActivity({
			_id: '5421bc631b303e101ec67747',
			year: '2014',
			semester: 'spring',
			teaching: 33,
			research: 33,
			service: 34
		});

		activity02 = new AssignedActivity({
			_id: '5421bc631b303e101ec67747',
			year: '2014',
			semester: 'spring',
			teaching: 33,
			research: 33,
			service: 34
		});

		done();
	});

	describe('Method Save', function() {
		it('should be able to save without problem', function(done) {
			activity01.save();
			done();
		});

		it('should fail to save an existing activity again', function(done) {
			activity01.save();
			return activity02.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save a year that is beyond the present year', function(done) {
			activity01.year = 2015;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should not fail to save a semester that is not spring, fall, summer', function(done) {
			activity01.semester = 'fall';
			activity01.save();
			done();
		});

		it('should fail to save a semester that is not spring, fall, summer', function(done) {
			activity01.semester = 'winter';
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if teaching that is a negative number', function(done) {
			activity01.teaching = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if research that is a negative number', function(done) {
			activity01.research = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if service that is a negative number', function(done) {
			activity01.service = -50;
			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should fail to save if teaching, research and service don\'t add up to 100', function(done) {
			activity01.teaching = 10;
			activity01.service = 20;
			activity01.research = 5;

			return activity01.save(function(err) {
				should.exist(err);
				done();
			});
		});
	});

	afterEach(function(done) {
		AssignedActivity.remove().exec();
		done();
	});
});
<|endoftext|>


<commit_before>var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Find Records
 * GET /:model
 * GET /:model/:id
 *
 * An API call to find and return model instances from the data adapter using the specified criteria.
 * If an id was specified, just the instance with that unique id will be returned.
 */
module.exports = function (req, res) {
    if (actionUtil.parsePk(req)) return require('./findOne')(req, res);

    var Model = actionUtil.parseModel(req),
        query = Model
            .find()
            .where(actionUtil.parseCriteria(req))
            .limit(actionUtil.parseLimit(req))
            .skip(actionUtil.parseSkip(req))
            .sort(actionUtil.parseSort(req));

    query = actionUtil.populateEach(query, req);
    query.exec(function (error, records) {
        if (error) return res.serverError(error);
        return res.ok(records);
    });
};
<commit_msg>Resolve #32<commit_after>var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Find Records
 * GET /:model
 * GET /:model/:id
 *
 * An API call to find and return model instances from the data adapter using the specified criteria.
 * If an id was specified, just the instance with that unique id will be returned.
 */
module.exports = function (req, res) {
    if (actionUtil.parsePk(req)) return require('./findOne')(req, res);

    var Model = actionUtil.parseModel(req),
        where = actionUtil.parseCriteria(req),
        limit = actionUtil.parseLimit(req),
        skip = actionUtil.parseSkip(req),
        sort = actionUtil.parseSort(req),
        query = Model.find().where(where).limit(limit).skip(skip).sort(sort);

    query = actionUtil.populateEach(query, req);
    query.exec(function (error, records) {
        if (error) return res.serverError(error);

        Model
            .count()
            .exec(function (error, count) {
                if (error) return res.serverError(error);

                var metaInfo = {
                    start: skip,
                    end: skip + limit,
                    limit: limit,
                    total: count,
                    criteria: where
                };

                res.set('Content-Range', metaInfo.start + '-' + metaInfo.end + '/' + metaInfo.total);
                return res.ok(records, null, null, metaInfo);
            });
    });
};
<|endoftext|>


<commit_before>'use strict';

let gulp = require('gulp');
let spritesmith = require('gulp.spritesmith');
let plumber = require('gulp-plumber');
let config = require('./gulp.config.js');

let options = {
	imgName: 'sprites.png',
	cssName: 'sprite-vars.<%= extPreprocessor %>',
	imgPath: '../imgs/sprites/sprites.png',
	algorithm: 'binary-tree',
	engine: 'pngsmith',
	cssVarMap: sprite => {
		sprite.name = `sprite-${sprite.name}`;
	}
};

gulp.task('sprites', spritesTask);

function spritesTask() {
  let sprite = gulp
    .src(config.sprites.src)
    .pipe(plumber())
    .pipe(spritesmith(options));

  sprite.img.pipe(gulp.dest(config.sprites.dest));
  sprite.css.pipe(gulp.dest('./client/styles/components/'));
}
<commit_msg>comma in sprite-images<commit_after>'use strict';

let gulp = require('gulp');
let spritesmith = require('gulp.spritesmith');
let plumber = require('gulp-plumber');
let config = require('./gulp.config.js');

let options = {
	imgName: 'sprites.png',
	cssName: 'sprite-vars.<%= extPreprocessor %>',
	imgPath: '../imgs/sprites/sprites.png',
	algorithm: 'binary-tree',
	engine: 'pngsmith',
	cssVarMap: sprite => {
		sprite.name = `sprite-${sprite.name}`;
	},
};

gulp.task('sprites', spritesTask);

function spritesTask() {
  let sprite = gulp
    .src(config.sprites.src)
    .pipe(plumber())
    .pipe(spritesmith(options));

  sprite.img.pipe(gulp.dest(config.sprites.dest));
  sprite.css.pipe(gulp.dest('./client/styles/components/'));
}
<|endoftext|>


<commit_before>/*global UIATarget:true */
"use strict";

var system = UIATarget.localTarget().host();
var defWaitForDataTimeout = 3600;
var waitForDataTimeout = defWaitForDataTimeout;
var curAppiumCmdId = -1;
var shell = null;

var sysExec = function(cmd, shellOverride) {
  if (typeof shellOverride === "undefined") {
    shellOverride = shell;
  }
  var res = system.performTaskWithPathArgumentsTimeout(shellOverride,
      ['-c', cmd], 3);
  if (res.exitCode !== 0) {
    throw new Error("Failed executing the command " + cmd + " (exit code " + res.exitCode + ")");
  } else {
    var output = res.stdout.trim();
    if (output.length) {
      return output;
    } else {
      throw new Error("Executing " + cmd + " failed since there was no output");
    }
  }
};

shell = function() {
  try {
    var ret = sysExec("echo $SHELL", "/bin/sh");
    console.log("Using shell: " + ret);
    return ret;
  } catch (e) {
    console.log("Error getting user shell: " + e.message);
    return "/bin/bash";
  }
}();

// get npm-installed instruments_client bin if necessary
var globalPath = (function() {
  try {
    return sysExec('which instruments_client');
  } catch (e) {
    return null;
  }
})();

// figure out where instruments client is (relative to where appium is run)
var clientPath = (function() {
  var client = 'instruments/client.js';
  var module = 'node_modules/appium/';

  try {
    sysExec('ls ' + client);
    return client;
  } catch(e) {
    try {
      sysExec('ls ' + module + client);
      return module + client;
    } catch(e) {
      if (globalPath === null) {
        console.log("WARNING: could not find instruments/client.js in its " +
                    "usual place, and global instruments_client not around " +
                    "either. This could cause problems");
      }
    }
  }
})();

// figure out where node is
var nodePath = (function() {
  var path = null;
  try {
    path = sysExec("echo $NODE_BIN");
    console.log("Found node using $NODE_BIN: " + path);
  } catch(e) {
    try {
      path = sysExec('which node');
      console.log("Found node using `which node`: " + path);
    } catch (e) {
      var appScript = [
          'try'
        , '  set appiumIsRunning to false'
        , '  tell application "System Events"'
        , '    set appiumIsRunning to name of every process contains "Appium"'
        , '  end tell'
        , '  if appiumIsRunning then'
        , '    tell application "Appium" to return node path'
        , '  end if'
        , 'end try'
        , 'return "NULL"'
      ].join("\n");
      var appNodeWorked = false;
      try {
        path = sysExec("osascript -e '" + appScript + "'");
        appNodeWorked = path !== "NULL";
      } catch(e) {}
      if (!appNodeWorked) {
        try {
          path = sysExec("ls /usr/local/bin/node");
          console.log("Found node at " + path);
        } catch (e) {
          try {
            path = sysExec("ls /opt/local/bin/node");
            console.log("Found node at " + path);
          } catch (e) {
            throw new Error("Could not find node using `which node`, at /usr/" +
                            "local/bin/node, at /opt/local/bin/node, at " +
                            "$NODE_BIN, or by querying Appium.app. Where is " +
                            "it?");
          }
        }
      } else {
        console.log("Found node in Appium.app");
      }
    }
  }
  return path;
})();

var isAppiumApp = (function() {
  try {
    return sysExec('echo $Appium_app') !== null;
  } catch(e) {
    return false;
  }
})();

var sendResultAndGetNext = function(result) {
  curAppiumCmdId++;
  var args = ['-s', '/tmp/instruments_sock'], res
    , binaryPath = globalPath;
  if (isAppiumApp) {
    globalPath = null;
  }
  if (globalPath === null) {
    binaryPath = nodePath;
    args.unshift(clientPath);
  }
  if (typeof result !== "undefined") {
    args = args.concat(['-r', JSON.stringify(result)]);
  }
  try {
    res = system.performTaskWithPathArgumentsTimeout(binaryPath, args, waitForDataTimeout);
  } catch(e) {
    console.log(e.name + " error getting command " + curAppiumCmdId + ": " + e.message);
    return null;
  }

  if (res.exitCode !== 0) {
    var cmd = binaryPath + " " + args.join(" ");
    console.log("Instruments client (" + cmd + ") exited with " + res.exitCode +
                ", here's stderr:");
    console.log(res.stderr);
    console.log("And stdout:");
    console.log(res.stdout);
  }
  return res.stdout;
};

var getFirstCommand = function() {
  return sendResultAndGetNext();
};

<commit_msg>don't allow custom shell, but do load user's .bashrc<commit_after>/*global UIATarget:true */
"use strict";

var system = UIATarget.localTarget().host();
var defWaitForDataTimeout = 3600;
var waitForDataTimeout = defWaitForDataTimeout;
var curAppiumCmdId = -1;
var user = null;

var sysExec = function(cmd) {
  var params = [];
  if (user !== null) {
    params = params.concat(['--rcfile', '/Users/' + user + '/.bashrc']);
  }
  params = params.concat(['-c', cmd]);
  var res = system.performTaskWithPathArgumentsTimeout("/bin/bash",
      params, 3);
  if (res.exitCode !== 0) {
    throw new Error("Failed executing the command " + cmd + " (exit code " + res.exitCode + ")");
  } else {
    var output = res.stdout.trim();
    if (output.length) {
      return output;
    } else {
      throw new Error("Executing " + cmd + " failed since there was no output");
    }
  }
};

user = function() {
  try {
    var ret = sysExec("whoami");
    console.log("Instruments shell user: " + ret);
    return ret;
  } catch (e) {
    console.log("Error getting user: " + e.message);
    return null;
  }
}();

// get npm-installed instruments_client bin if necessary
var globalPath = (function() {
  try {
    return sysExec('which instruments_client');
  } catch (e) {
    return null;
  }
})();

// figure out where instruments client is (relative to where appium is run)
var clientPath = (function() {
  var client = 'instruments/client.js';
  var module = 'node_modules/appium/';

  try {
    sysExec('ls ' + client);
    return client;
  } catch(e) {
    try {
      sysExec('ls ' + module + client);
      return module + client;
    } catch(e) {
      if (globalPath === null) {
        console.log("WARNING: could not find instruments/client.js in its " +
                    "usual place, and global instruments_client not around " +
                    "either. This could cause problems");
      }
    }
  }
})();

// figure out where node is
var nodePath = (function() {
  var path = null;
  try {
    path = sysExec("echo $NODE_BIN");
    console.log("Found node using $NODE_BIN: " + path);
  } catch(e) {
    try {
      path = sysExec('which node');
      console.log("Found node using `which node`: " + path);
    } catch (e) {
      var appScript = [
          'try'
        , '  set appiumIsRunning to false'
        , '  tell application "System Events"'
        , '    set appiumIsRunning to name of every process contains "Appium"'
        , '  end tell'
        , '  if appiumIsRunning then'
        , '    tell application "Appium" to return node path'
        , '  end if'
        , 'end try'
        , 'return "NULL"'
      ].join("\n");
      var appNodeWorked = false;
      try {
        path = sysExec("osascript -e '" + appScript + "'");
        appNodeWorked = path !== "NULL";
      } catch(e) {}
      if (!appNodeWorked) {
        try {
          path = sysExec("ls /usr/local/bin/node");
          console.log("Found node at " + path);
        } catch (e) {
          try {
            path = sysExec("ls /opt/local/bin/node");
            console.log("Found node at " + path);
          } catch (e) {
            throw new Error("Could not find node using `which node`, at /usr/" +
                            "local/bin/node, at /opt/local/bin/node, at " +
                            "$NODE_BIN, or by querying Appium.app. Where is " +
                            "it?");
          }
        }
      } else {
        console.log("Found node in Appium.app");
      }
    }
  }
  return path;
})();

var isAppiumApp = (function() {
  try {
    return sysExec('echo $Appium_app') !== null;
  } catch(e) {
    return false;
  }
})();

var sendResultAndGetNext = function(result) {
  curAppiumCmdId++;
  var args = ['-s', '/tmp/instruments_sock'], res
    , binaryPath = globalPath;
  if (isAppiumApp) {
    globalPath = null;
  }
  if (globalPath === null) {
    binaryPath = nodePath;
    args.unshift(clientPath);
  }
  if (typeof result !== "undefined") {
    args = args.concat(['-r', JSON.stringify(result)]);
  }
  try {
    res = system.performTaskWithPathArgumentsTimeout(binaryPath, args, waitForDataTimeout);
  } catch(e) {
    console.log(e.name + " error getting command " + curAppiumCmdId + ": " + e.message);
    return null;
  }

  if (res.exitCode !== 0) {
    var cmd = binaryPath + " " + args.join(" ");
    console.log("Instruments client (" + cmd + ") exited with " + res.exitCode +
                ", here's stderr:");
    console.log(res.stderr);
    console.log("And stdout:");
    console.log(res.stdout);
  }
  return res.stdout;
};

var getFirstCommand = function() {
  return sendResultAndGetNext();
};

<|endoftext|>


<commit_before>{
  /*
   * WARNING
   * -------
   *
   * Make sure you are editing 'configuration.js' and not the default configuration file, as the default one will be replaced with each update.
   *
   */

  /*
   * Simple way of configuring the plugin
   * ------------------------------------
   *
   * Set value of 'defaultAccount' to one of the following values:
   *
   *   "#preferred"  to use your preferred TweetDeck account (the one used to log into TweetDeck)
   *   "#last"       to specify the account that was selected last time (only updates if a single account is selected)
   *   "#default"    to fall back to default TweetDeck behavior; useful for advanced configuration below, otherwise disable the plugin instead
   *   "@myAccount"  to specify an account name to use; has to be one of your registered account names
   *
   */

  defaultAccount: "#preferred",

  /*
   * Advanced way of configuring the plugin
   * --------------------------------------
   *
   * This assumes a basic knowledge of JavaScript and jQuery.
   *
   * 1. Set value of 'useAdvancedSelector' to true
   * 2. Uncomment the 'customSelector' function, and replace the example code with your desired behavior
   *
   * The 'customSelector' function should return a string in one of the formats supported by 'defaultAccount'.
   * If it returns anything else (for example, false or undefined), it falls back to 'defaultAccount' behavior.
   *
   *
   * The 'type' parameter is TweetDeck column type. Here is the full list of column types, note that some are
   * unused and have misleading names (for example, Home columns are 'col_timeline' instead of 'col_home'):
   *   col_timeline, col_interactions, col_mentions, col_followers, col_search, col_list,
   *   col_customtimeline, col_messages, col_usertweets, col_favorites, col_activity,
   *   col_dataminr, col_home, col_me, col_inbox, col_scheduled, col_unknown
   *
   * If you want to see your current column types, run this in your browser console:
   *   TD.controller.columnManager.getAllOrdered().map(obj => obj.getColumnType());
   *
   *
   * The 'title' parameter is the column title. Some are fixed (such as 'Home' or 'Notifications'),
   * some contain specific information (for example, Search columns contain the search query).
   *
   *
   * The 'account' parameter is the account name displayed next to the column title (including the @).
   * This parameter is empty for some columns (such as Messages, or Notifications for all accounts) or can
   * contain other text (for example, the Scheduled column contains the string 'All accounts').
   *
   *
   * The 'column' parameter is a TweetDeck column object. If you want to see all properties of the object,
   * run the following code in your browser console, which will return an array containing all of your
   * current column objects in order:
   *   TD.controller.columnManager.getAllOrdered()
   *
   */

  useAdvancedSelector: false,

  /*customSelector: function(type, title, account, column){
    if (type === "col_search" && title === "TweetDuck"){
      // This is a search column that looks for 'TweetDuck' in the tweets,
      // search columns are normally linked to the preferred account
      // so this forces the @TryTweetDuck account to be used instead.
      return "@TryTweetDuck";
    }
    else if (type === "col_timeline" && account === "@chylexcz"){
      // This is a Home column of my test account @chylexcz,
      // but I want to reply to tweets from my official account.
      return "@chylexmc";
    }

    // otherwise returns 'undefined' which falls back to 'defaultAccount' behavior
  }*/
}<commit_msg>Remove a warning in the reply-account plugin's default config<commit_after>{
  /*
   * Simple way of configuring the plugin
   * ------------------------------------
   *
   * Set value of 'defaultAccount' to one of the following values:
   *
   *   "#preferred"  to use your preferred TweetDeck account (the one used to log into TweetDeck)
   *   "#last"       to specify the account that was selected last time (only updates if a single account is selected)
   *   "#default"    to fall back to default TweetDeck behavior; useful for advanced configuration below, otherwise disable the plugin instead
   *   "@myAccount"  to specify an account name to use; has to be one of your registered account names
   *
   */

  defaultAccount: "#preferred",

  /*
   * Advanced way of configuring the plugin
   * --------------------------------------
   *
   * This assumes a basic knowledge of JavaScript and jQuery.
   *
   * 1. Set value of 'useAdvancedSelector' to true
   * 2. Uncomment the 'customSelector' function, and replace the example code with your desired behavior
   *
   * The 'customSelector' function should return a string in one of the formats supported by 'defaultAccount'.
   * If it returns anything else (for example, false or undefined), it falls back to 'defaultAccount' behavior.
   *
   *
   * The 'type' parameter is TweetDeck column type. Here is the full list of column types, note that some are
   * unused and have misleading names (for example, Home columns are 'col_timeline' instead of 'col_home'):
   *   col_timeline, col_interactions, col_mentions, col_followers, col_search, col_list,
   *   col_customtimeline, col_messages, col_usertweets, col_favorites, col_activity,
   *   col_dataminr, col_home, col_me, col_inbox, col_scheduled, col_unknown
   *
   * If you want to see your current column types, run this in your browser console:
   *   TD.controller.columnManager.getAllOrdered().map(obj => obj.getColumnType());
   *
   *
   * The 'title' parameter is the column title. Some are fixed (such as 'Home' or 'Notifications'),
   * some contain specific information (for example, Search columns contain the search query).
   *
   *
   * The 'account' parameter is the account name displayed next to the column title (including the @).
   * This parameter is empty for some columns (such as Messages, or Notifications for all accounts) or can
   * contain other text (for example, the Scheduled column contains the string 'All accounts').
   *
   *
   * The 'column' parameter is a TweetDeck column object. If you want to see all properties of the object,
   * run the following code in your browser console, which will return an array containing all of your
   * current column objects in order:
   *   TD.controller.columnManager.getAllOrdered()
   *
   */

  useAdvancedSelector: false,

  /*customSelector: function(type, title, account, column){
    if (type === "col_search" && title === "TweetDuck"){
      // This is a search column that looks for 'TweetDuck' in the tweets,
      // search columns are normally linked to the preferred account
      // so this forces the @TryTweetDuck account to be used instead.
      return "@TryTweetDuck";
    }
    else if (type === "col_timeline" && account === "@chylexcz"){
      // This is a Home column of my test account @chylexcz,
      // but I want to reply to tweets from my official account.
      return "@chylexmc";
    }

    // otherwise returns 'undefined' which falls back to 'defaultAccount' behavior
  }*/
}<|endoftext|>


<commit_before>// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// function for old data
// process old data through days, until current day
exp.process_old_data = function (database) {
    console.log("process_old_data");

};
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// function for current day
// just for current day
// run once an hour          ???? maybe more often ?
// --------------------------------------------------------------------------------------
// map usernames to mac addresses
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database) {
  min_date = new Date();        // current day
  max_date = new Date(min_date.getTime() + 86400000);   // the next day

  database.logs.aggregate([
    {
      $match :
        {
          timestamp :             // get only data for current day
            {
              $gte : min_date,
              $lt : max_date
            },
          pn :
            {
              $ne : ""            // only non empty usernames
            }
          //  ,
          //csi :                 // data can contain records where one mac address is empty for certain username, we also want to includes these records
          //  {
          //    $ne : ""            // only non empty mac addresses
          //  }
        }
    },
    {
      $project :                  // need only username and mac address
        {
          pn : 1,
          csi : 1
        }
    },
    {
      $group :                    // group by pair [ username, mac address ]
        {
          _id :
            {
              pn : "$pn",
              csi : "$csi"
            }
        }
    },
    {
      $group :                    // group again by username
        {
          _id :
            {
              pn : "$_id.pn"
            },
            addrs :
              {
                $addToSet : "$$ROOT._id.csi"  // add mac addresses for matching username to array
              }
        }
    },
    //{
    //  $out : "users_mac"       // write result to collection
    //}
    ],

    function(err, items) {
      transform(items, database);
    });
};
// --------------------------------------------------------------------------------------
// transform data and update database
// --------------------------------------------------------------------------------------
function transform(items, database)
{
  dict = {};

  for(var item in items) {
    var key = items[item];
    dict["username"] = key._id.pn;  // save username
    dict["addrs"] = key.addrs;  // save array of mac addressses

    database.users_mac.update(
      {                                 // query
        "username" : dict["username"]
      },
      {                                 // update
        "username" : dict["username"],  // set username
        $addToSet :                     // add mac addresses to array
          {
            "addrs" :
              {
                $each : dict["addrs"]   // each one separately not whole array
              }
          }
      },
      {
        upsert : true                   // update if matching document is found
      },
      function (err, result) {
        // nothing to do here
        // update needs a function to work
    });
  }
}
// --------------------------------------------------------------------------------------
module.exports = exp;
<commit_msg>add TODO<commit_after>// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// function for old data
// process old data through days, until current day
exp.process_old_data = function (database) {
    console.log("process_old_data");
    // TODO
};
// --------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------
// function for current day
// just for current day
// run once an hour          ???? maybe more often ?
// --------------------------------------------------------------------------------------
// map usernames to mac addresses
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database) {
  min_date = new Date();        // current day
  max_date = new Date(min_date.getTime() + 86400000);   // the next day

  database.logs.aggregate([
    {
      $match :
        {
          timestamp :             // get only data for current day
            {
              $gte : min_date,
              $lt : max_date
            },
          pn :
            {
              $ne : ""            // only non empty usernames
            }
          //  ,
          //csi :                 // data can contain records where one mac address is empty for certain username, we also want to includes these records
          //  {
          //    $ne : ""            // only non empty mac addresses
          //  }
        }
    },
    {
      $project :                  // need only username and mac address
        {
          pn : 1,
          csi : 1
        }
    },
    {
      $group :                    // group by pair [ username, mac address ]
        {
          _id :
            {
              pn : "$pn",
              csi : "$csi"
            }
        }
    },
    {
      $group :                    // group again by username
        {
          _id :
            {
              pn : "$_id.pn"
            },
            addrs :
              {
                $addToSet : "$$ROOT._id.csi"  // add mac addresses for matching username to array
              }
        }
    },
    //{
    //  $out : "users_mac"       // write result to collection
    //}
    ],

    function(err, items) {
      transform(items, database);
    });
};
// --------------------------------------------------------------------------------------
// transform data and update database
// --------------------------------------------------------------------------------------
function transform(items, database)
{
  dict = {};

  for(var item in items) {
    var key = items[item];
    dict["username"] = key._id.pn;  // save username
    dict["addrs"] = key.addrs;  // save array of mac addressses

    database.users_mac.update(
      {                                 // query
        "username" : dict["username"]
      },
      {                                 // update
        "username" : dict["username"],  // set username
        $addToSet :                     // add mac addresses to array
          {
            "addrs" :
              {
                $each : dict["addrs"]   // each one separately not whole array
              }
          }
      },
      {
        upsert : true                   // update if matching document is found
      },
      function (err, result) {
        // nothing to do here
        // update needs a function to work
    });
  }
}
// --------------------------------------------------------------------------------------
module.exports = exp;
<|endoftext|>