<commit_before>import fs from 'fs';
import path from 'path';
import JSON5 from 'json5';
import findCacheDir from 'find-cache-dir';
import { createDefaultWebpackConfig } from '@storybook/core/server';

// avoid ESLint errors
const logger = console;

function removeReactHmre(presets) {
  const index = presets.indexOf('react-hmre');
  if (index > -1) {
    presets.splice(index, 1);
  }
}

// Tries to load a .babelrc and returns the parsed object if successful
function loadBabelConfig(babelConfigPath) {
  let config;
  if (fs.existsSync(babelConfigPath)) {
    const content = fs.readFileSync(babelConfigPath, 'utf-8');
    try {
      config = JSON5.parse(content);
      config.babelrc = false;
    } catch (e) {
      logger.error(`=> Error parsing .babelrc file: ${e.message}`);
      throw e;
    }
  }

  if (!config) return null;

  // Remove react-hmre preset.
  // It causes issues with react-storybook.
  // We don't really need it.
  // Earlier, we fix this by runnign storybook in the production mode.
  // But, that hide some useful debug messages.
  if (config.presets) {
    removeReactHmre(config.presets);
  }

  if (config.env && config.env.development && config.env.development.presets) {
    removeReactHmre(config.env.development.presets);
  }

  return config;
}

// `baseConfig` is a webpack configuration bundled with storybook.
// Storybook will look in the `configDir` directory
// (inside working directory) if a config path is not provided.
export default function(configType, baseConfig, projectDir, configDir) {
  const config = baseConfig;

  // Search for a .babelrc in project directory, config directory, and storybook
  // module directory. If found, use that to extend webpack configurations.
  const babelConfigInConfig = loadBabelConfig(path.resolve(configDir, '.babelrc'));
  const babelConfigInProject = loadBabelConfig(path.resolve(projectDir, '.babelrc'));
  const babelConfigInModule = loadBabelConfig('.babelrc');

  let babelConfig = null;
  let babelConfigDir = '';

  if (babelConfigInConfig) {
    logger.info('=> Loading custom .babelrc from config directory.');
    babelConfig = babelConfigInConfig;
    babelConfigDir = configDir;
  } else if (babelConfigInProject) {
    logger.info('=> Loading custom .babelrc from project directory.');
    babelConfig = babelConfigInProject;
    babelConfigDir = projectDir;
  } else {
    babelConfig = babelConfigInModule;
  }

  if (babelConfig) {
    // If the custom config uses babel's `extends` clause, then replace it with
    // an absolute path. `extends` will not work unless we do this.
    if (babelConfig.extends) {
      babelConfig.extends = babelConfigDir
        ? path.resolve(babelConfigDir, babelConfig.extends)
        : path.resolve(babelConfig.extends);
    }
    config.module.rules[0].query = babelConfig;
  }

  // This is a feature of `babel-loader` for webpack (not Babel itself).
  // It enables a cache directory for faster-rebuilds
  // `find-cache-dir` will create the cache directory under the node_modules directory.
  config.module.rules[0].query.cacheDirectory = findCacheDir({
    name: 'react-storybook',
  });

  // Check whether addons.js file exists inside the storybook.
  // Load the default addons.js file if it's missing.
  const storybookDefaultAddonsPath = path.resolve(__dirname, 'addons.js');
  const storybookCustomAddonsPath = path.resolve(configDir, 'addons.js');
  if (fs.existsSync(storybookCustomAddonsPath)) {
    logger.info('=> Loading custom addons config.');
    config.entry.manager.unshift(storybookCustomAddonsPath);
  } else {
    config.entry.manager.unshift(storybookDefaultAddonsPath);
  }

  const defaultConfig = createDefaultWebpackConfig(config);

  // Check whether user has a custom webpack config file and
  // return the (extended) base configuration if it's not available.
  const customConfigPath = path.resolve(configDir, 'webpack.config.js');
  if (!fs.existsSync(customConfigPath)) {
    logger.info('=> Using default webpack setup based on "Create React App".');
    return defaultConfig;
  }

  const customConfig = require(customConfigPath); // eslint-disable-line

  if (typeof customConfig === 'function') {
    logger.info('=> Loading custom webpack config (full-control mode).');
    return customConfig(config, configType, defaultConfig, configDir);
  }

  logger.info('=> Loading custom webpack config.');

  customConfig.module = customConfig.module || {};

  return {
    ...customConfig,
    // We'll always load our configurations after the custom config.
    // So, we'll always load the stuff we need.
    ...config,
    // We need to use our and custom plugins.
    plugins: [...config.plugins, ...(customConfig.plugins || [])],
    module: {
      ...config.module,
      // We need to use our and custom rules.
      ...customConfig.module,
      rules: [...config.module.rules, ...(customConfig.module.rules || [])],
    },
  };
}
<commit_msg>Remove deprecated attempt to load default addons<commit_after>import fs from 'fs';
import path from 'path';
import JSON5 from 'json5';
import findCacheDir from 'find-cache-dir';
import { createDefaultWebpackConfig } from '@storybook/core/server';

// avoid ESLint errors
const logger = console;

function removeReactHmre(presets) {
  const index = presets.indexOf('react-hmre');
  if (index > -1) {
    presets.splice(index, 1);
  }
}

// Tries to load a .babelrc and returns the parsed object if successful
function loadBabelConfig(babelConfigPath) {
  let config;
  if (fs.existsSync(babelConfigPath)) {
    const content = fs.readFileSync(babelConfigPath, 'utf-8');
    try {
      config = JSON5.parse(content);
      config.babelrc = false;
    } catch (e) {
      logger.error(`=> Error parsing .babelrc file: ${e.message}`);
      throw e;
    }
  }

  if (!config) return null;

  // Remove react-hmre preset.
  // It causes issues with react-storybook.
  // We don't really need it.
  // Earlier, we fix this by runnign storybook in the production mode.
  // But, that hide some useful debug messages.
  if (config.presets) {
    removeReactHmre(config.presets);
  }

  if (config.env && config.env.development && config.env.development.presets) {
    removeReactHmre(config.env.development.presets);
  }

  return config;
}

// `baseConfig` is a webpack configuration bundled with storybook.
// Storybook will look in the `configDir` directory
// (inside working directory) if a config path is not provided.
export default function(configType, baseConfig, projectDir, configDir) {
  const config = baseConfig;

  // Search for a .babelrc in project directory, config directory, and storybook
  // module directory. If found, use that to extend webpack configurations.
  const babelConfigInConfig = loadBabelConfig(path.resolve(configDir, '.babelrc'));
  const babelConfigInProject = loadBabelConfig(path.resolve(projectDir, '.babelrc'));
  const babelConfigInModule = loadBabelConfig('.babelrc');

  let babelConfig = null;
  let babelConfigDir = '';

  if (babelConfigInConfig) {
    logger.info('=> Loading custom .babelrc from config directory.');
    babelConfig = babelConfigInConfig;
    babelConfigDir = configDir;
  } else if (babelConfigInProject) {
    logger.info('=> Loading custom .babelrc from project directory.');
    babelConfig = babelConfigInProject;
    babelConfigDir = projectDir;
  } else {
    babelConfig = babelConfigInModule;
  }

  if (babelConfig) {
    // If the custom config uses babel's `extends` clause, then replace it with
    // an absolute path. `extends` will not work unless we do this.
    if (babelConfig.extends) {
      babelConfig.extends = babelConfigDir
        ? path.resolve(babelConfigDir, babelConfig.extends)
        : path.resolve(babelConfig.extends);
    }
    config.module.rules[0].query = babelConfig;
  }

  // This is a feature of `babel-loader` for webpack (not Babel itself).
  // It enables a cache directory for faster-rebuilds
  // `find-cache-dir` will create the cache directory under the node_modules directory.
  config.module.rules[0].query.cacheDirectory = findCacheDir({
    name: 'react-storybook',
  });

  const defaultConfig = createDefaultWebpackConfig(config);

  // Check whether user has a custom webpack config file and
  // return the (extended) base configuration if it's not available.
  const customConfigPath = path.resolve(configDir, 'webpack.config.js');
  if (!fs.existsSync(customConfigPath)) {
    logger.info('=> Using default webpack setup based on "Create React App".');
    return defaultConfig;
  }

  const customConfig = require(customConfigPath); // eslint-disable-line

  if (typeof customConfig === 'function') {
    logger.info('=> Loading custom webpack config (full-control mode).');
    return customConfig(config, configType, defaultConfig, configDir);
  }

  logger.info('=> Loading custom webpack config.');

  customConfig.module = customConfig.module || {};

  return {
    ...customConfig,
    // We'll always load our configurations after the custom config.
    // So, we'll always load the stuff we need.
    ...config,
    // We need to use our and custom plugins.
    plugins: [...config.plugins, ...(customConfig.plugins || [])],
    module: {
      ...config.module,
      // We need to use our and custom rules.
      ...customConfig.module,
      rules: [...config.module.rules, ...(customConfig.module.rules || [])],
    },
  };
}
<|endoftext|>


<commit_before>Lizard.Overview = {};

Lizard.Overview.DefaultLayout = Backbone.Marionette.Layout.extend({
  template: '#overview-template',
  regions: {
    'sidebarRegion': '#sidebarRegion',
    'dashboardRegion': '#dashboardRegion'
  }
});

Lizard.Overview.Router = Backbone.Marionette.AppRouter.extend({
    appRoutes: {
      'overview': 'overview'
    }
});

Lizard.Overview.DashboardView = Backbone.Marionette.ItemView.extend({
  template: '#dashboard-template',
  initialize: function(){
    console.log('DashboardView.initialize()');
  },
  onDomRefresh: function() {
    // Best moment to initialize Leaflet and other DOM-dependent stuff
    console.log('onDomRefresh()');

        var gridster = $('.gridster ul').gridster({
            widget_margins: [10, 10],
            widget_base_dimensions: [140, 140],
            draggable: {
              stop: function(event, ui) {
                console.log('Syncing dashboard: ', gridster.serialize());
                $('.top-right').notify({
                    message: {
                      text: 'Saving your dashboard layout!'
                    }
                  }).show();
              }
            }
        }).data('gridster');

        gridster.add_widget(
          '
' +
          '

' +
          '
',
          2,
          2,
          1,
          1
        );

        gridster.add_widget(
          '
' +
          '

' +
          '
',
          2,
          2,
          1,
          3
        );

        gridster.add_widget(
          '
' +
          '

' +
          '
',
          2,
          2,
          3,
          1
        );

        var g1 = new JustGage({
          id: "g1",
          value: getRandomInt(650, 980),
          min: 350,
          max: 980,
          title: "Amstel",
          label: "Verplaatsing (m3/s)"
        });

        var g2 = new JustGage({
          id: "g2",
          value: 70,
          min: 0,
          max: 100,
          title: "Amstel 4-2-21",
          label: "Waterstand (NAP)"
        });

        var g3 = new JustGage({
          id: "g3",
          value: 80,
          min: 0,
          max: 100,
          title: "Amstel 4-2-20",
          label: "Waterstand (NAP)"
        });

        setInterval(function() {
          g1.refresh(getRandomInt(350, 980));
          g2.refresh(getRandomInt(80, 90));
          g3.refresh(getRandomInt(80, 90));
        }, 2500);

  }
});

Lizard.Overview.overview = function(){
  console.log('Lizard.Overview.overview()');

  // Instantiate Overview's default layout
  var overviewView = new Lizard.Overview.DefaultLayout();
  Lizard.App.content.show(overviewView);

  var dashboardView = new Lizard.Overview.DashboardView();

  overviewView.dashboardRegion.show(dashboardView.render());
  Backbone.history.navigate('overview');
};

Lizard.App.addInitializer(function(){
  Lizard.Overview.router = new Lizard.Overview.Router({
    controller: Lizard.Overview
  });

  Lizard.App.vent.trigger('routing:started');
});

<commit_msg>Removing dashboardview<commit_after>Lizard.Overview = {};

Lizard.Overview.DefaultLayout = Backbone.Marionette.Layout.extend({
  template: '#overview-template',
  regions: {
    'sidebarRegion': '#sidebarRegion',
    'dashboardRegion': '#dashboardRegion'
  }
});

Lizard.Overview.Router = Backbone.Marionette.AppRouter.extend({
    appRoutes: {
      'overview': 'overview'
    }
});

Lizard.Overview.overview = function(){
  console.log('Lizard.Overview.overview()');

  // Instantiate Overview's default layout
  var overviewView = new Lizard.Overview.DefaultLayout();
  Lizard.App.content.show(overviewView);

  overviewView.dashboardRegion.show(widgetcollectionview.render());
  Backbone.history.navigate('overview');
};

Lizard.App.addInitializer(function(){
  Lizard.Overview.router = new Lizard.Overview.Router({
    controller: Lizard.Overview
  });

  Lizard.App.vent.trigger('routing:started');
});

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import classnames from 'classnames'
import Modernizr from 'modernizr'

import * as Paths from './../Paths'

import {
  exportDataClipByEndpoint,
  mountExportDataclip
} from './../actions/ExportActions'

import {
  Loading,
  CloseButton
} from './../components'

import { Menu as FormWidgetMenu } from './../Widget/plugins/Form/components'
import { Menu as DonationWidgetMenu } from '../Widget/plugins/Donation/components/settings'

class ExportWidgetData extends React.Component {
  static propTypes = {
    params: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    exportDataClipByEndpoint: PropTypes.func.isRequired,
    mountExportDataclip: PropTypes.func.isRequired,
    exported: PropTypes.bool,
    success: PropTypes.bool,
    error: PropTypes.object
  }

  componentDidMount() {
    this.props.mountExportDataclip()
  }

  widget (props = this.props) {
    const { widgets, params: { widget_id } } = props
    const idStringify = widget => widget.id.toString()
    const currentWidgetIndex = widgets.data.map(idStringify).indexOf(widget_id)
    return widgets.data[currentWidgetIndex]
  }

  fixzero(value) {
    let valueToString = value.toString()
    return valueToString.length === 1 ? '0' + valueToString : valueToString
  }

  formatExportAt(widget) {
    let datetime = new Date(String(widget.exported_at))
    const date = this.fixzero(datetime.getDate()) + '/' + this.fixzero(datetime.getMonth()) + '/' + datetime.getFullYear()
    const time = this.fixzero(datetime.getHours()) + ':' + this.fixzero(datetime.getMinutes())
    return date + ' às ' + time
  }

  renderLoadingMessage() {
    return

      Aguarde enquanto estamos processando...

  }

  renderExportedMessage(widget = this.widget()) {
    return
      Última exportação: {this.formatExportAt(widget)}.

  }

  renderErrorMessage() {
    return {error}
  }

  renderDisclaimer() {
    return

           Atenção

        Você está utilizando o navegador Safari. Os passos a seguir são
        necessários devido a uma incompatibilidade.

          Clique com o botão direito do mouse no botão abaixo e selecione
          a opção "Transferir Arquivo Vinculado Como..."

          Salve o arquivo com o nome desejado e a extensão .xlsx

  }

  renderSaveAsContainer() {
    const { loading } = this.props
    return

    return

        Salvar planilha

  }

  renderPage() {
    const {
      mobilization,
      loading,
      error,
      exported,
      success,
      exportDataClipByEndpoint,
      params,
      auth: { credentials }
    } = this.props

    const widget = this.widget()
    const filename = mobilization.name + '.xlsx'

    return (

        {( widget.kind === 'donation'
          ? <DonationWidgetMenu {...this.props} widget={widget} />
          : <FormWidgetMenu {...this.props} widget={widget} />
        )}

            Exportar

            Clique no botão abaixo para baixar o relatório completo do
            formulário em formato excel.

            <button
              disabled={loading}
              className='button bg-aqua caps p2'
              onClick={() => exportDataClipByEndpoint(
                {
                  mobilization_id: mobilization.id,
                  widget_id: widget.id,
                  filename,
                  credentials
                }
              )}>
              {Modernizr.adownload
                ? 'Clique para baixar a planilha completa.'
                : 'Clique para processar a planilha completa.'
              }
            </button>

            {(loading ? this.renderLoadingMessage() : null)}
            {(widget.exported_at && !loading ? this.renderExportedMessage() : null)}
            {(error ? this.renderErrorMessage() : null)}

          {(!Modernizr.adownload && !loading && success ? this.renderDisclaimer() : null)}
          {(!Modernizr.adownload ? this.renderSaveAsContainer() : null)}

        <CloseButton path={ Paths.editMobilization(mobilization.id) } />

    )
  }

  renderLoading() {
    return <Loading />
  }

  render () {
    const { widgets: { data } } = this.props
    return (data.length ? this.renderPage() : this.renderLoading())
  }
}

const mapStateToProps = (globalState) => {
  return {
    loading: globalState.exportDataClip.loading,
    error: globalState.exportDataClip.error,
    success: globalState.exportDataClip.success
  }
}

const mapActionCreators = {
  exportDataClipByEndpoint,
  mountExportDataclip
}

export default connect(mapStateToProps, mapActionCreators)(ExportWidgetData)
<commit_msg>Fix ExportWidgetData page layout. #184<commit_after>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import classnames from 'classnames'
import Modernizr from 'modernizr'

import * as Paths from '../Paths'

import {
  exportDataClipByEndpoint,
  mountExportDataclip
} from '../actions/ExportActions'

import {
  Loading,
  CloseButton
} from '../components'

import { Menu as FormWidgetMenu } from './../Widget/plugins/Form/components'
import { Menu as DonationWidgetMenu } from '../Widget/plugins/Donation/components/settings'

class ExportWidgetData extends React.Component {
  static propTypes = {
    params: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    exportDataClipByEndpoint: PropTypes.func.isRequired,
    mountExportDataclip: PropTypes.func.isRequired,
    exported: PropTypes.bool,
    success: PropTypes.bool,
    error: PropTypes.object
  }

  componentDidMount() {
    this.props.mountExportDataclip()
  }

  widget (props = this.props) {
    const { widgets, params: { widget_id } } = props
    const idStringify = widget => widget.id.toString()
    const currentWidgetIndex = widgets.data.map(idStringify).indexOf(widget_id)
    return widgets.data[currentWidgetIndex]
  }

  fixzero(value) {
    let valueToString = value.toString()
    return valueToString.length === 1 ? '0' + valueToString : valueToString
  }

  formatExportAt(widget) {
    let datetime = new Date(String(widget.exported_at))
    const date = this.fixzero(datetime.getDate()) + '/' + this.fixzero(datetime.getMonth()) + '/' + datetime.getFullYear()
    const time = this.fixzero(datetime.getHours()) + ':' + this.fixzero(datetime.getMinutes())
    return date + ' às ' + time
  }

  renderLoadingMessage() {
    return

      Aguarde enquanto estamos processando...

  }

  renderExportedMessage(widget = this.widget()) {
    return
      Última exportação: {this.formatExportAt(widget)}.

  }

  renderErrorMessage() {
    return {error}
  }

  renderDisclaimer() {
    return

           Atenção

        Você está utilizando o navegador Safari. Os passos a seguir são
        necessários devido a uma incompatibilidade.

          Clique com o botão direito do mouse no botão abaixo e selecione
          a opção "Transferir Arquivo Vinculado Como..."

          Salve o arquivo com o nome desejado e a extensão .xlsx

  }

  renderSaveAsContainer() {
    const { loading } = this.props
    return

    return

        Salvar planilha

  }

  renderPage() {
    const {
      mobilization,
      loading,
      error,
      exported,
      success,
      exportDataClipByEndpoint,
      params,
      auth: { credentials }
    } = this.props

    const widget = this.widget()
    const filename = mobilization.name + '.xlsx'

    return (

        {( widget.kind === 'donation'
          ? <DonationWidgetMenu {...this.props} widget={widget} />
          : <FormWidgetMenu {...this.props} widget={widget} />
        )}

            Exportar

            Clique no botão abaixo para baixar o relatório completo do
            formulário em formato excel.

            <button
              disabled={loading}
              className='btn bg-pagenta white caps p2 rounded'
              onClick={() => exportDataClipByEndpoint(
                {
                  mobilization_id: mobilization.id,
                  widget_id: widget.id,
                  filename,
                  credentials
                }
              )}>
              {Modernizr.adownload
                ? 'Clique para baixar a planilha completa.'
                : 'Clique para processar a planilha completa.'
              }
            </button>

            {(loading ? this.renderLoadingMessage() : null)}
            {(widget.exported_at && !loading ? this.renderExportedMessage() : null)}
            {(error ? this.renderErrorMessage() : null)}

          {(!Modernizr.adownload && !loading && success ? this.renderDisclaimer() : null)}
          {(!Modernizr.adownload ? this.renderSaveAsContainer() : null)}

        <CloseButton path={ Paths.editMobilization(mobilization.id) } />

    )
  }

  renderLoading() {
    return <Loading />
  }

  render () {
    const { widgets: { data } } = this.props
    return (data.length ? this.renderPage() : this.renderLoading())
  }
}

const mapStateToProps = (globalState) => {
  return {
    loading: globalState.exportDataClip.loading,
    error: globalState.exportDataClip.error,
    success: globalState.exportDataClip.success
  }
}

const mapActionCreators = {
  exportDataClipByEndpoint,
  mountExportDataclip
}

export default connect(mapStateToProps, mapActionCreators)(ExportWidgetData)
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name groongaAdminApp.service:schemaLoader
 * @description
 * # schemaLoader
 * Groonga database schema loader.
 */
angular.module('groongaAdminApp')
  .factory('schemaLoader', [
    '$q', '$http', '$timeout',
    function ($q, $http, $timeout) {
      var fetching = false;
      var waitingDeferes = [];
      var fetched = false;
      var schema = {
        tables: {}
      };
      var client = new GroongaClient($http);

      function isTextType(typeName) {
        switch (typeName) {
        case 'ShortText':
        case 'Text':
        case 'LongText':
          return true;
        default:
          return false;
        }
      }

      function isReferenceType(typeName) {
        return typeName in schema.tables;
      }

      function resolveTable(table) {
        table.keyType = {
          name: table.domain,
          isTextType: isTextType(table.domain)
        };
      }

      function resolveTables() {
        angular.forEach(schema.tables, function(table) {
          resolveTable(table);
        });
      }

      function resolveColumn(column) {
        column.valueType = {
          name: column.range,
          isTextType: isTextType(column.range),
          isReferenceType: isReferenceType(column.range)
        };
      }

      function resolveColumns() {
        angular.forEach(schema.tables, function(table) {
          angular.forEach(table.columns, function(column) {
            resolveColumn(column);
          });
        });
      }

      function resolveIndex(column) {
        var table = schema.tables[column.range];
        column.sources.forEach(function(source) {
          var columnName;
          if (source.indexOf('.') === -1) {
            columnName = '_key';
          } else {
            columnName = source.split('.')[1];
          }
          var targetColumn = table.columns[columnName];
          targetColumn.indexes.push(column);
        });
      }

      function resolveIndexes() {
        angular.forEach(schema.tables, function(table) {
          angular.forEach(table.columns, function(column) {
            if (column.isIndex) {
              resolveIndex(column);
            }
          });
        });
      }

      function addColumn(table, column) {
        column.table = table;
        column.indexes = [];
        table.columns[column.name] = column;
      }

      function fetchColumns(table) {
        table.columns = {};

        addColumn(table, {
          name: '_id',
          range: 'UInt32'
        });

        return client.execute('column_list', {table: table.name})
          .success(function(response) {
            var columns = response.columns();

            columns.forEach(function(column) {
              addColumn(table, column);
            });
          });
      }

      function fetchTables() {
        return client.execute('table_list')
          .success(function(response) {
            response.tables().forEach(function(table) {
              schema.tables[table.name] = table;
            });
            resolveTables();

            var fetchColumnsTasks = [];
            angular.forEach(schema.tables, function(table) {
              fetchColumnsTasks.push(fetchColumns(table));
            });

            return $q.all(fetchColumnsTasks)
              .then(function() {
                resolveColumns();
                resolveIndexes();
                fetched = true;
                fetching = false;
                waitingDeferes.forEach(function(defer) {
                  defer.resolve(schema);
                });
                waitingDeferes = [];
                return schema;
              });
          });
      }

      return function() {
        if (fetching) {
          var defer = $q.defer();
          waitingDeferes.push(defer);
          return defer.promise;
        } else if (fetched) {
          var defer = $q.defer();
          $timeout(function() {
            defer.resolve(schema);
          });
          return defer.promise;
        } else {
          fetching = true
          return fetchTables();
        }
      };
    }]);
<commit_msg>Remove duplicated variable declarations<commit_after>'use strict';

/**
 * @ngdoc function
 * @name groongaAdminApp.service:schemaLoader
 * @description
 * # schemaLoader
 * Groonga database schema loader.
 */
angular.module('groongaAdminApp')
  .factory('schemaLoader', [
    '$q', '$http', '$timeout',
    function ($q, $http, $timeout) {
      var fetching = false;
      var waitingDeferes = [];
      var fetched = false;
      var schema = {
        tables: {}
      };
      var client = new GroongaClient($http);

      function isTextType(typeName) {
        switch (typeName) {
        case 'ShortText':
        case 'Text':
        case 'LongText':
          return true;
        default:
          return false;
        }
      }

      function isReferenceType(typeName) {
        return typeName in schema.tables;
      }

      function resolveTable(table) {
        table.keyType = {
          name: table.domain,
          isTextType: isTextType(table.domain)
        };
      }

      function resolveTables() {
        angular.forEach(schema.tables, function(table) {
          resolveTable(table);
        });
      }

      function resolveColumn(column) {
        column.valueType = {
          name: column.range,
          isTextType: isTextType(column.range),
          isReferenceType: isReferenceType(column.range)
        };
      }

      function resolveColumns() {
        angular.forEach(schema.tables, function(table) {
          angular.forEach(table.columns, function(column) {
            resolveColumn(column);
          });
        });
      }

      function resolveIndex(column) {
        var table = schema.tables[column.range];
        column.sources.forEach(function(source) {
          var columnName;
          if (source.indexOf('.') === -1) {
            columnName = '_key';
          } else {
            columnName = source.split('.')[1];
          }
          var targetColumn = table.columns[columnName];
          targetColumn.indexes.push(column);
        });
      }

      function resolveIndexes() {
        angular.forEach(schema.tables, function(table) {
          angular.forEach(table.columns, function(column) {
            if (column.isIndex) {
              resolveIndex(column);
            }
          });
        });
      }

      function addColumn(table, column) {
        column.table = table;
        column.indexes = [];
        table.columns[column.name] = column;
      }

      function fetchColumns(table) {
        table.columns = {};

        addColumn(table, {
          name: '_id',
          range: 'UInt32'
        });

        return client.execute('column_list', {table: table.name})
          .success(function(response) {
            var columns = response.columns();

            columns.forEach(function(column) {
              addColumn(table, column);
            });
          });
      }

      function fetchTables() {
        return client.execute('table_list')
          .success(function(response) {
            response.tables().forEach(function(table) {
              schema.tables[table.name] = table;
            });
            resolveTables();

            var fetchColumnsTasks = [];
            angular.forEach(schema.tables, function(table) {
              fetchColumnsTasks.push(fetchColumns(table));
            });

            return $q.all(fetchColumnsTasks)
              .then(function() {
                resolveColumns();
                resolveIndexes();
                fetched = true;
                fetching = false;
                waitingDeferes.forEach(function(defer) {
                  defer.resolve(schema);
                });
                waitingDeferes = [];
                return schema;
              });
          });
      }

      return function() {
        var defer;
        if (fetching) {
          defer = $q.defer();
          waitingDeferes.push(defer);
          return defer.promise;
        } else if (fetched) {
          defer = $q.defer();
          $timeout(function() {
            defer.resolve(schema);
          });
          return defer.promise;
        } else {
          fetching = true
          return fetchTables();
        }
      };
    }]);
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var _ = require('lodash');
var yeoman = require('yeoman-generator');
var spawn = require('cross-spawn');

module.exports = yeoman.generators.Base.extend({

    upgrade: function() {
        var me = this;

        // 从 package.json 中取回脚手架初始化项目时指定的一些变量
        var pkg = JSON.parse(me.readFileAsString('package.json'));
        var authorName = pkg.author.name;
        var componentName = _.capitalize(_.camelCase(pkg.name))
            .replace(/Tingle/, '').replace(/^Dd/, 'DD').replace(/^Nw/, 'NW');

        // gulpfile 和 gitignore 更新
        me.bulkCopy('_gitignore', '.gitignore');
        me.bulkCopy('gulpfile.js', 'gulpfile.js');

        // 依赖更新
        pkg.dependencies = {
            'classnames': '^2.1.2',
            'fastclick': '^1.0.6',
            'react': '^0.13.3',
            'tingle-context': '~0.1.0',
            'tingle-style': '~0.0.2',
            'zepto': '0.0.4'
        };
        pkg.devDependencies = {
            'babel-core': '^5.8.19',
            'babel-loader': '^5.3.2',
            'gulp': '^3.9.0',
            'tingle-dev-tools': 'latest'
        };
        me.writeFileFromString(JSON.stringify(pkg, null, '  '), 'package.json');

        // DEMO 样式文件路径变更
        var html = me.readFileAsString('index.html');
        if (html.indexOf('./demo/' + componentName + 'Demo.css') !== -1) {
            html = html.replace('./demo/' + componentName + 'Demo.css', './dist/demo.css');
            me.writeFileFromString(html, 'index.html');
        }

        // 增加 svg 文件目录
        me.mkdir('src/svg/tingle');
        me.mkdir('src/svg/custom');

        // 没有版权声明的增加版权声明
        me.expandFiles('src/*.js').forEach(function(file) {
            var content = me.readFileAsString(file);
            if (content.indexOf('/**') && content.indexOf('/*!')) {
                content = [
                    '/**',
                    ' * ' + componentName + ' Component for tingle',
                    ' * @author ' + authorName,
                    ' *',
                    ' * Copyright 2014-2015, Tingle Team, Alinw.',
                    ' * All rights reserved.',
                    ' */',
                    ''
                ].join('\n') + content;
                me.writeFileFromString(content, file);
            }
        });
        me.expandFiles('src/*.styl').forEach(function(file) {
            var content = me.readFileAsString(file);
            if (content.indexOf('/**') && content.indexOf('/*!')) {
                content = [
                    '/**',
                    ' * ' + componentName + ' Component Style for tingle',
                    ' * @author ' + authorName,
                    ' *',
                    ' * Copyright 2014-2015, Tingle Team, Alinw.',
                    ' * All rights reserved.',
                    ' */',
                    ''
                ].join('\n') + content;
                me.writeFileFromString(content, file);
            }
        });
    },

    install: function() {
        var me = this;
        var done = me.async();
        var args = [
            'install',
            '-d'
        ];
        var opts = {
            stdio: 'inherit'
        };
        spawn('tnpm', args, opts).on('error', function() {
            spawn('npm', args, opts).on('exit', done);
        }).on('exit', done);
    }
});<commit_msg>fix #14<commit_after>'use strict';
var path = require('path');
var _ = require('lodash');
var yeoman = require('yeoman-generator');
var spawn = require('cross-spawn');

module.exports = yeoman.generators.Base.extend({

    upgrade: function() {
        var me = this;

        // 从 package.json 中取回脚手架初始化项目时指定的一些变量
        var pkg = JSON.parse(me.readFileAsString('package.json'));
        var authorName = pkg.author.name;
        var componentName = _.capitalize(_.camelCase(pkg.name))
            .replace(/Tingle/, '').replace(/^Dd/, 'DD').replace(/^Nw/, 'NW');

        // gulpfile 和 gitignore 更新
        me.bulkCopy('_gitignore', '.gitignore');
        me.bulkCopy('gulpfile.js', 'gulpfile.js');

        // 依赖更新
        pkg.dependencies = {
            'tingle-context': '~0.1.0',
            'tingle-style': '~0.0.1',
            'classnames': '^2.1.2'
        };
        pkg.devDependencies = {
            'babel-core': '^5.8.19',
            'babel-loader': '^5.3.2',
            'gulp': '^3.9.0',
            'tingle-dev-tools': 'latest',
            'react': '^0.13.3',
            'zepto': '0.0.4',
            'fastclick': '^1.0.6'
        };
        me.writeFileFromString(JSON.stringify(pkg, null, '  '), 'package.json');

        // DEMO 样式文件路径变更
        var html = me.readFileAsString('index.html');
        if (html.indexOf('./demo/' + componentName + 'Demo.css') !== -1) {
            html = html.replace('./demo/' + componentName + 'Demo.css', './dist/demo.css');
            me.writeFileFromString(html, 'index.html');
        }

        // 增加 svg 文件目录
        me.mkdir('src/svg/tingle');
        me.mkdir('src/svg/custom');

        // 没有版权声明的增加版权声明
        me.expandFiles('src/*.js').forEach(function(file) {
            var content = me.readFileAsString(file);
            if (content.indexOf('/**') && content.indexOf('/*!')) {
                content = [
                    '/**',
                    ' * ' + componentName + ' Component for tingle',
                    ' * @author ' + authorName,
                    ' *',
                    ' * Copyright 2014-2015, Tingle Team, Alinw.',
                    ' * All rights reserved.',
                    ' */',
                    ''
                ].join('\n') + content;
                me.writeFileFromString(content, file);
            }
        });
        me.expandFiles('src/*.styl').forEach(function(file) {
            var content = me.readFileAsString(file);
            if (content.indexOf('/**') && content.indexOf('/*!')) {
                content = [
                    '/**',
                    ' * ' + componentName + ' Component Style for tingle',
                    ' * @author ' + authorName,
                    ' *',
                    ' * Copyright 2014-2015, Tingle Team, Alinw.',
                    ' * All rights reserved.',
                    ' */',
                    ''
                ].join('\n') + content;
                me.writeFileFromString(content, file);
            }
        });
    },

    install: function() {
        var me = this;
        var done = me.async();
        var args = [
            'install',
            '-d'
        ];
        var opts = {
            stdio: 'inherit'
        };
        spawn('tnpm', args, opts).on('error', function() {
            spawn('npm', args, opts).on('exit', done);
        }).on('exit', done);
    }
});
<|endoftext|>


<commit_before>/** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";

import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes";
import store from "./.store";
import { StyleRoot } from "radium";

// Make sure that webpack considers new dependencies introduced in the Index
// file
import "../../Index.js";

export default class Entry extends Component {
  static defaultProps = {
    store: store()
  };

  render () {
    const {
      routerContext,
      radiumConfig,
      store
    } = this.props;

    return (
      <StyleRoot radiumConfig={radiumConfig}>
        <Root routerContext={routerContext} routes={routes} store={store} />
      </StyleRoot>
    );
  }
}

Entry.start = function () {
  match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => {
    render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main"));
  });
};

<commit_msg>Move Index import to the top to fix css order issue<commit_after>/** DO NOT MODIFY **/
import React, { Component } from "react";
import { render } from "react-dom";

// Make sure that webpack considers new dependencies introduced in the Index
// file
import "../../Index.js";

import { Root } from "gluestick-shared";
import { match } from "react-router";
import routes from "./routes";
import store from "./.store";
import { StyleRoot } from "radium";

export default class Entry extends Component {
  static defaultProps = {
    store: store()
  };

  render () {
    const {
      routerContext,
      radiumConfig,
      store
    } = this.props;

    return (
      <StyleRoot radiumConfig={radiumConfig}>
        <Root routerContext={routerContext} routes={routes} store={store} />
      </StyleRoot>
    );
  }
}

Entry.start = function () {
  match({routes, location: window.location.pathname}, (error, redirectLocation, renderProps) => {
    render(<Entry radiumConfig={{userAgent: window.navigator.userAgent}} {...renderProps} />, document.getElementById("main"));
  });
};

<|endoftext|>


<commit_before>var _ = require('../lib/underscore'),
    db = require('../db'),
    expat = require('node-expat'),
    request = require('request');

var RADIO_IDENT = {auth: 'Radio'};
var RADIO_MOUNT = '/radio';
var POLL_URL = 'http://localhost:5555/poll.xsl';
var SHORT_INTERVAL = 3 * 1000;
var LONG_INTERVAL = 30 * 1000;

function update_banner(info, cb) {
	var yaku = new db.Yakusoku(info.board, RADIO_IDENT);
	yaku.set_banner(info.op, info.message, function (err, res) {
		yaku.disconnect();
		cb(err, res);
	});
}

function monitor(last) {
	poll(POLL_URL, function (err, mounts) {
		var info;
		if (err)
			console.error(err);
		else
			info = format_now_playing(mounts);
		var interval = SHORT_INTERVAL;
		if (!info && last) {
			// stopped playing, clear
			info = last;
			info.message = '';
			last = null;
			interval = LONG_INTERVAL;
		}
		if (!info || _.isEqual(info, last)) {
			if (!info)
				interval = LONG_INTERVAL;
			setTimeout(monitor.bind(null, last), interval);
		}
		else {
			update_banner(info, function (err, cb) {
				if (err) {
					console.error(err);
					interval = LONG_INTERVAL;
				}
				setTimeout(monitor.bind(null, info), interval);
			});
		}
	});
}

function poll(url, cb) {
	request.get(url, function (err, resp, body) {
		if (err)
			return cb(err);
		if (resp.statusCode != 200)
			return console.error("Got " + resp.statusCode);
		parse(body, function (err, mounts) {
			if (err)
				cb(err);
			else
				cb(null, mounts);
		});
	});
}

function format_now_playing(mounts) {
	var radio = mounts[RADIO_MOUNT];
	if (!radio || !radio.url)
		return null;
	var m = radio.url.match(/\/(\w+)\/(\d+)/);
	if (!m)
		return null;
	var board = m[1];
	if (!db.is_board(board))
		return;
	var op = parseInt(m[2], 10);
	if (!op)
		return;
	var count = parseInt(radio.listeners, 10);
	count = count + ' listener' + (count == 1 ? '' : 's');
	var msg = count + (radio.title ? (': ' + radio.title) : '');
	return {board: board, op: op, message: msg};
}

function parse(input, cb) {
	var mounts = {}, curMount, thisKey, thisVal;
	var parser = new expat.Parser('UTF-8');
	parser.on('startElement', function (name, data) {
		if (name == 'mount') {
			curMount = {};
			return;
		}
		if (curMount) {
			thisKey = name;
			thisVal = [];
		}
	});
	parser.on('text', function (val) {
		if (thisKey)
			thisVal.push(val);
	});
	parser.on('endElement', function (name) {
		if (thisKey) {
			if (name != thisKey)
				console.error("Unmatched or nested?!");
			curMount[thisKey] = thisVal.join('').trim();
			thisKey = thisVal = null;
		}
		else if (name == 'mount') {
			if (curMount.point)
				mounts[curMount.point] = curMount;
			else
				console.warn("Unknown mount", curMount);
			curMount = null;
		}
		else if (name == 'mounts') {
			parser.removeAllListeners();
			cb(null, mounts);
		}
	});
	parser.on('error', cb);
	parser.parse(input);
}

if (require.main === module) {
	var args = process.argv;
	if (args.length == 2)
		monitor();
	else if (args.length == 5) {
		var op = parseInt(args[3], 10);
		var info = {board: args[2], op: op, message: args[4]};
		update_banner(info, function (err) {
			if (err)
				console.error(err);
			process.exit(err ? -1 : 0);
		});
	}
}
<commit_msg>Fix continuous reset banner messages<commit_after>var _ = require('../lib/underscore'),
    db = require('../db'),
    expat = require('node-expat'),
    request = require('request');

var RADIO_IDENT = {auth: 'Radio'};
var RADIO_MOUNT = '/radio';
var POLL_URL = 'http://localhost:5555/poll.xsl';
var SHORT_INTERVAL = 3 * 1000;
var LONG_INTERVAL = 30 * 1000;

function update_banner(info, cb) {
	var yaku = new db.Yakusoku(info.board, RADIO_IDENT);
	yaku.set_banner(info.op, info.message, function (err, res) {
		yaku.disconnect();
		cb(err, res);
	});
}

function monitor(last) {
	poll(POLL_URL, function (err, mounts) {
		var info, clear = false;
		if (err)
			console.error(err);
		else
			info = format_now_playing(mounts);
		var interval = SHORT_INTERVAL;
		if (!info && last) {
			clear = true;
			info = last;
			info.message = '';
			interval = LONG_INTERVAL;
		}
		var sameAsLast = _.isEqual(info, last);
		if (!clear && (!info || sameAsLast)) {
			if (!info)
				interval = LONG_INTERVAL;
			setTimeout(monitor.bind(null, last), interval);
		}
		else {
			update_banner(info, function (err, cb) {
				if (err) {
					console.error(err);
					interval = LONG_INTERVAL;
				}
				if (clear)
					info = null;
				setTimeout(monitor.bind(null, info), interval);
			});
		}
	});
}

function poll(url, cb) {
	request.get(url, function (err, resp, body) {
		if (err)
			return cb(err);
		if (resp.statusCode != 200)
			return console.error("Got " + resp.statusCode);
		parse(body, function (err, mounts) {
			if (err)
				cb(err);
			else
				cb(null, mounts);
		});
	});
}

function format_now_playing(mounts) {
	var radio = mounts[RADIO_MOUNT];
	if (!radio || !radio.url)
		return null;
	var m = radio.url.match(/\/(\w+)\/(\d+)/);
	if (!m)
		return null;
	var board = m[1];
	if (!db.is_board(board))
		return;
	var op = parseInt(m[2], 10);
	if (!op)
		return;
	var count = parseInt(radio.listeners, 10);
	count = count + ' listener' + (count == 1 ? '' : 's');
	var msg = count + (radio.title ? (': ' + radio.title) : '');
	return {board: board, op: op, message: msg};
}

function parse(input, cb) {
	var mounts = {}, curMount, thisKey, thisVal;
	var parser = new expat.Parser('UTF-8');
	parser.on('startElement', function (name, data) {
		if (name == 'mount') {
			curMount = {};
			return;
		}
		if (curMount) {
			thisKey = name;
			thisVal = [];
		}
	});
	parser.on('text', function (val) {
		if (thisKey)
			thisVal.push(val);
	});
	parser.on('endElement', function (name) {
		if (thisKey) {
			if (name != thisKey)
				console.error("Unmatched or nested?!");
			curMount[thisKey] = thisVal.join('').trim();
			thisKey = thisVal = null;
		}
		else if (name == 'mount') {
			if (curMount.point)
				mounts[curMount.point] = curMount;
			else
				console.warn("Unknown mount", curMount);
			curMount = null;
		}
		else if (name == 'mounts') {
			parser.removeAllListeners();
			cb(null, mounts);
		}
	});
	parser.on('error', cb);
	parser.parse(input);
}

if (require.main === module) {
	var args = process.argv;
	if (args.length == 2)
		monitor();
	else if (args.length == 5) {
		var op = parseInt(args[3], 10);
		var info = {board: args[2], op: op, message: args[4]};
		update_banner(info, function (err) {
			if (err)
				console.error(err);
			process.exit(err ? -1 : 0);
		});
	}
}
<|endoftext|>


<commit_before>if(typeof sb.swf =='undefined'){
	sb.include('swf');
}
/*
@Name: sb.upload_button
@Description: Instantiates a new upload
@Example:
var uploader = new sb.upload_button({
	debug : true,
	maxFiles : 5,
	maxFileSizeK : 5000000,
	url : 'http://frameworkdev.sv/uploads/test',
	data : {
		friend : 'tim',
		nano : "Hello there timmy's dog"
	},
	onReturnData : function(file){
		sb.objects.alert(file);
	},
	onExceedsMaxFiles : function(){},
	onExceedsMaxFileSizeK : function(file){},
	onError : function(data){
		alert(data.message);
	},
	styles : {
		backgroundColor : '0x00FF00',
		backgroundColorRoll : '0xFFFF00',
		borderColor : '0xFF0000',
		color : '0xFF0000',
		cornerRadius : '15',
		borderThickness : '0',
		fontSize : 16,
		width : 62,
		height : 24,
		fontSize : 16,
		font : 'Tahoma'
	}
});
uploader.embed('#chicken');
*/

sb.upload_button = function(parameters){

	this.id = sb.upload_button.uploads.length;

	for(var prop in parameters){
		this[prop] = parameters[prop];
	}

	sb.upload_button.uploads.push(this);

	//create swf and associate call to thei sb.upload_button for event handling

	this.swf = new sb.swf({
		src : sb.base+"/UploadButton.swf?id="+this.id,
		width : this.styles.width || 62,
		height : this.styles.height || 24,
		id : 'upload'+this.id,
		bgcolor : '#000000',
		wmode: 'transparent',
		flashvars : {
			debug : (this.debug != null) ? this.debug : true,
			innerHTML : this.innerHTML || 'upload'
		},
		version : 9,
		alt : '
You need at least flashplayer 9+ to upload
'
	});

	this.load_params = function(){

		this.swf.getInterface().create_upload(this.id);

	};
};

/**
@Name: sb.upload_button.uploads
@Description: Used Internally
*/
sb.upload_button.uploads = [];

sb.upload_button.prototype = {
	styles : {},

	/**
	 * Returns the HTML of the swf for testing
	 */
	toHTML : function(){
		return this.swf.toHTML();
	},

	/**
	 * Embeds the button into another element
	 */
	embed : function(el){
		this.swf.embed(el);
	},

	/**
	@Name: sb.upload_button.prototype.setStyles
	@Description: Sets the MXML CSS styles for the button
	@Param: styles Object Hash of css properties
	@Example:
		this.setStyles(
			letterSpacing : '20'
		);
	*/
	setStyles : function(styles){
		this.swf.getInterface().set_button_styles(styles);
	},

	/**
	@Name: sb.upload_button.prototype.cancels
	@Description: Cancels all file uploads for this instance
	@Name: string name optionally cancels only for files that match the file name given
	*/
	cancel : function(name){
		name = name || '';
		this.swf.getInterface().upload_cancel(name);
	},

	/**
	@Name: sb.upload_button.prototype.id
	@Description: Used Internally
	*/
	id: 0,

	/**
	@Name: sb.upload_button.prototype.maxFiles
	@Description: The maximum number of files the user can select in the browser before it throws an error and fires onMaxFilesExceeded
	*/
	maxFiles : 5,

	/**
	@Name: sb.upload_button.prototype.maxFileSizeK
	@Description: The maximum file size per file that the user can upload before it throws an error and fires onMaxFileSizeExceeded
	*/
	maxFileSizeK : 1024,

	/**
	@Name: sb.upload_button.prototype.acceptedFileTypes
	@Description: The file types to accept for upload
	*/
	acceptedFileTypes : '*.*',

	/**
	@Name: sb.upload_button.prototype.method
	@Description: The default method to send data
	*/
	method : 'post',

	/**
	@Name: sb.upload_button.prototype.url
	@Description: The URL to upload the data to
	*/
	url : '',

	/**
	@Name: sb.upload_button.prototype.data
	@Description: Additional data objectw hich is url encoded into post data and sent with the files
	*/
	data : {},

	/**
	@Name: sb.upload_button.prototype.debug
	@Description: Determines if file upload debug info is traced to the flash debug player
	*/
	debug : true,

	/**
	@Name: sb.upload_button.prototype.onSelect
	@Description: Fires when the user selects files from the browse box that pops up when you begin an upload
	@Param: object files.total
	*/
	onSelect : function(files){},

	/**
	@Name: sb.upload_button.prototype.onExceedsMaxFileSizeK
	@Description: Fires when a file exceeds the maximum file size specified and is therefore not uplaoded
	@Param: object file file.name, file.size, file.sizeK, file.exceededBy, file.limit, file.message
	*/
	onExceedsMaxFileSizeK : function(file){},

	/**
	@Name: sb.upload_button.prototype.onExceedsMaxFiles
	@Description: Fires when a user selects too many files
	@Param: object files.chosen, files.limit, files.message
	*/
	onExceedsMaxFiles : function(files){},

	/**
	@Name: sb.upload_button.prototype.onError
	@Description: Fires if the upload is canceled due to an error
	@Param: object file.name, file.size, file.sizeK, file.type, file.error
	*/
	onError : function(file){},

	/**
	@Name: sb.upload_button.prototype.onOpen
	@Description: Fires when the file is opened for upload on the client's computer
	@Param: object file.name, file.size, file.sizeK, file.type
	*/
	onOpen : function(file){},

	/**
	@Name: sb.upload_button.prototype.onReturnData
	@Description: Fires when the data is returned from the server, , must beturn something from the serer for this to fire, can be a simple space
	@Param: object file.name, file.size, file.sizeK, file.type, file.data
	*/
	onReturnData : function(file){},

	/**
	@Name: sb.upload_button.prototype.onAllComplete
	@Description: Fires when all uploads for this upload instance are complete
	@Param: object files.total
	*/
	onAllComplete : function(files){},

	/**
	@Name: sb.upload_button.prototype.onComplete
	@Description: Fires when a file is done uploading, must beturn something from the serer for this to fire, can be a simple space
	@Param: object file.name, file.size, file.sizeK, file.type
	*/
	onComplete : function(files){},

	/**
	@Name: sb.upload_button.prototype.onAllProgress
	@Description: Fires each time one more file is uploaded until the que is empty
	@Param: object files.total, files.remaining
	*/
	onAllProgress : function(files){},

	/**
	@Name: sb.upload_button.prototype.onProgress
	@Description: Fires periodically as a file uploads alerting you of the progress in percent, deosn't seem to fire for really quick uploads on local server, must return something from the serer for this to fire, can be a simple space
	@Param: object file.name, file.size, file.sizeK, file.type, file.bytesLoaded, file.bytesTotal, file.percent
	*/
	onProgress : function(files){},
	//files.remaining

	/**
	@Name: sb.upload_button.prototype.onCancelBrowse
	@Description: Fires when the user hits cancel in the file browser
	*/
	onCancelBrowse : function(){},

	/**
	@Name: sb.upload_button.prototype.onCancelAll
	@Description: Fires once when the upload que is canceled using upload.cancel();
	*/
	onCancelAll : function(){},

	/**
	@Name: sb.upload_button.prototype.onCancelFile
	@Description: Fires when one file in the que is canceled by filename with upload.cancel(file.name); or once per file when upload.cancel()l is fired without a name specified
	@Param: object file.name
	*/
	onCancelFile : function(){}

};<commit_msg>removing upload_button.js in favor of uploadButton.js<commit_after><|endoftext|>


<commit_before>Package.describe({
  name: 'barbatus:ng2-compilers',
  version: '0.2.0-beta.1',
  summary: 'Angular2 template, HTML, JSX, TypeScript Compilers for Meteor',
  git: 'https://github.com/barbatus/ng2-compilers',
  documentation: null
});

Package.registerBuildPlugin({
  name: 'Compilers',
  sources: [
    'utils/file_mixin.js',
    'utils/mixin.js',
    'compilers/ng_compiler.js',
    'compilers/ng_caching_compiler.js',
    'compilers/html_compiler.js',
    'plugin/register.js'
  ],
  use: [
    'caching-compiler@1.0.0',
    'mrt:cheerio@0.3.2',
    'barbatus:ts-compilers@0.2.5',
    'ecmascript@0.3.1-modules.4',
    'check@1.1.0',
    'underscore@1.0.4'
  ]
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.0.1');

  // Required in order to register plugins
  api.use('isobuild:compiler-plugin@1.0.0');

  api.imply([
    'check@1.1.0',
    'ejson@1.0.7',
    'mongo@1.1.3',
    'tracker@1.0.9',
    'underscore@1.0.4'
  ]);

  api.addFiles('stub/stub.html');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('barbatus:ng2-compilers');
});
<commit_msg>Bump version of ng2-compilers<commit_after>Package.describe({
  name: 'barbatus:ng2-compilers',
  version: '0.2.0-beta.2',
  summary: 'Angular2 template, HTML, TypeScript Compilers for Meteor 1.3',
  git: 'https://github.com/Urigo/angular2-meteor/',
  documentation: null
});

Package.registerBuildPlugin({
  name: 'Compilers',
  sources: [
    'utils/file_mixin.js',
    'utils/mixin.js',
    'compilers/ng_compiler.js',
    'compilers/ng_caching_compiler.js',
    'compilers/html_compiler.js',
    'plugin/register.js'
  ],
  use: [
    'caching-compiler@1.0.0',
    'mrt:cheerio@0.3.2',
    'barbatus:ts-compilers@0.2.5',
    'ecmascript@0.3.1-modules.4',
    'check@1.1.0',
    'underscore@1.0.4'
  ]
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.0.1');

  // Required in order to register plugins
  api.use('isobuild:compiler-plugin@1.0.0');

  api.imply([
    'check@1.1.0',
    'ejson@1.0.7',
    'mongo@1.1.3',
    'tracker@1.0.9',
    'underscore@1.0.4'
  ]);

  api.addFiles('stub/stub.html');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('barbatus:ng2-compilers');
});
<|endoftext|>


<commit_before>(function (window, undefined) {

    var defaults = {

            color: 'pink'

        },

        colors = {

            blue: function(r, g, b) {
                var threshold = 50;

                if ((b - r) >= threshold && (b - g) >= threshold) {
                    return true;
                }
            },

            green: function(r, g, b) {
                var thresholdRed = 30,
                    thresholdBlue = 10;

                if ((g - r) >= thresholdRed && (g - b) >= thresholdBlue) {
                    return true;
                }
            },

            pink: function(r, g, b) {
                var threshold = 50;

                if ((r - g) >= threshold && (b - g) >= threshold) {
                    return true;
                }
            }

        },

        isString = tracking.isString,

        distance = tracking.math.distance;

    tracking.type.COLOR = function(config, video) {

        var cpx, cpy, cpz,

            dist,

            dx = 0, dy = 0,

            m1 = 0, m2 = 0, n,

            minx = Infinity, maxx = -1,

            miny = Infinity, maxy = -1,

            pixels = [],

            total = 0, totalInliers = 0,

            x, y,

            imageData = video.getVideoCanvasImageData(),

            colorThreshold = config.color || defaults.color;

        if (isString(colorThreshold) && colors.hasOwnProperty(colorThreshold)) {
            colorThreshold = colors[colorThreshold];
        }

        video.canvas.forEach(imageData, function pixelMatrixLoop(r, g, b, a, w, i, j) {
            if (colorThreshold(r, g, b, a, w, i, j)) {
                total += 2;
                pixels.push(j, i);
            }
        });

        if (total < 30) {
            return;
        }

        // Flag outliers
        for (; m1 < total; m1+=2) {
            dist = 0;

            for (n = 2; n < total; n+=2) {
                dist += distance(pixels[m1], pixels[m1+1], pixels[n], pixels[n+1]);
            }

            if (dist/total > 20) {
                pixels[m1] = -1;
                pixels[m1+1] = -1;
            }
        }

        for (; m2 < total; m2+=2) {
            x = pixels[m2];
            y = pixels[m2+1];

            if (x > -1 && y > -1) {
                dx += x;
                dy += y;
                totalInliers++;

                if (x < minx) {
                    minx = x;
                }

                if (x > maxx) {
                    maxx = x;
                }

                if (y < miny) {
                    miny = y;
                }

                if (y > maxy) {
                    maxy = y;
                }
            }
        }

        cpy = dy/totalInliers;
        cpx = dx/totalInliers;
        cpz = 60 - ((maxx - minx) + (maxy - miny))/2;

        if (config.callback) {
            config.callback.call(video, {
                x: cpx,
                y: cpy,
                z: cpz,
                pixels: pixels
            });
        }
    };

    tracking.type.COLOR.colors = colors;

    tracking.type.COLOR.defaults = defaults;

}( window ));<commit_msg>Source Formatting<commit_after>(function (window, undefined) {

    var defaults = {

            color: 'pink'

        },

        colors = {

            blue: function(r, g, b) {
                var threshold = 50;

                if ((b - r) >= threshold && (b - g) >= threshold) {
                    return true;
                }
            },

            green: function(r, g, b) {
                var thresholdRed = 30,
                    thresholdBlue = 10;

                if ((g - r) >= thresholdRed && (g - b) >= thresholdBlue) {
                    return true;
                }
            },

            pink: function(r, g, b) {
                var threshold = 50;

                if ((r - g) >= threshold && (b - g) >= threshold) {
                    return true;
                }
            }

        },

        isString = tracking.isString,

        distance = tracking.math.distance;

    tracking.type.COLOR = function(config, video) {

        var cpx, cpy, cpz,

            dist,

            dx = 0, dy = 0,

            m1 = 0, m2 = 0, n,

            minx = Infinity, maxx = -1,

            miny = Infinity, maxy = -1,

            pixels = [],

            total = 0, totalInliers = 0,

            x, y,

            imageData = video.getVideoCanvasImageData(),

            colorThreshold = config.color || defaults.color;

        if (isString(colorThreshold) && colors.hasOwnProperty(colorThreshold)) {
            colorThreshold = colors[colorThreshold];
        }

        video.canvas.forEach(
            imageData,
            function pixelMatrixLoop(r, g, b, a, w, i, j) {
                if (colorThreshold(r, g, b, a, w, i, j)) {
                    total += 2;
                    pixels.push(j, i);
                }
            }
        );

        if (total < 30) {
            return;
        }

        // Flag outliers
        for (; m1 < total; m1+=2) {
            dist = 0;

            for (n = 2; n < total; n+=2) {
                dist += distance(
                    pixels[m1], pixels[m1+1], pixels[n], pixels[n+1]);
            }

            if (dist/total > 20) {
                pixels[m1] = -1;
                pixels[m1+1] = -1;
            }
        }

        for (; m2 < total; m2+=2) {
            x = pixels[m2];
            y = pixels[m2+1];

            if (x > -1 && y > -1) {
                dx += x;
                dy += y;
                totalInliers++;

                if (x < minx) {
                    minx = x;
                }

                if (x > maxx) {
                    maxx = x;
                }

                if (y < miny) {
                    miny = y;
                }

                if (y > maxy) {
                    maxy = y;
                }
            }
        }

        cpy = dy/totalInliers;
        cpx = dx/totalInliers;
        cpz = 60 - ((maxx - minx) + (maxy - miny))/2;

        if (config.callback) {
            config.callback.call(video, {
                x: cpx,
                y: cpy,
                z: cpz,
                pixels: pixels
            });
        }
    };

    tracking.type.COLOR.colors = colors;

    tracking.type.COLOR.defaults = defaults;

}( window ));<|endoftext|>


<commit_before>import React, { Component } from 'react'

export default class Head extends Component {
  render() {
    const { head } = this.props
    return (

        <Title>{head.title}</Title>
        {head.subtitle?
          <SubTitle>{head.subtitle}</SubTitle>: null
        }

    )
  }
}

Head.proptTypes = {
  head: React.PropTypes.shape({
    title: React.PropTypes.string.isRequired,

    logo: React.PropTypes.string,
    subtitle: React.PropTypes.string,
    description: React.PropTypes.string,
  }).isRequired
}

class Title extends Component {
  render() {
    return (

        {this.props.children.toUpperCase()}

    )
  }
}

class SubTitle extends Component {
  render () {
    return (

          {this.props.children.toLowerCase()}

    )
  }
}
<commit_msg>Create Head html architecture<commit_after>import React, { Component } from 'react'

export default class Head extends Component {
  constructor(props) {
    super(props)
    this.state = {height: this.props.height}
  }

  componentDidMount() {
    this.setState({height: window.innerHeight})
  }

  render() {
    const { head } = this.props
    return (
      <div style={{
        height: `${Math.min(this.state.height, 500)}px`,
        display: 'flex'
      }}>

          <Title>{head.title}</Title>
          {head.subtitle?<SubTitle>{head.subtitle}</SubTitle>: null}

    )
  }
}

Head.proptTypes = {
  head: React.PropTypes.shape({
    title: React.PropTypes.string.isRequired,

    logo: React.PropTypes.string,
    subtitle: React.PropTypes.string,
    description: React.PropTypes.string,
  }).isRequired,
  height: React.PropTypes.number,
}

Head.defaultProps = {
  height: 500,
}

class Title extends Component {
  render() {
    return (

{this.props.children.toUpperCase()}

    )
  }
}

class SubTitle extends Component {
  render () {
    return (

          {this.props.children.toLowerCase()}

    )
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

const co = require("co");
const Hook = require("../util/hook");
const UserError = require("../../lib/util/user_error");

/**
 * This module contains the entrypoint for the `checkout` command.
 */

exports.helpText = `Check out a commit in the meta-repository and each
(visible) submodule.  Fetch commits by SHA as needed for submodules`;

/**
 * Configure the sepcified `parser` for the `checkout` command.
 *
 * @param {ArgumentParser} parser
 */
exports.configureParser = function (parser) {

    parser.addArgument(["-b"], {
        dest: "new branch name",
        help: `Create a new branch to check out.`,
        nargs: 1,
    });

    parser.addArgument(["committish_or_file"], {
        type: "string",
        help: `if this resolves to a commit, check out that commit.
If this <committish> is not found, but does \
match a single remote tracking branch, treat as equivalent to \
'checkout -b <committish> -t <remote>/<committish>'.  Else, treat \
        as a file`,
        defaultValue: null,
        nargs: "?",
    });

    parser.addArgument(["files"], {
        type: "string",
        nargs: "*"
    });

    parser.addArgument(["-t", "--track"], {
        help: "Set tracking branch.",
        action: "storeConst",
        constant: true,
    });

    parser.addArgument(["-f", "--force"], {
        required: false,
        action: "storeConst",
        constant: true,
        help: `Overwrite conflicting local changes.`,
    });
};

/*
Argparse literally can't represent git's semantics here.  Checkout
takes optional arguments [branch] and [files].  In git, anything after
"--" (hereinafter, "the separator") is part of "files".  So if you say
"git checkout -- myfile", it'll assume that last argument is a file.

There are two types of arguments that argparse recognizes: regular and
positional.  Branch can't be a non-required regular argument, because
regular arguments must have names which start with "-".  So it must be
a positional argument with nargs='?'.  In argparse, the right side of
"--" is always positional arguments.  And that means that the branch
will be read from the right side of the separator if it is not present
on the left side.

(Incidentally, the same is true of Python's argparse, of which node's
argparse is a port.)

Thanks, git, for using "--" for an utterly non-standard fashion.
*/
function reanalyzeArgs(args)  {
    const separatorIndex = process.argv.indexOf("--");
    if (separatorIndex === -1) {
        return;
    }

    const countAfterSeparator = (process.argv.length - 1) - separatorIndex;

    if (args.files.length !== countAfterSeparator) {
        const firstFile = args.committish_or_file;
        args.committish_or_file = null;
        args.files.splice(0, 0, firstFile);
    }
}

/**
 * Execute the `checkout` command based on the supplied arguments.
 *
 * @async
 * @param {Object} args
 * @param {String} args.committish
 */
exports.executeableSubcommand = co.wrap(function *(args) {
    reanalyzeArgs(args);

    const colors  = require("colors");

    const Checkout  = require("../util/checkout");
    const GitUtil   = require("../util/git_util");
    let newBranch = null;
    let branchCheckout = "1";

    const newBranchNameArr = args["new branch name"];
    if (newBranchNameArr) {
        newBranch = newBranchNameArr[0];
    }
    const repo = yield GitUtil.getCurrentRepo();

    // Validate and determine what operation we're actually doing.

    let committish = args.committish_or_file;
    let files = args.files;

    if (files.length > 0 && newBranch) {
        throw new UserError(`Cannot update paths and switch to branch
                            '${newBranch}' at the same time.`);
    }

    const op = yield Checkout.deriveCheckoutOperation(repo,
                                                      committish,
                                                      newBranch,
                                                      args.track || false,
                                                      files);

    if (op.commit === null) {
        throw new UserError(`pathspec '${committish}' did not match any
                            file(s) known to git.`);
    }

    // If we're going to check out files, just do that
    if (op.resolvedPaths !== null &&
        Object.keys(op.resolvedPaths).length !== 0) {
        yield Checkout.checkoutFiles(repo, op);
        return;
    }

    // If we're already on this branch, note it and exit.

    if (null === op.newBranch && null !== op.switchBranch) {
        const current = yield GitUtil.getCurrentBranchName(repo);
        if (current === op.switchBranch) {
            console.log(`Already on branch ${colors.green(current)}.`);
            return;                                                   // RETURN
        }
    }

    // Remember if we were detached so we can tell the users if we become
    // detached.

    const wasDetached = repo.headDetached() !== 0;

    // Now, do the actual operation.

    yield Checkout.executeCheckout(repo,
                                   op.commit,
                                   op.newBranch,
                                   op.switchBranch,
                                   args.force || false);

    // Tell the user what we just did.

    if (null !== op.commit && null === op.switchBranch) {
        // In this case, we're not making a branch; just let the user know what
        // we checked out.

        branchCheckout = "0";
        console.log(`Checked out ${colors.green(args.committish)}.`);
    }

    // Run post-checkout hook.
    // Note: The hook is given three parameters: the ref of the previous HEAD,
    // the ref of the new HEAD (which may or may not have changed), and a flag
    // indicating whether the checkout was a branch checkout (changing
    // branches, flag = "1"), or a file checkout (retrieving a file from the
    // index, flag = "0").

    const headId = yield repo.getHeadCommit();
    const oldHead = headId.id().tostrS();
    const newHead = op.commit;
    yield Hook.execHook(repo, "post-checkout",
                        [oldHead, newHead, branchCheckout]);
    // If we made a new branch, let the user know about it.

    const newB = op.newBranch;

    if (null !== newB) {
        const name = newB.name;
        console.log(`Created branch ${colors.green(name)}.`);
        const tracking = newB.tracking;
        if (null !== tracking) {
            if (null === tracking.remoteName) {
                console.log(`\
Configured ${colors.green(name)} to track local branch \
${colors.blue(tracking.branchName)}.`);
            }
            else {
                console.log(`\
Configured ${colors.green(name)} to track remote branch \
${colors.blue(tracking.branchName)} from \
${colors.blue(tracking.remoteName)}.`);
            }
        }
    }
    if (null !== op.switchBranch) {
        // Let the user know if we switched branches.

        console.log(`Switched to branch ${colors.green(op.switchBranch)}.`);
    }
    else if (null !== op.commit) {
        // If we just did a checkout and didn't switch branches, let the user
        // know if we transitioned to a detached state.

        if (!wasDetached) {
            console.log(`You are now in 'detached HEAD' state.`);
        }
    }
});
<commit_msg>fix "undefined"  for detached head<commit_after>/*
 * Copyright (c) 2016, Two Sigma Open Source
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of git-meta nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

const co = require("co");
const Hook = require("../util/hook");
const UserError = require("../../lib/util/user_error");

/**
 * This module contains the entrypoint for the `checkout` command.
 */

exports.helpText = `Check out a commit in the meta-repository and each
(visible) submodule.  Fetch commits by SHA as needed for submodules`;

/**
 * Configure the sepcified `parser` for the `checkout` command.
 *
 * @param {ArgumentParser} parser
 */
exports.configureParser = function (parser) {

    parser.addArgument(["-b"], {
        dest: "new branch name",
        help: `Create a new branch to check out.`,
        nargs: 1,
    });

    parser.addArgument(["committish_or_file"], {
        type: "string",
        help: `if this resolves to a commit, check out that commit.
If this <committish> is not found, but does \
match a single remote tracking branch, treat as equivalent to \
'checkout -b <committish> -t <remote>/<committish>'.  Else, treat \
        as a file`,
        defaultValue: null,
        nargs: "?",
    });

    parser.addArgument(["files"], {
        type: "string",
        nargs: "*"
    });

    parser.addArgument(["-t", "--track"], {
        help: "Set tracking branch.",
        action: "storeConst",
        constant: true,
    });

    parser.addArgument(["-f", "--force"], {
        required: false,
        action: "storeConst",
        constant: true,
        help: `Overwrite conflicting local changes.`,
    });
};

/*
Argparse literally can't represent git's semantics here.  Checkout
takes optional arguments [branch] and [files].  In git, anything after
"--" (hereinafter, "the separator") is part of "files".  So if you say
"git checkout -- myfile", it'll assume that last argument is a file.

There are two types of arguments that argparse recognizes: regular and
positional.  Branch can't be a non-required regular argument, because
regular arguments must have names which start with "-".  So it must be
a positional argument with nargs='?'.  In argparse, the right side of
"--" is always positional arguments.  And that means that the branch
will be read from the right side of the separator if it is not present
on the left side.

(Incidentally, the same is true of Python's argparse, of which node's
argparse is a port.)

Thanks, git, for using "--" for an utterly non-standard fashion.
*/
function reanalyzeArgs(args)  {
    const separatorIndex = process.argv.indexOf("--");
    if (separatorIndex === -1) {
        return;
    }

    const countAfterSeparator = (process.argv.length - 1) - separatorIndex;

    if (args.files.length !== countAfterSeparator) {
        const firstFile = args.committish_or_file;
        args.committish_or_file = null;
        args.files.splice(0, 0, firstFile);
    }
}

/**
 * Execute the `checkout` command based on the supplied arguments.
 *
 * @async
 * @param {Object} args
 * @param {String} args.committish
 */
exports.executeableSubcommand = co.wrap(function *(args) {
    reanalyzeArgs(args);

    const colors  = require("colors");

    const Checkout  = require("../util/checkout");
    const GitUtil   = require("../util/git_util");
    let newBranch = null;
    let branchCheckout = "1";

    const newBranchNameArr = args["new branch name"];
    if (newBranchNameArr) {
        newBranch = newBranchNameArr[0];
    }
    const repo = yield GitUtil.getCurrentRepo();

    // Validate and determine what operation we're actually doing.

    let committish = args.committish_or_file;
    let files = args.files;

    if (files.length > 0 && newBranch) {
        throw new UserError(`Cannot update paths and switch to branch
                            '${newBranch}' at the same time.`);
    }

    const op = yield Checkout.deriveCheckoutOperation(repo,
                                                      committish,
                                                      newBranch,
                                                      args.track || false,
                                                      files);

    if (op.commit === null) {
        throw new UserError(`pathspec '${committish}' did not match any
                            file(s) known to git.`);
    }

    // If we're going to check out files, just do that
    if (op.resolvedPaths !== null &&
        Object.keys(op.resolvedPaths).length !== 0) {
        yield Checkout.checkoutFiles(repo, op);
        return;
    }

    // If we're already on this branch, note it and exit.

    if (null === op.newBranch && null !== op.switchBranch) {
        const current = yield GitUtil.getCurrentBranchName(repo);
        if (current === op.switchBranch) {
            console.log(`Already on branch ${colors.green(current)}.`);
            return;                                                   // RETURN
        }
    }

    // Remember if we were detached so we can tell the users if we become
    // detached.

    const wasDetached = repo.headDetached() !== 0;

    // Now, do the actual operation.

    yield Checkout.executeCheckout(repo,
                                   op.commit,
                                   op.newBranch,
                                   op.switchBranch,
                                   args.force || false);

    // Tell the user what we just did.

    if (null !== op.commit && null === op.switchBranch) {
        // In this case, we're not making a branch; just let the user know what
        // we checked out.

        branchCheckout = "0";
        console.log(`Checked out ${colors.green(committish)}.`);
    }

    // Run post-checkout hook.
    // Note: The hook is given three parameters: the ref of the previous HEAD,
    // the ref of the new HEAD (which may or may not have changed), and a flag
    // indicating whether the checkout was a branch checkout (changing
    // branches, flag = "1"), or a file checkout (retrieving a file from the
    // index, flag = "0").

    const headId = yield repo.getHeadCommit();
    const oldHead = headId.id().tostrS();
    const newHead = op.commit;
    yield Hook.execHook(repo, "post-checkout",
                        [oldHead, newHead, branchCheckout]);
    // If we made a new branch, let the user know about it.

    const newB = op.newBranch;

    if (null !== newB) {
        const name = newB.name;
        console.log(`Created branch ${colors.green(name)}.`);
        const tracking = newB.tracking;
        if (null !== tracking) {
            if (null === tracking.remoteName) {
                console.log(`\
Configured ${colors.green(name)} to track local branch \
${colors.blue(tracking.branchName)}.`);
            }
            else {
                console.log(`\
Configured ${colors.green(name)} to track remote branch \
${colors.blue(tracking.branchName)} from \
${colors.blue(tracking.remoteName)}.`);
            }
        }
    }
    if (null !== op.switchBranch) {
        // Let the user know if we switched branches.

        console.log(`Switched to branch ${colors.green(op.switchBranch)}.`);
    }
    else if (null !== op.commit) {
        // If we just did a checkout and didn't switch branches, let the user
        // know if we transitioned to a detached state.

        if (!wasDetached) {
            console.log(`You are now in 'detached HEAD' state.`);
        }
    }
});
<|endoftext|>


<commit_before>var errors = {
	INVALID_SESSION : function() {
		this.code=1;
		this.msg="Session is invalid, try logging in again.";
	},
	ACCESS_TOKEN_EXPIRED : function() {
		this.code=2;
		this.msg="Access tokens expired, try making the request again.";
	},
	ACCESS_ERROR : function() {
		this.code=3;
		this.msg="Error occured while accessing server. Server reply: ";
	},
	FETCH_PLAYLISTS_FAILED : function() {
		this.code=4;
		this.msg="Failed to get playlists. Reason: ";
	},
	ERROR_COPYING_PLAYLIST : function() {
		this.code=5;
		this.msg="Error attempting to copy over playlist. Response Data: ";
	},
	INVALID_PARAMETERS : function() {
		this.code=6;
		this.msg="Invalid paramteres supplied";
	},
	ERROR_ADDING_TRACKS : function() {
		this.code=7;
		this.msg="An error occured while adding tracks. Response data: ";
	},
	ERROR_REMOVING_TRACKS : function() {
		this.code=8;
		this.msg="An error occured while removing tracks. Response data: ";
	}
}

// For node.js
module.exports = errors;<commit_msg>added new error, made code's more readable<commit_after>var errors = {
	INVALID_SESSION : function() {
		this.code = 1;
		this.msg="Session is invalid, try logging in again.";
	},
	ACCESS_TOKEN_EXPIRED : function() {
		this.code = 2;
		this.msg="Access tokens expired, try making the request again.";
	},
	ACCESS_ERROR : function() {
		this.code = 3;
		this.msg="Error occured while accessing server. Server reply: ";
	},
	FETCH_PLAYLISTS_FAILED : function() {
		this.code = 4;
		this.msg="Failed to get playlists. Reason: ";
	},
	ERROR_COPYING_PLAYLIST : function() {
		this.code = 5;
		this.msg="Error attempting to copy over playlist. Response Data: ";
	},
	INVALID_PARAMETERS : function() {
		this.code = 6;
		this.msg="Invalid paramteres supplied";
	},
	ERROR_ADDING_TRACKS : function() {
		this.code = 7;
		this.msg="An error occured while adding tracks. Response data: ";
	},
	ERROR_REMOVING_TRACKS : function() {
		this.code = 8;
		this.msg="An error occured while removing tracks. Response data: ";
	},
	FAILED_CREATE_PLAYLIST : function() {
		this.code = 9;
		this.msg="Failed to create playlist. Response data: ";
	}
}

// For node.js
module.exports = errors;<|endoftext|>


<commit_before>'use strict'
/*
  Add Inflows, i,j,k,amp,cost,lb,ub into the system.  If inflow==0
  we won't add it in, so  this can always be called.  Returns 0 rows otherwise
*/
var u = require('./utils');

module.exports = function(item, steps) {
  var rows=[];
  var p=item.properties;
  var id=p.hobbes.networkId;

  if (p.inflows) {
    // This should be done for every inflow
    var inflow = p.inflows.default.inflow;
    var time;
    var row;
    var inflow_at={};
    var inf, i;

    // Lookup evap - could be faster
    inflow.forEach(function(e) {
      inflow_at[e[0]] = e[1];
    });

    for( i = 0; i < steps.length; i++ ){
      inf = inflow_at[steps[i]];
      if( typeof inf !=='undefined' && inf !== null && inf !== 0) {
        rows.push([
          u.id('INFLOW',steps[i]),
          u.id(id,steps[i]),
          // JM - fixing issue #32.
          // old values: k=0, cost=1
          0,   // k
          0,   // cost
          1,   // amplitude
          inf, // lower bound
          inf  // upper bound
        ]);
      }
    }
  }

  return rows;
};
<commit_msg>adding 0 inflow values to matrix, issue #37<commit_after>'use strict'
/*
  Add Inflows, i,j,k,amp,cost,lb,ub into the system.  If inflow==0
  we won't add it in, so  this can always be called.  Returns 0 rows otherwise
*/
var u = require('./utils');

module.exports = function(item, steps) {
  var rows=[];
  var p=item.properties;
  var id=p.hobbes.networkId;

  if (p.inflows) {
    // This should be done for every inflow
    var inflow = p.inflows.default.inflow;
    var time;
    var row;
    var inflow_at={};
    var inf, i;

    // Lookup evap - could be faster
    inflow.forEach(function(e) {
      inflow_at[e[0]] = e[1];
    });

    for( i = 0; i < steps.length; i++ ){
      inf = inflow_at[steps[i]];
      // JM - fix for issue #37
      // if( typeof inf !=='undefined' && inf !== null && inf !== 0) {
      if( typeof inf !=='undefined' && inf !== null ) {
        rows.push([
          u.id('INFLOW',steps[i]),
          u.id(id,steps[i]),
          // JM - fixing issue #32.
          // old values: k=0, cost=1
          0,   // k
          0,   // cost
          1,   // amplitude
          inf, // lower bound
          inf  // upper bound
        ]);
      }
    }
  }

  return rows;
};
<|endoftext|>


<commit_before>import React from 'react';

/* eslint-disable no-underscore-dangle */
/* @link http://stackoverflow.com/questions/46155/validate-email-address-in-javascript */
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

const isEmpty = (value) => (typeof value === 'undefined' || value === null || value === '');

/* eslint-disable no-confusing-arrow */
export const coreConstraints = {
    required: (value) => isEmpty(value) ? 'Required field' : null,
    min: (value, _, min) => !isEmpty(value) && (isNaN(parseInt(value, 10)) || parseInt(value, 10) < min) ? `Minimum value: ${min}` : null,
    max: (value, _, max) => !isEmpty(value) && (isNaN(parseInt(value, 10)) || parseInt(value, 10) > max) ? `Maximum value: ${max}` : null,
    minLength: (value, _, min) => isEmpty(value) || `${value}`.length < min ? `Minimum length: ${min}` : null,
    maxLength: (value, _, max) => !isEmpty(value) && `${value}`.length > max ? `Maximum length: ${max}` : null,
    email: (value) => !isEmpty(value) && !EMAIL_REGEX.test(value) ? 'Must be a valid email' : null,
    regex: (value, _, { pattern, message }) => !isEmpty(value) && !pattern.test(value) ? message : null,
    choices: (value, _, { list, message }) => !isEmpty(value) && list.indexOf(value) === -1 ? message : null,
    custom: (value, values, func) => func(value, values),
};

/**
 * Combine multiple constraints into a single function
 *
 * @param {Object} constraints Constraints object; e.g. { required: true, min: 3 }
 *
 * @return {function} A function (value, values) => [errors]
 */
const getConstraintsFunction = constraints => (value, values) => Object.keys(constraints)
    .filter(constraintName => coreConstraints[constraintName])
    .map(constraintName => {
        const constraint = coreConstraints[constraintName];
        constraint._name = constraintName; // .name does not exist on IE
        return constraint;
    })
    .reduce((errors, constraint) => [
        ...errors,
        constraint(value, values, constraints[constraint.name]),
    ], [])
    .filter(error => error !== null);

export const getConstraintsFunctionFromFunctionOrObject = (constraints) => {
    if (typeof constraints === 'function') return constraints;
    if (!Array.isArray(constraints) && typeof constraints === 'object') return getConstraintsFunction(constraints);
    throw new Error('Unsupported validation type');
};

/**
 * @example
 * from the following fields:
 *     <TextField source="title" validation={{ minLength: 5 }} />
 *     <TextField source="age" validation={{ required: true, min: 18 }} />
 * produces the following output
 * {
 *    title: (value) => value.length < 5 ? ['title is too short'] : [],
 *    age:   (value) => {
 *       const errors = [];
 *       if (value) errors.push('age is required');
 *       if (value < 18) errors.push('age is under 18');
 *       return errors;
 *    }
 * }
 */
export const getFieldConstraints = children => React.Children.toArray(children)
    .map(({ props: { source: fieldName, validation } }) => ({ fieldName, validation }))
    .filter(({ validation }) => !!validation)
    .reduce((constraints, { fieldName, validation }) => {
        constraints[fieldName] = getConstraintsFunctionFromFunctionOrObject(validation); // eslint-disable-line no-param-reassign
        return constraints;
    }, {});

export const getErrorsForForm = (validation, values) => {
    const errorsForForm = typeof validation === 'function' ? validation(values) : {};
    // warn user we expect an object here, in case of validation just returned an error message
    if (errorsForForm === null || typeof errorsForForm !== 'object') {
        throw new Error('Validation function given to form components should return an object.');
    }
    return errorsForForm;
};

export const getErrorsForFieldConstraints = (fieldConstraints, values) => {
    const errors = {};
    Object.keys(fieldConstraints).forEach((fieldName) => {
        const error = fieldConstraints[fieldName](values[fieldName], values);
        if (error.length > 0) {
            if (!errors[fieldName]) {
                errors[fieldName] = [];
            }
            errors[fieldName] = [...errors[fieldName], ...error];
        }
    });
    return errors;
};

/**
 * Validator function for redux-form
 */
export const validateForm = (values, { children, validation }) => ({
    ...getErrorsForForm(validation, values),
    ...getErrorsForFieldConstraints(getFieldConstraints(children), values),
});
<commit_msg>Rename variable<commit_after>import React from 'react';

/* eslint-disable no-underscore-dangle */
/* @link http://stackoverflow.com/questions/46155/validate-email-address-in-javascript */
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

const isEmpty = (value) => (typeof value === 'undefined' || value === null || value === '');

/* eslint-disable no-confusing-arrow */
export const coreConstraints = {
    required: (value) => isEmpty(value) ? 'Required field' : null,
    min: (value, _, min) => !isEmpty(value) && (isNaN(parseInt(value, 10)) || parseInt(value, 10) < min) ? `Minimum value: ${min}` : null,
    max: (value, _, max) => !isEmpty(value) && (isNaN(parseInt(value, 10)) || parseInt(value, 10) > max) ? `Maximum value: ${max}` : null,
    minLength: (value, _, min) => isEmpty(value) || `${value}`.length < min ? `Minimum length: ${min}` : null,
    maxLength: (value, _, max) => !isEmpty(value) && `${value}`.length > max ? `Maximum length: ${max}` : null,
    email: (value) => !isEmpty(value) && !EMAIL_REGEX.test(value) ? 'Must be a valid email' : null,
    regex: (value, _, { pattern, message }) => !isEmpty(value) && !pattern.test(value) ? message : null,
    choices: (value, _, { list, message }) => !isEmpty(value) && list.indexOf(value) === -1 ? message : null,
    custom: (value, values, func) => func(value, values),
};

/**
 * Combine multiple constraints into a single function
 *
 * @param {Object} constraints Constraints object; e.g. { required: true, min: 3 }
 *
 * @return {function} A function (value, values) => [errors]
 */
const getConstraintsFunction = constraints => (value, values) => Object.keys(constraints)
    .filter(constraintName => coreConstraints[constraintName])
    .map(constraintName => {
        const constraint = coreConstraints[constraintName];
        constraint._name = constraintName; // .name does not exist on IE
        return constraint;
    })
    .reduce((errors, constraint) => [
        ...errors,
        constraint(value, values, constraints[constraint.name]),
    ], [])
    .filter(error => error !== null);

export const getConstraintsFunctionFromFunctionOrObject = (constraints) => {
    if (typeof constraints === 'function') return constraints;
    if (!Array.isArray(constraints) && typeof constraints === 'object') return getConstraintsFunction(constraints);
    throw new Error('Unsupported validation type');
};

/**
 * @example
 * from the following fields:
 *     <TextField source="title" validation={{ minLength: 5 }} />
 *     <TextField source="age" validation={{ required: true, min: 18 }} />
 * produces the following output
 * {
 *    title: (value) => value.length < 5 ? ['title is too short'] : [],
 *    age:   (value) => {
 *       const errors = [];
 *       if (value) errors.push('age is required');
 *       if (value < 18) errors.push('age is under 18');
 *       return errors;
 *    }
 * }
 */
export const getFieldConstraints = children => React.Children.toArray(children)
    .map(({ props: { source: fieldName, validation } }) => ({ fieldName, validation }))
    .filter(({ validation }) => !!validation)
    .reduce((constraints, { fieldName, validation }) => {
        constraints[fieldName] = getConstraintsFunctionFromFunctionOrObject(validation); // eslint-disable-line no-param-reassign
        return constraints;
    }, {});

export const getErrorsForForm = (validation, values) => {
    const errors = typeof validation === 'function' ? validation(values) : {};
    // warn user we expect an object here, in case of validation just returned an error message
    if (errors === null || typeof errors !== 'object') {
        throw new Error('Validation function given to form components should return an object.');
    }
    return errors;
};

export const getErrorsForFieldConstraints = (fieldConstraints, values) => {
    const errors = {};
    Object.keys(fieldConstraints).forEach((fieldName) => {
        const error = fieldConstraints[fieldName](values[fieldName], values);
        if (error.length > 0) {
            if (!errors[fieldName]) {
                errors[fieldName] = [];
            }
            errors[fieldName] = [...errors[fieldName], ...error];
        }
    });
    return errors;
};

/**
 * Validator function for redux-form
 */
export const validateForm = (values, { children, validation }) => ({
    ...getErrorsForForm(validation, values),
    ...getErrorsForFieldConstraints(getFieldConstraints(children), values),
});
<|endoftext|>


<commit_before>"use strict"

module.exports = function(attrName, callback, context) {
	return function(e) {
		return callback.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName))
	}
}
<commit_msg>don't return from withAttr<commit_after>"use strict"

module.exports = function(attrName, callback, context) {
	return function(e) {
		callback.call(context || this, attrName in e.currentTarget ? e.currentTarget[attrName] : e.currentTarget.getAttribute(attrName))
	}
}
<|endoftext|>


<commit_before>var iris = require('./iris-base.js');
var config = iris.loadConfiguration();
var app = iris.app;
iris.configureViews(app);
var routes = iris.routes;

/* Widget configuration
 *
 * Associate widget name (key) with renderer (value)
 * Rendering JavaScript is assumed to be in DOCSROOT/js/widgets
 *
 * TODO: Move to MetaContainer?
 */
var widgetList = [
	{ id: 'manhattan', name: 'Manhattan Plot', js: 'manhattan.js' },
	{ id: 'data', name: 'Data browser', js: 'data.js' },
	{ id: 'pcoords', name: 'Parallel Coordinates Plot', js: 'pcoords.js' },
	{ id: 'chord', name: 'Chord', js: 'chord.js' },
	{ id: 'barChart', name: 'Bar Chart', js: 'barchart.js' }
];

function findWidget(key, val) {
	for(var i in widgetList) {
		if (widgetList[i][key] === val) {
			return widgetList[i];
		}
	}
	return null;
}

// Routes
app.get('/', routes.index);

app.get('/404', function(req, res) {
    res.render('error', { title: 'Page not found',
                          heading: 'Page not found',
                          message: 'Now go back to where ya came from.'});
});

app.get('/widget/:widget', function(req, res) {
    // TODO: Should this be configured at a more stateful level, e.g., session?
    var layout = req.query["layout"] != null && req.query["layout"] == 'on';
	var widget = findWidget("id",req.params.widget);
    if (widget == null) {
        res.redirect('/404');
    } else {
        routes.widget(req, res, { widget: widget.id, js: widget.js, layout: layout });
    }
});

app.get('/workspace-demo', function(req, res) {
    routes.workspace(req, res, widgetList);
});
app.get('/workspace', function(req, res) {
	routes.workspace(req, res, widgetList);
});

app.get('/services', function(req,res){
	res.json(iris.services['services']);
});

iris.startService();
<commit_msg>Missed a small change.<commit_after>var iris = require('./iris-base.js');
var config = iris.loadConfiguration();
var app = iris.app;
iris.configureViews(app);
var routes = iris.routes;

/* Widget configuration
 *
 * Associate widget name (key) with renderer (value)
 * Rendering JavaScript is assumed to be in DOCSROOT/js/widgets
 *
 * TODO: Move to MetaContainer?
 */
var widgetList = [
	{ id: 'manhattan', name: 'Manhattan Plot', js: 'manhattan.js' },
	{ id: 'data', name: 'Data browser', js: 'data.js' },
	{ id: 'pcoords', name: 'Parallel Coordinates Plot', js: 'pcoords.js' },
	{ id: 'chord', name: 'Chord', js: 'chord.js' },
	{ id: 'barChart', name: 'Bar Chart', js: 'barchart.js' }
];

function findWidget(key, val) {
	for(var i in widgetList) {
		if (widgetList[i][key] === val) {
			return widgetList[i];
		}
	}
	return null;
}

// Routes
app.get('/', routes.index);

app.get('/404', function(req, res) {
    res.render('error', { title: 'Page not found',
                          heading: 'Page not found',
                          message: 'Now go back to where ya came from.'});
});

app.get('/widget/:widget', function(req, res) {
    // TODO: Should this be configured at a more stateful level, e.g., session?
    var layout = req.query["layout"] != null && req.query["layout"] == 'on';
	var widget = findWidget("id",req.params.widget);
    if (widget == null) {
        res.redirect('/404');
    } else {
        routes.widget(req, res, { widget: widget.id, js: widget.js, layout: layout });
    }
});

app.get('/workspace', function(req, res) {
	routes.workspace(req, res, widgetList);
});

app.get('/services', function(req,res){
	res.json(iris.services['services']);
});

iris.startService();
<|endoftext|>