<commit_before>var loadExamples = function() {
  var graphWordBoundaries = document.getElementById("graphWordBoundaries");
  var showWordBoundaries;
  if (graphWordBoundaries && graphWordBoundaries.checked) {
    showWordBoundaries = true;
  } else {
    showWordBoundaries = false;
  }

  var rerenderIfWordBoundariesChange = [];
  graphWordBoundaries.onchange = function() {
    if (graphWordBoundaries && graphWordBoundaries.checked) {
      showWordBoundaries = true;
    } else {
      showWordBoundaries = false;
    }
    for (var functionToCall = 0; functionToCall < rerenderIfWordBoundariesChange.length; functionToCall++) {
      rerenderIfWordBoundariesChange[functionToCall]();
    }
  };

  var url = "https://localhost:6984";
  // var firstdb = "elisekm-eti3_data_tutorial";
  // var firstGlosser = new Glosser({
  //   pouchname: firstdb
  // });
  // firstGlosser.downloadPrecedenceRules(firstdb, url + "/" + firstdb + "/_design/lexicon/_view/morphemesPrecedenceContext?group=true", function(precedenceRelations) {
  //   var utterance = firstGlosser.guessUtteranceFromMorphemes({
  //     utterance: "",
  //     morphemes: "Kicha-nay-wa-n punqo-ta",
  //     allomorphs: "",
  //     gloss: "open-DES-1OM-3SG door-ACC",
  //     translation: "I feel like opening the door."
  //   });
  //   console.log(utterance);
  //   var lexicon = LexiconFactory({
  //     precedenceRelations: precedenceRelations,
  //     dbname: firstdb,
  //     element: document.getElementById("lexicon"),
  //     dontConnectWordBoundaries: !showWordBoundaries,
      // url: url+ "/" + seconddb
  //   });
  //   lexicon.bindToView();
  //   var renderFirstGraph = function() {
  //     var glosserElement = document.getElementById("glosser");
  //     glosserElement.innerHTML = "";
  //     var confidenceThreshold = document.getElementById("lexiconConfidenceThreshold").value /10;
  //     firstGlosser.visualizePrecedenceRelationsAsForceDirectedGraph(lexicon, glosserElement, !showWordBoundaries, confidenceThreshold);
  //   };
  //   rerenderIfWordBoundariesChange.push(renderFirstGraph);
  //   renderFirstGraph();
  // });

  var seconddb = "nemo814-group_data_entry_tutorial";
  var secondGlosser = new Glosser({
    pouchname: seconddb
  });
  secondGlosser.downloadPrecedenceRules(seconddb, url + "/" + seconddb + "/_design/lexicon/_view/morphemesPrecedenceContext?group=true", function(precedenceRelations) {
    var lexicon = LexiconFactory({
      precedenceRelations: precedenceRelations,
      dbname: seconddb,
      element: document.getElementById("lexicon2"),
      dontConnectWordBoundaries: !showWordBoundaries,
      url: url+ "/" + seconddb
    });
    lexicon.bindToView();

    var renderSecondGraph = function() {
      var glosserElement = document.getElementById("glosser2");
      glosserElement.innerHTML = "";
      var confidenceThreshold = document.getElementById("lexiconConfidenceThreshold").value /10;
      secondGlosser.visualizePrecedenceRelationsAsForceDirectedGraph(lexicon, glosserElement, !showWordBoundaries, confidenceThreshold);
    };
    rerenderIfWordBoundariesChange.push(renderSecondGraph);
    renderSecondGraph();
  });

};

var refreshButton = document.getElementById("refreshButton");
refreshButton.onclick = loadExamples;

var showGlosserAsGraph = document.getElementById("showGlosserAsGraph");
showGlosserAsGraph.onchange = function(){
  document.getElementById("glosser").hidden = !showGlosserAsGraph.checked;
  document.getElementById("glosser2").hidden = !showGlosserAsGraph.checked;
};

var showLexiconAsList = document.getElementById("showLexiconAsList");
showLexiconAsList.onchange = function(){
  document.getElementById("lexicon").hidden = !showLexiconAsList.checked;
  document.getElementById("lexicon2").hidden = !showLexiconAsList.checked;
};

loadExamples();
<commit_msg>changed to use http and cleaning corpus<commit_after>var loadExamples = function() {
  var graphWordBoundaries = document.getElementById("graphWordBoundaries");
  var showWordBoundaries;
  if (graphWordBoundaries && graphWordBoundaries.checked) {
    showWordBoundaries = true;
  } else {
    showWordBoundaries = false;
  }

  var rerenderIfWordBoundariesChange = [];
  graphWordBoundaries.onchange = function() {
    if (graphWordBoundaries && graphWordBoundaries.checked) {
      showWordBoundaries = true;
    } else {
      showWordBoundaries = false;
    }
    for (var functionToCall = 0; functionToCall < rerenderIfWordBoundariesChange.length; functionToCall++) {
      rerenderIfWordBoundariesChange[functionToCall]();
    }
  };

  var url = "http://localhost:5984";
  // var firstdb = "elisekm-eti3_data_tutorial";
  // var firstGlosser = new Glosser({
  //   pouchname: firstdb
  // });
  // firstGlosser.downloadPrecedenceRules(firstdb, url + "/" + firstdb + "/_design/lexicon/_view/morphemesPrecedenceContext?group=true", function(precedenceRelations) {
  //   var utterance = firstGlosser.guessUtteranceFromMorphemes({
  //     utterance: "",
  //     morphemes: "Kicha-nay-wa-n punqo-ta",
  //     allomorphs: "",
  //     gloss: "open-DES-1OM-3SG door-ACC",
  //     translation: "I feel like opening the door."
  //   });
  //   console.log(utterance);
  //   var lexicon = LexiconFactory({
  //     precedenceRelations: precedenceRelations,
  //     dbname: firstdb,
  //     element: document.getElementById("lexicon"),
  //     dontConnectWordBoundaries: !showWordBoundaries,
      // url: url+ "/" + seconddb
  //   });
  //   lexicon.bindToView();
  //   var renderFirstGraph = function() {
  //     var glosserElement = document.getElementById("glosser");
  //     glosserElement.innerHTML = "";
  //     var confidenceThreshold = document.getElementById("lexiconConfidenceThreshold").value /10;
  //     firstGlosser.visualizePrecedenceRelationsAsForceDirectedGraph(lexicon, glosserElement, !showWordBoundaries, confidenceThreshold);
  //   };
  //   rerenderIfWordBoundariesChange.push(renderFirstGraph);
  //   renderFirstGraph();
  // });

  var seconddb = "chuj-shared";
  var secondGlosser = new Glosser({
    pouchname: seconddb
  });
  secondGlosser.downloadPrecedenceRules(seconddb, url + "/" + seconddb + "/_design/lexicon/_view/morphemesPrecedenceContext?group=true", function(precedenceRelations) {
    var lexicon = LexiconFactory({
      precedenceRelations: precedenceRelations,
      dbname: seconddb,
      element: document.getElementById("lexicon2"),
      dontConnectWordBoundaries: !showWordBoundaries,
      url: url+ "/" + seconddb
    });
    lexicon.bindToView();

    var renderSecondGraph = function() {
      var glosserElement = document.getElementById("glosser2");
      glosserElement.innerHTML = "";
      var confidenceThreshold = document.getElementById("lexiconConfidenceThreshold").value /10;
      secondGlosser.visualizePrecedenceRelationsAsForceDirectedGraph(lexicon, glosserElement, !showWordBoundaries, confidenceThreshold);
    };
    rerenderIfWordBoundariesChange.push(renderSecondGraph);
    renderSecondGraph();
  });

};

var refreshButton = document.getElementById("refreshButton");
refreshButton.onclick = loadExamples;

var showGlosserAsGraph = document.getElementById("showGlosserAsGraph");
showGlosserAsGraph.onchange = function(){
  document.getElementById("glosser").hidden = !showGlosserAsGraph.checked;
  document.getElementById("glosser2").hidden = !showGlosserAsGraph.checked;
};

var showLexiconAsList = document.getElementById("showLexiconAsList");
showLexiconAsList.onchange = function(){
  document.getElementById("lexicon").hidden = !showLexiconAsList.checked;
  document.getElementById("lexicon2").hidden = !showLexiconAsList.checked;
};

loadExamples();
<|endoftext|>


<commit_before>Notifications = new Mongo.Collection('notifications');

// TODO add allow/deny rules
// user is owner of project - deny
// user is not logged in - deny

createRequestNotification = function(request) {
  check(request, {
    user: Object,
    project: Object,
    createdAt: Date,
    status: String,
    _id: String
  });

  Notifications.insert({
    userId: request.project.ownerId,
    requestingUserId: Meteor.userId(),
    text: Meteor.user().username + ' has requested to join ' + request.project.name,
    createdAt: new Date(),
    read: false,
    type: 'interactive',
    extraFields: {
      projectId: request.project.projectId,
      requestId: request._id
    }
  });
};

Meteor.methods({
  setNotificationAsRead: function(notification) {
    check(notification, String);
    console.log(notification);
    Notifications.update({ _id: notification }, {
      $set: {
        read: true
      }
    });
  }
});
<commit_msg>Remove console.log()<commit_after>Notifications = new Mongo.Collection('notifications');

// TODO add allow/deny rules
// user is owner of project - deny
// user is not logged in - deny

createRequestNotification = function(request) {
  check(request, {
    user: Object,
    project: Object,
    createdAt: Date,
    status: String,
    _id: String
  });

  Notifications.insert({
    userId: request.project.ownerId,
    requestingUserId: Meteor.userId(),
    text: Meteor.user().username + ' has requested to join ' + request.project.name,
    createdAt: new Date(),
    read: false,
    type: 'interactive',
    extraFields: {
      projectId: request.project.projectId,
      requestId: request._id
    }
  });
};

Meteor.methods({
  setNotificationAsRead: function(notification) {
    check(notification, String);
    Notifications.update({ _id: notification }, {
      $set: {
        read: true
      }
    });
  }
});
<|endoftext|>


<commit_before>var optimist = require('optimist');
var log = require('db-migrate-shared').log;

module.exports = function(internals, isModule) {

  var rc = require('rc');
  var deepExtend = require('deep-extend');

  internals.argv = optimist
    .default({
      verbose: false,
      table: 'migrations',
      'seeds-table': 'seeds',
      'force-exit': false,
      'sql-file': false,
      'non-transactional': false,
      config: internals.configFile || internals.cwd + '/database.json',
      'migrations-dir': internals.cwd + '/migrations',
      'vcseeder-dir': internals.cwd + '/VCSeeder',
      'staticseeder-dir': internals.cwd + '/Seeder',
      'ignore-completed-migrations': false
    })
    .usage(
      'Usage: db-migrate [up|down|reset|sync|create|db|transition] ' +
        '[[dbname/]migrationName|all] [options]'
    )
  .describe('env',
      'The environment to run the migrations under (dev, test, prod).')
    .alias('e', 'env')
    .string('e')

  .describe('migrations-dir', 'The directory containing your migration files.')
    .alias('m', 'migrations-dir')
    .string('m')

  .describe('count', 'Max number of migrations to run.')
    .alias('c', 'count')
    .string('c')

  .describe('dry-run', 'Prints the SQL but doesn\'t run it.')
    .boolean('dry-run')

  .describe('force-exit', 'Forcibly exit the migration process on completion.')
    .boolean('force-exit')

  .describe('verbose', 'Verbose mode.')
    .alias('v', 'verbose')
    .boolean('v')

  .alias('h', 'help')
    .alias('h', '?')
    .boolean('h')

  .describe('version', 'Print version info.')
    .alias('i', 'version')
    .boolean('version')

  .describe('config', 'Location of the database.json file.')
    .string('config')

  .describe('sql-file',
      'Automatically create two sql files for up and down statements in ' +
        '/sqls and generate the javascript code that loads them.'
    )
    .boolean('sql-file')

  .describe('coffee-file', 'Create a coffeescript migration file')
    .boolean('coffee-file')
    .describe('ignore-on-init',
      'Create files that will run only if ignore-on-init in the env is set ' +
        'to false (currently works onlt with SQL)'
    ).boolean('ignore-on-init')

  .describe('migration-table',
      'Set the name of the migration table, which stores the migration history.'
    )
    .alias('table', 'migration-table')
    .alias('t', 'table')
    .string('t')

  .describe('seeds-table',
      'Set the name of the seeds table, which stores the seed history.')
    .string('seeds-table')

  .describe('vcseeder-dir',
      'Set the path to the Version Controlled Seeder directory.')
    .string('vcseeder-dir')

  .describe('staticseeder-dir', 'Set the path to the Seeder directory.')
    .string('staticseeder-dir')

  .describe('non-transactional', 'Explicitly disable transactions')
    .boolean('non-transactional')

  .describe('ignore-completed-migrations', 'Start at the first migration')
    .boolean('ignore-completed-migrations')

  .describe('log-level', 'Set the log-level, for example sql|warn')
    .string('log-level');

  var plugins = internals.plugins;
  var plugin = plugins.hook('init:cli:config:hook');
  var _config = internals.argv.argv.config;

  if(plugin) {

    plugin.forEach(function(plugin) {

      var configs = plugin['init:cli:config:hook']();
      if(!configs) return;

      //hook not yet used, we look into migrating away from optimist first
      return;
    });
  }

  internals.argv = deepExtend(internals.argv.argv, rc('db-migrate', {}));
  internals.argv.rcconfig = internals.argv.config;
  internals.argv.config = _config;

  if (internals.argv.version) {
    console.log(internals.dbm.version);
    process.exit(0);
  }

  if (!isModule && (internals.argv.help || internals.argv._.length === 0)) {
    optimist.showHelp();
    process.exit(1);
  }

  if (internals.argv['log-level']) {

    log.setLogLevel(internals.argv['log-level']);
  }

  internals.ignoreCompleted = internals.argv['ignore-completed-migrations'];
  internals.migrationTable = internals.argv.table;
  internals.seedTable = internals.argv['seeds-table'];
  internals.matching = '';
  internals.verbose = internals.argv.verbose;
  global.verbose = internals.verbose;
  internals.notransactions = internals.argv['non-transactional'];
  internals.dryRun = internals.argv['dry-run'];
  global.dryRun = internals.dryRun;

  if (internals.dryRun) {
    log.info('dry run');
  }

};
<commit_msg>fix(args): dont parse when called as module<commit_after>var optimist = require('optimist');
var log = require('db-migrate-shared').log;

module.exports = function(internals, isModule) {

  var rc = require('rc');
  var deepExtend = require('deep-extend');
  var defaultConfig = {
    verbose: false,
    table: 'migrations',
    'seeds-table': 'seeds',
    'force-exit': false,
    'sql-file': false,
    'non-transactional': false,
    config: internals.configFile || internals.cwd + '/database.json',
    'migrations-dir': internals.cwd + '/migrations',
    'vcseeder-dir': internals.cwd + '/VCSeeder',
    'staticseeder-dir': internals.cwd + '/Seeder',
    'ignore-completed-migrations': false
  };

  if(!isModule) {

    internals.argv = optimist
      .default(defaultConfig)
      .usage(
        'Usage: db-migrate [up|down|reset|sync|create|db|transition] ' +
          '[[dbname/]migrationName|all] [options]'
      )
    .describe('env',
        'The environment to run the migrations under (dev, test, prod).')
      .alias('e', 'env')
      .string('e')

    .describe('migrations-dir', 'The directory containing your migration files.')
      .alias('m', 'migrations-dir')
      .string('m')

    .describe('count', 'Max number of migrations to run.')
      .alias('c', 'count')
      .string('c')

    .describe('dry-run', 'Prints the SQL but doesn\'t run it.')
      .boolean('dry-run')

    .describe('force-exit', 'Forcibly exit the migration process on completion.')
      .boolean('force-exit')

    .describe('verbose', 'Verbose mode.')
      .alias('v', 'verbose')
      .boolean('v')

    .alias('h', 'help')
      .alias('h', '?')
      .boolean('h')

    .describe('version', 'Print version info.')
      .alias('i', 'version')
      .boolean('version')

    .describe('config', 'Location of the database.json file.')
      .string('config')

    .describe('sql-file',
        'Automatically create two sql files for up and down statements in ' +
          '/sqls and generate the javascript code that loads them.'
      )
      .boolean('sql-file')

    .describe('coffee-file', 'Create a coffeescript migration file')
      .boolean('coffee-file')
      .describe('ignore-on-init',
        'Create files that will run only if ignore-on-init in the env is set ' +
          'to false (currently works onlt with SQL)'
      ).boolean('ignore-on-init')

    .describe('migration-table',
        'Set the name of the migration table, which stores the migration history.'
      )
      .alias('table', 'migration-table')
      .alias('t', 'table')
      .string('t')

    .describe('seeds-table',
        'Set the name of the seeds table, which stores the seed history.')
      .string('seeds-table')

    .describe('vcseeder-dir',
        'Set the path to the Version Controlled Seeder directory.')
      .string('vcseeder-dir')

    .describe('staticseeder-dir', 'Set the path to the Seeder directory.')
      .string('staticseeder-dir')

    .describe('non-transactional', 'Explicitly disable transactions')
      .boolean('non-transactional')

    .describe('ignore-completed-migrations', 'Start at the first migration')
      .boolean('ignore-completed-migrations')

    .describe('log-level', 'Set the log-level, for example sql|warn')
      .string('log-level');
  }
  else {

    internals.argv = {

      get argv() {
        return defaultConfig;
      }
    };
  }

  var plugins = internals.plugins;
  var plugin = plugins.hook('init:cli:config:hook');
  var _config = internals.argv.argv.config;

  if(plugin) {

    plugin.forEach(function(plugin) {

      var configs = plugin['init:cli:config:hook']();
      if(!configs) return;

      //hook not yet used, we look into migrating away from optimist first
      return;
    });
  }

  internals.argv = deepExtend(internals.argv.argv, rc('db-migrate', {}));
  internals.argv.rcconfig = internals.argv.config;
  internals.argv.config = _config;

  if (internals.argv.version) {
    console.log(internals.dbm.version);
    process.exit(0);
  }

  if (!isModule && (internals.argv.help || internals.argv._.length === 0)) {
    optimist.showHelp();
    process.exit(1);
  }

  if (internals.argv['log-level']) {

    log.setLogLevel(internals.argv['log-level']);
  }

  internals.ignoreCompleted = internals.argv['ignore-completed-migrations'];
  internals.migrationTable = internals.argv.table;
  internals.seedTable = internals.argv['seeds-table'];
  internals.matching = '';
  internals.verbose = internals.argv.verbose;
  global.verbose = internals.verbose;
  internals.notransactions = internals.argv['non-transactional'];
  internals.dryRun = internals.argv['dry-run'];
  global.dryRun = internals.dryRun;

  if (internals.dryRun) {
    log.info('dry run');
  }

};
<|endoftext|>


<commit_before>// @flow
import Icon from '@conveyal/woonerf/components/icon'
import message from '@conveyal/woonerf/message'
import memoize from 'lodash/memoize'
import React, {Component} from 'react'

import Collapsible from './collapsible'
import {Button} from './buttons'
import {Group} from './input'

type Props = {
  createVariant: (name: string) => void,
  deleteVariant: (index: number) => void,
  editVariantName: ({index: number, name: string}) => void,
  showVariant: number => void,
  variants: string[]
}

export default class Variants extends Component<void, Props, void> {
  _create = () => {
    const {createVariant, variants} = this.props
    const variantName = window.prompt(
      `${message('variant.enterName')}`,
      `${message('variant.name')} ${variants.length + 1}`
    )
    if (variantName) createVariant(variantName)
  }

  _deleteVariant = memoize((index: number) => () => {
    const {deleteVariant} = this.props
    if (
      window.confirm(message('variant.deleteConfirmation'))
    ) {
      deleteVariant(index)
    }
  })

  _editVariantName = memoize((index: number) => () => {
    const {editVariantName, variants} = this.props
    const variantName = variants[index]
    const newVariantName = window.prompt(message('variant.enterName'),
      variantName
    )
    if (newVariantName) editVariantName({index, name: newVariantName})
  })

  _showVariant = memoize((index: number) => () => {
    this.props.showVariant(index)
  })

  render () {
    const {variants} = this.props
    return (

        <Collapsible title={message('variant.plural')}>

{message('variant.description')}

          <Group>
            <Button
              block
              onClick={this._create}
              style='success'
              >
              <Icon type='plus' />{message('variant.createAction')}
            </Button>
          </Group>

                {message('variant.baseline')}

                  <Icon type='eye' />

                  <Icon type='lock' />

            {variants.map((name, index) => (
              <div className='Variant' key={`variant-${index}`}>

 {name}

                    <Icon type='eye' />

                    <Icon type='pencil' />

                  {index !== 0 &&

                    <Icon type='trash' />
                  }

              ))}

        </Collapsible>

    )
  }
}
<commit_msg>fix(modifications): hide in Baseline scenario<commit_after>// @flow
import Icon from '@conveyal/woonerf/components/icon'
import message from '@conveyal/woonerf/message'
import memoize from 'lodash/memoize'
import React, {Component} from 'react'

import Collapsible from './collapsible'
import {Button} from './buttons'
import {Group} from './input'

type Props = {
  createVariant: (name: string) => void,
  deleteVariant: (index: number) => void,
  editVariantName: ({index: number, name: string}) => void,
  showVariant: number => void,
  variants: string[]
}

export default class Variants extends Component<void, Props, void> {
  _create = () => {
    const {createVariant, variants} = this.props
    const variantName = window.prompt(
      `${message('variant.enterName')}`,
      `${message('variant.name')} ${variants.length + 1}`
    )
    if (variantName) createVariant(variantName)
  }

  _deleteVariant = memoize((index: number) => () => {
    const {deleteVariant} = this.props
    if (
      window.confirm(message('variant.deleteConfirmation'))
    ) {
      deleteVariant(index)
    }
  })

  _editVariantName = memoize((index: number) => () => {
    const {editVariantName, variants} = this.props
    const variantName = variants[index]
    const newVariantName = window.prompt(message('variant.enterName'),
      variantName
    )
    if (newVariantName) editVariantName({index, name: newVariantName})
  })

  _showVariant = memoize((index: number) => () => {
    this.props.showVariant(index)
  })

  render () {
    const {variants} = this.props
    return (

        <Collapsible title={message('variant.plural')}>

{message('variant.description')}

          <Group>
            <Button
              block
              onClick={this._create}
              style='success'
              >
              <Icon type='plus' />{message('variant.createAction')}
            </Button>
          </Group>

                {message('variant.baseline')}

                  <Icon type='eye' />

                  <Icon type='lock' />

            {variants.map((name, index) => (
              <div className='Variant' key={`variant-${index}`}>

 {name}

                    <Icon type='eye' />

                    <Icon type='pencil' />

                  {index !== 0 &&

                    <Icon type='trash' />
                  }

              ))}

        </Collapsible>

    )
  }
}
<|endoftext|>


<commit_before>//= require date_range_selector/vendor/daterangepicker
//= require date_range_selector/vendor/moment
window.DateRangeSelector = {};
<commit_msg>Fix Javascript files order<commit_after>//= require date_range_selector/vendor/moment
//= require date_range_selector/vendor/daterangepicker
window.DateRangeSelector = {};
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import {injectIntl} from 'react-intl'
import {react} from 'tocco-util'

import {StyledEditableWrapper} from '../StyledEditableValue'
import {parseLocalePlaceholder, convertStringToNumber} from '../utils'
import StyledNumberEdit from './StyledNumberEdit'

export const calculateMaxValue = (prePointDigits, postPointDigits, maxValue) => {
  if (prePointDigits) {
    const calculatedMaxValue = 10 ** prePointDigits - (postPointDigits ? 1 / 10 ** postPointDigits : 1)
    return maxValue && maxValue > calculatedMaxValue ? maxValue : calculatedMaxValue
  }

  return maxValue
}

const getPreDecimalPositions = number => (number !== 0 ? Math.ceil(Math.log10(Math.abs(number) + 1)) : 1)

const isNumber = number => number !== null && number !== undefined && !isNaN(parseFloat(number))

export const checkValueRange = (minValue, maxValue, value) => {
  if (!isNumber(value)) {
    return true
  }

  if (isNumber(maxValue) && value > maxValue) {
    return false
  }

  if (isNumber(minValue) && value < minValue) {
    return false
  }

  return true
}

export const isAllowedValue =
  (minValue, maxValue) =>
  ({floatValue}) => {
    if (getPreDecimalPositions(floatValue) < getPreDecimalPositions(minValue)) {
      return true
    }

    return checkValueRange(minValue, maxValue, floatValue)
  }

const NumberEdit = props => {
  const {thousandSeparator, decimalSeparator} = parseLocalePlaceholder(props.intl.locale)
  const {
    prePointDigits,
    postPointDigits,
    minValue,
    maxValue,
    allowNegative,
    fixedDecimalScale,
    suffix,
    prefix,
    format
  } = props.options || {}

  const calculatedMaxValue = calculateMaxValue(prePointDigits, postPointDigits, maxValue)
  const numberFormatOptions = {
    isAllowed: isAllowedValue(minValue, calculatedMaxValue),
    allowNegative: !!allowNegative,
    ...(!isNaN(postPointDigits) ? {decimalScale: postPointDigits} : {}),
    fixedDecimalScale: !!fixedDecimalScale
  }

  const handleChange = values => {
    if (props.onChange && checkValueRange(minValue, calculatedMaxValue, values.floatValue)) {
      props.onChange(values.floatValue !== undefined ? values.floatValue : null)
    }
  }

  const handleBlur = event => {
    const valueBeforeBlur = convertStringToNumber(event.target.value)
    if (props.onChange && !checkValueRange(minValue, calculatedMaxValue, valueBeforeBlur)) {
      // if we reach this, then onChange was never called for the last entered value, so just remove it
      event.target.value = null
    }
  }

  return (
    <StyledEditableWrapper immutable={props.immutable}>
      <StyledNumberEdit
        decimalSeparator={decimalSeparator}
        disabled={props.immutable}
        id={props.id}
        isNumericString={true}
        name={props.name}
        onValueChange={handleChange}
        immutable={props.immutable}
        thousandSeparator={thousandSeparator}
        value={props.value}
        suffix={suffix}
        prefix={prefix}
        {...numberFormatOptions}
        format={format}
        onBlur={handleBlur}
      />
    </StyledEditableWrapper>
  )
}

NumberEdit.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.number,
  name: PropTypes.string,
  id: PropTypes.string,
  intl: PropTypes.object,
  immutable: PropTypes.bool,
  options: PropTypes.shape({
    allowNegative: PropTypes.bool,
    fixedDecimalScale: PropTypes.bool,
    postPointDigits: PropTypes.number,
    prePointDigits: PropTypes.number,
    minValue: PropTypes.number,
    maxValue: PropTypes.number,
    suffix: PropTypes.string,
    prefix: PropTypes.string,
    format: PropTypes.string
  })
}

export default injectIntl(react.Debouncer(NumberEdit, 800))
<commit_msg>feat(tocco-ui): show from and to placeholders on number ranges<commit_after>import PropTypes from 'prop-types'
import {injectIntl} from 'react-intl'
import {react} from 'tocco-util'

import {StyledEditableWrapper} from '../StyledEditableValue'
import {parseLocalePlaceholder, convertStringToNumber} from '../utils'
import StyledNumberEdit from './StyledNumberEdit'

export const calculateMaxValue = (prePointDigits, postPointDigits, maxValue) => {
  if (prePointDigits) {
    const calculatedMaxValue = 10 ** prePointDigits - (postPointDigits ? 1 / 10 ** postPointDigits : 1)
    return maxValue && maxValue > calculatedMaxValue ? maxValue : calculatedMaxValue
  }

  return maxValue
}

const getPreDecimalPositions = number => (number !== 0 ? Math.ceil(Math.log10(Math.abs(number) + 1)) : 1)

const isNumber = number => number !== null && number !== undefined && !isNaN(parseFloat(number))

export const checkValueRange = (minValue, maxValue, value) => {
  if (!isNumber(value)) {
    return true
  }

  if (isNumber(maxValue) && value > maxValue) {
    return false
  }

  if (isNumber(minValue) && value < minValue) {
    return false
  }

  return true
}

export const isAllowedValue =
  (minValue, maxValue) =>
  ({floatValue}) => {
    if (getPreDecimalPositions(floatValue) < getPreDecimalPositions(minValue)) {
      return true
    }

    return checkValueRange(minValue, maxValue, floatValue)
  }

const NumberEdit = props => {
  const {thousandSeparator, decimalSeparator} = parseLocalePlaceholder(props.intl.locale)
  const {
    prePointDigits,
    postPointDigits,
    minValue,
    maxValue,
    allowNegative,
    fixedDecimalScale,
    suffix,
    prefix,
    format
  } = props.options || {}

  const calculatedMaxValue = calculateMaxValue(prePointDigits, postPointDigits, maxValue)
  const numberFormatOptions = {
    isAllowed: isAllowedValue(minValue, calculatedMaxValue),
    allowNegative: !!allowNegative,
    ...(!isNaN(postPointDigits) ? {decimalScale: postPointDigits} : {}),
    fixedDecimalScale: !!fixedDecimalScale
  }

  const handleChange = values => {
    if (props.onChange && checkValueRange(minValue, calculatedMaxValue, values.floatValue)) {
      props.onChange(values.floatValue !== undefined ? values.floatValue : null)
    }
  }

  const handleBlur = event => {
    const valueBeforeBlur = convertStringToNumber(event.target.value)
    if (props.onChange && !checkValueRange(minValue, calculatedMaxValue, valueBeforeBlur)) {
      // if we reach this, then onChange was never called for the last entered value, so just remove it
      event.target.value = null
    }
  }

  return (
    <StyledEditableWrapper immutable={props.immutable}>
      <StyledNumberEdit
        decimalSeparator={decimalSeparator}
        disabled={props.immutable}
        id={props.id}
        isNumericString={true}
        name={props.name}
        onValueChange={handleChange}
        immutable={props.immutable}
        thousandSeparator={thousandSeparator}
        value={props.value}
        suffix={suffix}
        prefix={prefix}
        {...numberFormatOptions}
        format={format}
        placeholder={props.placeholder}
        onBlur={handleBlur}
      />
    </StyledEditableWrapper>
  )
}

NumberEdit.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.number,
  name: PropTypes.string,
  id: PropTypes.string,
  placeholder: PropTypes.string,
  intl: PropTypes.object,
  immutable: PropTypes.bool,
  options: PropTypes.shape({
    allowNegative: PropTypes.bool,
    fixedDecimalScale: PropTypes.bool,
    postPointDigits: PropTypes.number,
    prePointDigits: PropTypes.number,
    minValue: PropTypes.number,
    maxValue: PropTypes.number,
    suffix: PropTypes.string,
    prefix: PropTypes.string,
    format: PropTypes.string
  })
}

export default injectIntl(react.Debouncer(NumberEdit, 800))
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : graphModel.js
* Module : Lib::DataTier::GraphModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-12   Samuele Zanella    Initial code
* =========================================================
*/

var LegendModel = require('./legendModel.js');

function GraphModel(params) {
	if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
		console.log('Error: 352');
		return;
	}

	this._ID=params.ID;
	this._title='';
	this._type='';
	this._height=400;
	this._width=500;
	this._enableLegend=false;
	this._legend= new LegendModel();
	this.updateBaseProperties(params);
}

GraphModel.prototype.getProperties = function(){
	return {
		ID: this._ID,
		title: this._title,
		type: this._type,
		height: this._height,
		width: this._width,
		enableLegend: this._enableLegend,
		legend: this._legend.getProperties()
	};
};

GraphModel.prototype.updateBaseProperties = function(params) {
	if (params !== undefined){
		//ID field can't be modified
		var prop={};
		if(params.title!==undefined && typeof params.title === 'string'){
			this._title=prop.title=params.title;
		}

		if(params.type!==undefined && typeof params.type === 'string' && (params.type==='BarChart' || params.type==='LineChart' || params.type==='MapChart' || params.type==='Table')){
			this._type=prop.type=params.type;
		}

		if(params.height!==undefined && typeof params.height === 'number' && params.height >= 0){
			this._height=prop.height=params.height;
		}

		if(params.width!==undefined && typeof params.width === 'number' && params.width >= 0){
			this._width=prop.width=params.width;
		}

		if(params.enableLegend!==undefined && typeof params.enableLegend === 'boolean'){
			this._enableLegend=prop.enableLegend=params.enableLegend;
		}

		if(params.legend!==undefined){
			this._legend.updateProperties(params.legend);
			prop.legend=this._legend.getProperties();
		}
		return prop;
	}
	return 351;
};

module.exports = GraphModel;
<commit_msg>restore to 0 as default dimension<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : graphModel.js
* Module : Lib::DataTier::GraphModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-12   Samuele Zanella    Initial code
* =========================================================
*/

var LegendModel = require('./legendModel.js');

function GraphModel(params) {
	if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
		console.log('Error: 352');
		return;
	}

	this._ID=params.ID;
	this._title='';
	this._type='';
	this._height=0;
	this._width=0;
	this._enableLegend=false;
	this._legend= new LegendModel();
	this.updateBaseProperties(params);
}

GraphModel.prototype.getProperties = function(){
	return {
		ID: this._ID,
		title: this._title,
		type: this._type,
		height: this._height,
		width: this._width,
		enableLegend: this._enableLegend,
		legend: this._legend.getProperties()
	};
};

GraphModel.prototype.updateBaseProperties = function(params) {
	if (params !== undefined){
		//ID field can't be modified
		var prop={};
		if(params.title!==undefined && typeof params.title === 'string'){
			this._title=prop.title=params.title;
		}

		if(params.type!==undefined && typeof params.type === 'string' && (params.type==='BarChart' || params.type==='LineChart' || params.type==='MapChart' || params.type==='Table')){
			this._type=prop.type=params.type;
		}

		if(params.height!==undefined && typeof params.height === 'number' && params.height >= 0){
			this._height=prop.height=params.height;
		}

		if(params.width!==undefined && typeof params.width === 'number' && params.width >= 0){
			this._width=prop.width=params.width;
		}

		if(params.enableLegend!==undefined && typeof params.enableLegend === 'boolean'){
			this._enableLegend=prop.enableLegend=params.enableLegend;
		}

		if(params.legend!==undefined){
			this._legend.updateProperties(params.legend);
			prop.legend=this._legend.getProperties();
		}
		return prop;
	}
	return 351;
};

module.exports = GraphModel;
<|endoftext|>


<commit_before>// This code is largely borrowed from:
// https://github.com/missive/emoji-mart/blob/5f2ffcc/src/utils/emoji-index.js

import data from './emoji_mart_data_light';
import { getData, getSanitizedData, intersect } from './emoji_utils';

let originalPool = {};
let index = {};
let emojisList = {};
let emoticonsList = {};
let customEmojisList = [];

for (let emoji in data.emojis) {
  let emojiData = data.emojis[emoji];
  let { short_names, emoticons } = emojiData;
  let id = short_names[0];

  if (emoticons) {
    emoticons.forEach(emoticon => {
      if (emoticonsList[emoticon]) {
        return;
      }

      emoticonsList[emoticon] = id;
    });
  }

  emojisList[id] = getSanitizedData(id);
  originalPool[id] = emojiData;
}

function clearCustomEmojis(pool) {
  customEmojisList.forEach((emoji) => {
    let emojiId = emoji.id || emoji.short_names[0];

    delete pool[emojiId];
    delete emojisList[emojiId];
  });
}

function addCustomToPool(custom, pool) {
  if (customEmojisList.length) clearCustomEmojis(pool);

  custom.forEach((emoji) => {
    let emojiId = emoji.id || emoji.short_names[0];

    if (emojiId && !pool[emojiId]) {
      pool[emojiId] = getData(emoji);
      emojisList[emojiId] = getSanitizedData(emoji);
    }
  });

  customEmojisList = custom;
  index = {};
}

function search(value, { emojisToShowFilter, maxResults, include, exclude, custom } = {}) {
  if (custom !== undefined) {
    if (customEmojisList !== custom)
      addCustomToPool(custom, originalPool);
  } else {
    custom = [];
  }

  maxResults = maxResults || 75;
  include = include || [];
  exclude = exclude || [];

  let results = null,
    pool = originalPool;

  if (value.length) {
    if (value === '-' || value === '-1') {
      return [emojisList['-1']];
    }

    let values = value.toLowerCase().split(/[\s|,|\-|_]+/),
      allResults = [];

    if (values.length > 2) {
      values = [values[0], values[1]];
    }

    if (include.length || exclude.length) {
      pool = {};

      data.categories.forEach(category => {
        let isIncluded = include && include.length ? include.indexOf(category.name.toLowerCase()) > -1 : true;
        let isExcluded = exclude && exclude.length ? exclude.indexOf(category.name.toLowerCase()) > -1 : false;
        if (!isIncluded || isExcluded) {
          return;
        }

        category.emojis.forEach(emojiId => pool[emojiId] = data.emojis[emojiId]);
      });

      if (custom.length) {
        let customIsIncluded = include && include.length ? include.indexOf('custom') > -1 : true;
        let customIsExcluded = exclude && exclude.length ? exclude.indexOf('custom') > -1 : false;
        if (customIsIncluded && !customIsExcluded) {
          addCustomToPool(custom, pool);
        }
      }
    }

    allResults = values.map((value) => {
      let aPool = pool,
        aIndex = index,
        length = 0;

      for (let charIndex = 0; charIndex < value.length; charIndex++) {
        const char = value[charIndex];
        length++;

        aIndex[char] = aIndex[char] || {};
        aIndex = aIndex[char];

        if (!aIndex.results) {
          let scores = {};

          aIndex.results = [];
          aIndex.pool = {};

          for (let id in aPool) {
            let emoji = aPool[id],
              { search } = emoji,
              sub = value.substr(0, length),
              subIndex = search.indexOf(sub);

            if (subIndex !== -1) {
              let score = subIndex + 1;
              if (sub === id) score = 0;

              aIndex.results.push(emojisList[id]);
              aIndex.pool[id] = emoji;

              scores[id] = score;
            }
          }

          aIndex.results.sort((a, b) => {
            let aScore = scores[a.id],
              bScore = scores[b.id];

            return aScore - bScore;
          });
        }

        aPool = aIndex.pool;
      }

      return aIndex.results;
    }).filter(a => a);

    if (allResults.length > 1) {
      results = intersect.apply(null, allResults);
    } else if (allResults.length) {
      results = allResults[0];
    } else {
      results = [];
    }
  }

  if (results) {
    if (emojisToShowFilter) {
      results = results.filter((result) => emojisToShowFilter(data.emojis[result.id]));
    }

    if (results && results.length > maxResults) {
      results = results.slice(0, maxResults);
    }
  }

  return results;
}

export { search };
<commit_msg>When searching for an emoji with multiple separators, consider the full input (#9124)<commit_after>// This code is largely borrowed from:
// https://github.com/missive/emoji-mart/blob/5f2ffcc/src/utils/emoji-index.js

import data from './emoji_mart_data_light';
import { getData, getSanitizedData, uniq, intersect } from './emoji_utils';

let originalPool = {};
let index = {};
let emojisList = {};
let emoticonsList = {};
let customEmojisList = [];

for (let emoji in data.emojis) {
  let emojiData = data.emojis[emoji];
  let { short_names, emoticons } = emojiData;
  let id = short_names[0];

  if (emoticons) {
    emoticons.forEach(emoticon => {
      if (emoticonsList[emoticon]) {
        return;
      }

      emoticonsList[emoticon] = id;
    });
  }

  emojisList[id] = getSanitizedData(id);
  originalPool[id] = emojiData;
}

function clearCustomEmojis(pool) {
  customEmojisList.forEach((emoji) => {
    let emojiId = emoji.id || emoji.short_names[0];

    delete pool[emojiId];
    delete emojisList[emojiId];
  });
}

function addCustomToPool(custom, pool) {
  if (customEmojisList.length) clearCustomEmojis(pool);

  custom.forEach((emoji) => {
    let emojiId = emoji.id || emoji.short_names[0];

    if (emojiId && !pool[emojiId]) {
      pool[emojiId] = getData(emoji);
      emojisList[emojiId] = getSanitizedData(emoji);
    }
  });

  customEmojisList = custom;
  index = {};
}

function search(value, { emojisToShowFilter, maxResults, include, exclude, custom } = {}) {
  if (custom !== undefined) {
    if (customEmojisList !== custom)
      addCustomToPool(custom, originalPool);
  } else {
    custom = [];
  }

  maxResults = maxResults || 75;
  include = include || [];
  exclude = exclude || [];

  let results = null,
    pool = originalPool;

  if (value.length) {
    if (value === '-' || value === '-1') {
      return [emojisList['-1']];
    }

    let values = value.toLowerCase().split(/[\s|,|\-|_]+/),
      allResults = [];

    if (values.length > 2) {
      values = [values[0], values[1]];
    }

    if (include.length || exclude.length) {
      pool = {};

      data.categories.forEach(category => {
        let isIncluded = include && include.length ? include.indexOf(category.name.toLowerCase()) > -1 : true;
        let isExcluded = exclude && exclude.length ? exclude.indexOf(category.name.toLowerCase()) > -1 : false;
        if (!isIncluded || isExcluded) {
          return;
        }

        category.emojis.forEach(emojiId => pool[emojiId] = data.emojis[emojiId]);
      });

      if (custom.length) {
        let customIsIncluded = include && include.length ? include.indexOf('custom') > -1 : true;
        let customIsExcluded = exclude && exclude.length ? exclude.indexOf('custom') > -1 : false;
        if (customIsIncluded && !customIsExcluded) {
          addCustomToPool(custom, pool);
        }
      }
    }

    const searchValue = (value) => {
      let aPool = pool,
        aIndex = index,
        length = 0;

      for (let charIndex = 0; charIndex < value.length; charIndex++) {
        const char = value[charIndex];
        length++;

        aIndex[char] = aIndex[char] || {};
        aIndex = aIndex[char];

        if (!aIndex.results) {
          let scores = {};

          aIndex.results = [];
          aIndex.pool = {};

          for (let id in aPool) {
            let emoji = aPool[id],
              { search } = emoji,
              sub = value.substr(0, length),
              subIndex = search.indexOf(sub);

            if (subIndex !== -1) {
              let score = subIndex + 1;
              if (sub === id) score = 0;

              aIndex.results.push(emojisList[id]);
              aIndex.pool[id] = emoji;

              scores[id] = score;
            }
          }

          aIndex.results.sort((a, b) => {
            let aScore = scores[a.id],
              bScore = scores[b.id];

            return aScore - bScore;
          });
        }

        aPool = aIndex.pool;
      }

      return aIndex.results;
    };

    if (values.length > 1) {
      results = searchValue(value);
    } else {
      results = [];
    }

    allResults = values.map(searchValue).filter(a => a);

    if (allResults.length > 1) {
      allResults = intersect.apply(null, allResults);
    } else if (allResults.length) {
      allResults = allResults[0];
    }

    results = uniq(results.concat(allResults));
  }

  if (results) {
    if (emojisToShowFilter) {
      results = results.filter((result) => emojisToShowFilter(data.emojis[result.id]));
    }

    if (results && results.length > maxResults) {
      results = results.slice(0, maxResults);
    }
  }

  return results;
}

export { search };
<|endoftext|>


<commit_before>var global = (typeof window !== 'undefined') ? window : {};

export default function(scope) {
  return(global.ENV || {})[scope] || {};
}
<commit_msg>use Ember.get to read config<commit_after>var global = (typeof window !== 'undefined') ? window : {};

export default function(scope) {
  return Ember.get(global, 'ENV.' + scope) || {};
}
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const moment = require('moment');
const inherits = require('../../utils/inherits');

module.exports = BaseTypes => {
  const warn = BaseTypes.ABSTRACT.warn.bind(undefined, 'https://msdn.microsoft.com/en-us/library/ms187752%28v=sql.110%29.aspx');

  /**
   * types: [hex, ...]
   * @see hex here https://github.com/tediousjs/tedious/blob/master/src/data-type.js
   */

  BaseTypes.DATE.types.mssql = [43];
  BaseTypes.STRING.types.mssql = [231, 173];
  BaseTypes.CHAR.types.mssql = [175];
  BaseTypes.TEXT.types.mssql = false;
  // https://msdn.microsoft.com/en-us/library/ms187745(v=sql.110).aspx
  BaseTypes.TINYINT.types.mssql = [30];
  BaseTypes.SMALLINT.types.mssql = [34];
  BaseTypes.MEDIUMINT.types.mssql = false;
  BaseTypes.INTEGER.types.mssql = [38];
  BaseTypes.BIGINT.types.mssql = false;
  BaseTypes.FLOAT.types.mssql = [109];
  BaseTypes.TIME.types.mssql = [41];
  BaseTypes.DATEONLY.types.mssql = [40];
  BaseTypes.BOOLEAN.types.mssql = [104];
  BaseTypes.BLOB.types.mssql = [165];
  BaseTypes.DECIMAL.types.mssql = [106];
  BaseTypes.UUID.types.mssql = false;
  BaseTypes.ENUM.types.mssql = false;
  BaseTypes.REAL.types.mssql = [109];
  BaseTypes.DOUBLE.types.mssql = [109];
  // BaseTypes.GEOMETRY.types.mssql = [240]; // not yet supported
  BaseTypes.GEOMETRY.types.mssql = false;
  BaseTypes.JSON.types.mssql = false;

  function BLOB(length) {
    if (!(this instanceof BLOB)) return new BLOB(length);
    BaseTypes.BLOB.apply(this, arguments);
  }
  inherits(BLOB, BaseTypes.BLOB);

  BLOB.prototype.toSql = function toSql() {
    if (this._length) {
      if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
        warn('MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.');
        return 'VARBINARY(256)';
      }
      warn('MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.');
    }
    return 'VARBINARY(MAX)';
  };

  BLOB.prototype._hexify = function _hexify(hex) {
    return '0x' + hex;
  };

  function STRING(length, binary) {
    if (!(this instanceof STRING)) return new STRING(length, binary);
    BaseTypes.STRING.apply(this, arguments);
  }
  inherits(STRING, BaseTypes.STRING);

  function JSONTYPE() {
    if (!(this instanceof JSONTYPE)) return new JSONTYPE();
    BaseTypes.JSON.apply(this, arguments);
  }
  inherits(JSONTYPE, BaseTypes.JSON);

  // /!\ JSON type don't exist in metadata of column,
  // thus we can't use "parse"
  // JSONTYPE.parse = function parse(data) {
  //   return JSON.parse(data);
  // };

  JSONTYPE.prototype.stringify = function(data) {
    if (data && typeof data === 'string') {
      return data;
    } else {
      return JSON.stringify(data);
    }
  }

  /** "parse" data in set */
  JSONTYPE.prototype.parseInSet = function(data) {
    if (data && typeof data === 'string') {
      try {
        return JSON.parse(data);
      } catch (error) {
        //erreur lors du parse, soit JSON malformé soit une string => pas besoin de parse on l'a renvoie direct
        return data;
      }

    } else {
      return data;
    }
  }

  JSONTYPE.prototype.toSql = function toSql() {
    return 'NVARCHAR(MAX)';
  };

  STRING.prototype.toSql = function toSql() {
    if (!this._binary) {
      return 'NVARCHAR(' + this._length + ')';
    } else {
      return 'BINARY(' + this._length + ')';
    }
  };

  STRING.prototype.escape = false;
  STRING.prototype._stringify = function _stringify(value, options) {
    if (this._binary) {
      return BLOB.prototype._stringify(value);
    } else {
      return options.escape(value);
    }
  };

  function TEXT(length) {
    if (!(this instanceof TEXT)) return new TEXT(length);
    BaseTypes.TEXT.apply(this, arguments);
  }
  inherits(TEXT, BaseTypes.TEXT);

  TEXT.prototype.toSql = function toSql() {
    // TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.
    // Using unicode is just future proof
    if (this._length) {
      if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
        warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');
        return 'NVARCHAR(256)';
      }
      warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');
    }
    return 'NVARCHAR(MAX)';
  };

  function BOOLEAN() {
    if (!(this instanceof BOOLEAN)) return new BOOLEAN();
    BaseTypes.BOOLEAN.apply(this, arguments);
  }
  inherits(BOOLEAN, BaseTypes.BOOLEAN);

  BOOLEAN.prototype.toSql = function toSql() {
    return 'BIT';
  };

  function UUID() {
    if (!(this instanceof UUID)) return new UUID();
    BaseTypes.UUID.apply(this, arguments);
  }
  inherits(UUID, BaseTypes.UUID);

  UUID.prototype.toSql = function toSql() {
    return 'CHAR(36)';
  };

  function NOW() {
    if (!(this instanceof NOW)) return new NOW();
    BaseTypes.NOW.apply(this, arguments);
  }
  inherits(NOW, BaseTypes.NOW);

  NOW.prototype.toSql = function toSql() {
    return 'GETDATE()';
  };

  function DATE(length) {
    if (!(this instanceof DATE)) return new DATE(length);
    BaseTypes.DATE.apply(this, arguments);
  }
  inherits(DATE, BaseTypes.DATE);

  DATE.prototype.toSql = function toSql() {
    return 'DATETIMEOFFSET';
  };

  /**
   * If the dates are not DateTimeOffset we set them like this
   * */
  if (process.env.SEQ_MSSQL_LEGACY_DATE && process.env.SEQ_MSSQL_LEGACY_DATE.trim() === 'true') {
    DATE.prototype._stringify = function(date, options) {

      date = this._applyTimezone(date, options);

      //On ne passe pas le timezone comme sequelize tente de le faire (reprise https://github.com/sequelize/sequelize/blob/v3/lib/dialects/mssql/data-types.js)
      return date.format('YYYY-MM-DD HH:mm:ss.SSS');
    };
  }

  function DATEONLY() {
    if (!(this instanceof DATEONLY)) return new DATEONLY();
    BaseTypes.DATEONLY.apply(this, arguments);
  }
  inherits(DATEONLY, BaseTypes.DATEONLY);

  DATEONLY.parse = function(value) {
    return moment(value).format('YYYY-MM-DD');
  };

  function INTEGER(length) {
    if (!(this instanceof INTEGER)) return new INTEGER(length);
    BaseTypes.INTEGER.apply(this, arguments);

    // MSSQL does not support any options for integer
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(INTEGER, BaseTypes.INTEGER);

  function TINYINT(length) {
    if (!(this instanceof TINYINT)) return new TINYINT(length);
    BaseTypes.TINYINT.apply(this, arguments);

    // MSSQL does not support any options for tinyint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support TINYINT with options. Plain `TINYINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(TINYINT, BaseTypes.TINYINT);

  function SMALLINT(length) {
    if (!(this instanceof SMALLINT)) return new SMALLINT(length);
    BaseTypes.SMALLINT.apply(this, arguments);

    // MSSQL does not support any options for smallint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support SMALLINT with options. Plain `SMALLINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(SMALLINT, BaseTypes.SMALLINT);

  function BIGINT(length) {
    if (!(this instanceof BIGINT)) return new BIGINT(length);
    BaseTypes.BIGINT.apply(this, arguments);

    // MSSQL does not support any options for bigint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(BIGINT, BaseTypes.BIGINT);

  function REAL(length, decimals) {
    if (!(this instanceof REAL)) return new REAL(length, decimals);
    BaseTypes.REAL.apply(this, arguments);

    // MSSQL does not support any options for real
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(REAL, BaseTypes.REAL);

  function FLOAT(length, decimals) {
    if (!(this instanceof FLOAT)) return new FLOAT(length, decimals);
    BaseTypes.FLOAT.apply(this, arguments);

    // MSSQL does only support lengths as option.
    // Values between 1-24 result in 7 digits precision (4 bytes storage size)
    // Values between 25-53 result in 15 digits precision (8 bytes storage size)
    // If decimals are provided remove these and print a warning
    if (this._decimals) {
      warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
    }
    if (this._unsigned) {
      warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
      this._unsigned = undefined;
    }
    if (this._zerofill) {
      warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
      this._zerofill = undefined;
    }
  }
  inherits(FLOAT, BaseTypes.FLOAT);

  function ENUM() {
    if (!(this instanceof ENUM)) {
      const obj = Object.create(ENUM.prototype);
      ENUM.apply(obj, arguments);
      return obj;
    }
    BaseTypes.ENUM.apply(this, arguments);
  }
  inherits(ENUM, BaseTypes.ENUM);

  ENUM.prototype.toSql = function toSql() {
    return 'VARCHAR(255)';
  };

  const exports = {
    BLOB,
    BOOLEAN,
    ENUM,
    STRING,
    UUID,
    DATE,
    DATEONLY,
    NOW,
    TINYINT,
    SMALLINT,
    INTEGER,
    BIGINT,
    REAL,
    FLOAT,
    TEXT,
    JSON : JSONTYPE
  };

  _.forIn(exports, (DataType, key) => {
    if (!DataType.key) DataType.key = key;
    if (!DataType.extend) {
      DataType.extend = function extend(oldType) {
        return new DataType(oldType.options);
      };
    }
  });

  return exports;
};
<commit_msg>fix(data-type.js): mssql ;<commit_after>'use strict';

const _ = require('lodash');
const moment = require('moment');
const inherits = require('../../utils/inherits');

module.exports = BaseTypes => {
  const warn = BaseTypes.ABSTRACT.warn.bind(undefined, 'https://msdn.microsoft.com/en-us/library/ms187752%28v=sql.110%29.aspx');

  /**
   * types: [hex, ...]
   * @see hex here https://github.com/tediousjs/tedious/blob/master/src/data-type.js
   */

  BaseTypes.DATE.types.mssql = [43];
  BaseTypes.STRING.types.mssql = [231, 173];
  BaseTypes.CHAR.types.mssql = [175];
  BaseTypes.TEXT.types.mssql = false;
  // https://msdn.microsoft.com/en-us/library/ms187745(v=sql.110).aspx
  BaseTypes.TINYINT.types.mssql = [30];
  BaseTypes.SMALLINT.types.mssql = [34];
  BaseTypes.MEDIUMINT.types.mssql = false;
  BaseTypes.INTEGER.types.mssql = [38];
  BaseTypes.BIGINT.types.mssql = false;
  BaseTypes.FLOAT.types.mssql = [109];
  BaseTypes.TIME.types.mssql = [41];
  BaseTypes.DATEONLY.types.mssql = [40];
  BaseTypes.BOOLEAN.types.mssql = [104];
  BaseTypes.BLOB.types.mssql = [165];
  BaseTypes.DECIMAL.types.mssql = [106];
  BaseTypes.UUID.types.mssql = false;
  BaseTypes.ENUM.types.mssql = false;
  BaseTypes.REAL.types.mssql = [109];
  BaseTypes.DOUBLE.types.mssql = [109];
  // BaseTypes.GEOMETRY.types.mssql = [240]; // not yet supported
  BaseTypes.GEOMETRY.types.mssql = false;
  BaseTypes.JSON.types.mssql = false;

  function BLOB(length) {
    if (!(this instanceof BLOB)) return new BLOB(length);
    BaseTypes.BLOB.apply(this, arguments);
  }
  inherits(BLOB, BaseTypes.BLOB);

  BLOB.prototype.toSql = function toSql() {
    if (this._length) {
      if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
        warn('MSSQL does not support BLOB with the `length` = `tiny` option. `VARBINARY(256)` will be used instead.');
        return 'VARBINARY(256)';
      }
      warn('MSSQL does not support BLOB with the `length` option. `VARBINARY(MAX)` will be used instead.');
    }
    return 'VARBINARY(MAX)';
  };

  BLOB.prototype._hexify = function _hexify(hex) {
    return '0x' + hex;
  };

  function STRING(length, binary) {
    if (!(this instanceof STRING)) return new STRING(length, binary);
    BaseTypes.STRING.apply(this, arguments);
  }
  inherits(STRING, BaseTypes.STRING);

  function JSONTYPE() {
    if (!(this instanceof JSONTYPE)) return new JSONTYPE();
    BaseTypes.JSON.apply(this, arguments);
  }
  inherits(JSONTYPE, BaseTypes.JSON);

  // /!\ JSON type don't exist in metadata of column,
  // thus we can't use "parse"
  // JSONTYPE.parse = function parse(data) {
  //   return JSON.parse(data);
  // };

  JSONTYPE.prototype.stringify = function(data) {
    if (data && typeof data === 'string') {
      return data;
    } else {
      return JSON.stringify(data);
    }
  }

  /** "parse" data in set */
  JSONTYPE.prototype.parseInSet = function(data) {
    if (data && typeof data === 'string') {
      try {
        return JSON.parse(data);
      } catch (error) {
        //erreur lors du parse, soit JSON malformé soit une string => pas besoin de parse on l'a renvoie direct
        return data;
      }

    } else {
      return data;
    }
  }

  JSONTYPE.prototype.toSql = function toSql() {
    return 'NVARCHAR(MAX)';
  };

  STRING.prototype.toSql = function toSql() {
    if (!this._binary) {
      return 'NVARCHAR(' + this._length + ')';
    } else {
      return 'BINARY(' + this._length + ')';
    }
  };

  STRING.prototype.escape = false;
  STRING.prototype._stringify = function _stringify(value, options) {
    if (this._binary) {
      return BLOB.prototype._stringify(value);
    } else {
      return options.escape(value);
    }
  };

  function TEXT(length) {
    if (!(this instanceof TEXT)) return new TEXT(length);
    BaseTypes.TEXT.apply(this, arguments);
  }
  inherits(TEXT, BaseTypes.TEXT);

  TEXT.prototype.toSql = function toSql() {
    // TEXT is deprecated in mssql and it would normally be saved as a non-unicode string.
    // Using unicode is just future proof
    if (this._length) {
      if (this._length.toLowerCase() === 'tiny') { // tiny = 2^8
        warn('MSSQL does not support TEXT with the `length` = `tiny` option. `NVARCHAR(256)` will be used instead.');
        return 'NVARCHAR(256)';
      }
      warn('MSSQL does not support TEXT with the `length` option. `NVARCHAR(MAX)` will be used instead.');
    }
    return 'NVARCHAR(MAX)';
  };

  function BOOLEAN() {
    if (!(this instanceof BOOLEAN)) return new BOOLEAN();
    BaseTypes.BOOLEAN.apply(this, arguments);
  }
  inherits(BOOLEAN, BaseTypes.BOOLEAN);

  BOOLEAN.prototype.toSql = function toSql() {
    return 'BIT';
  };

  function UUID() {
    if (!(this instanceof UUID)) return new UUID();
    BaseTypes.UUID.apply(this, arguments);
  }
  inherits(UUID, BaseTypes.UUID);

  UUID.prototype.toSql = function toSql() {
    return 'CHAR(36)';
  };

  function NOW() {
    if (!(this instanceof NOW)) return new NOW();
    BaseTypes.NOW.apply(this, arguments);
  }
  inherits(NOW, BaseTypes.NOW);

  NOW.prototype.toSql = function toSql() {
    return 'GETDATE()';
  };

  function DATE(length) {
    if (!(this instanceof DATE)) return new DATE(length);
    BaseTypes.DATE.apply(this, arguments);
  }
  inherits(DATE, BaseTypes.DATE);

  DATE.prototype.toSql = function toSql() {
    if (process.env.SEQ_MSSQL_LEGACY_DATE && process.env.SEQ_MSSQL_LEGACY_DATE.trim() === 'true') {
      return 'DATETIME';
    } else {
      return 'DATETIMEOFFSET';
    }
  };

  /**
   * If the dates are not DateTimeOffset we set them like this
   * */
  if (process.env.SEQ_MSSQL_LEGACY_DATE && process.env.SEQ_MSSQL_LEGACY_DATE.trim() === 'true') {
    DATE.prototype._stringify = function(date, options) {

      date = this._applyTimezone(date, options);

      //On ne passe pas le timezone comme sequelize tente de le faire (reprise https://github.com/sequelize/sequelize/blob/v3/lib/dialects/mssql/data-types.js)
      return date.format('YYYY-MM-DD HH:mm:ss.SSS');
    };
  }

  function DATEONLY() {
    if (!(this instanceof DATEONLY)) return new DATEONLY();
    BaseTypes.DATEONLY.apply(this, arguments);
  }
  inherits(DATEONLY, BaseTypes.DATEONLY);

  DATEONLY.parse = function(value) {
    return moment(value).format('YYYY-MM-DD');
  };

  function INTEGER(length) {
    if (!(this instanceof INTEGER)) return new INTEGER(length);
    BaseTypes.INTEGER.apply(this, arguments);

    // MSSQL does not support any options for integer
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support INTEGER with options. Plain `INTEGER` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(INTEGER, BaseTypes.INTEGER);

  function TINYINT(length) {
    if (!(this instanceof TINYINT)) return new TINYINT(length);
    BaseTypes.TINYINT.apply(this, arguments);

    // MSSQL does not support any options for tinyint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support TINYINT with options. Plain `TINYINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(TINYINT, BaseTypes.TINYINT);

  function SMALLINT(length) {
    if (!(this instanceof SMALLINT)) return new SMALLINT(length);
    BaseTypes.SMALLINT.apply(this, arguments);

    // MSSQL does not support any options for smallint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support SMALLINT with options. Plain `SMALLINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(SMALLINT, BaseTypes.SMALLINT);

  function BIGINT(length) {
    if (!(this instanceof BIGINT)) return new BIGINT(length);
    BaseTypes.BIGINT.apply(this, arguments);

    // MSSQL does not support any options for bigint
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support BIGINT with options. Plain `BIGINT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(BIGINT, BaseTypes.BIGINT);

  function REAL(length, decimals) {
    if (!(this instanceof REAL)) return new REAL(length, decimals);
    BaseTypes.REAL.apply(this, arguments);

    // MSSQL does not support any options for real
    if (this._length || this.options.length || this._unsigned || this._zerofill) {
      warn('MSSQL does not support REAL with options. Plain `REAL` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
      this._unsigned = undefined;
      this._zerofill = undefined;
    }
  }
  inherits(REAL, BaseTypes.REAL);

  function FLOAT(length, decimals) {
    if (!(this instanceof FLOAT)) return new FLOAT(length, decimals);
    BaseTypes.FLOAT.apply(this, arguments);

    // MSSQL does only support lengths as option.
    // Values between 1-24 result in 7 digits precision (4 bytes storage size)
    // Values between 25-53 result in 15 digits precision (8 bytes storage size)
    // If decimals are provided remove these and print a warning
    if (this._decimals) {
      warn('MSSQL does not support Float with decimals. Plain `FLOAT` will be used instead.');
      this._length = undefined;
      this.options.length = undefined;
    }
    if (this._unsigned) {
      warn('MSSQL does not support Float unsigned. `UNSIGNED` was removed.');
      this._unsigned = undefined;
    }
    if (this._zerofill) {
      warn('MSSQL does not support Float zerofill. `ZEROFILL` was removed.');
      this._zerofill = undefined;
    }
  }
  inherits(FLOAT, BaseTypes.FLOAT);

  function ENUM() {
    if (!(this instanceof ENUM)) {
      const obj = Object.create(ENUM.prototype);
      ENUM.apply(obj, arguments);
      return obj;
    }
    BaseTypes.ENUM.apply(this, arguments);
  }
  inherits(ENUM, BaseTypes.ENUM);

  ENUM.prototype.toSql = function toSql() {
    return 'VARCHAR(255)';
  };

  const exports = {
    BLOB,
    BOOLEAN,
    ENUM,
    STRING,
    UUID,
    DATE,
    DATEONLY,
    NOW,
    TINYINT,
    SMALLINT,
    INTEGER,
    BIGINT,
    REAL,
    FLOAT,
    TEXT,
    JSON : JSONTYPE
  };

  _.forIn(exports, (DataType, key) => {
    if (!DataType.key) DataType.key = key;
    if (!DataType.extend) {
      DataType.extend = function extend(oldType) {
        return new DataType(oldType.options);
      };
    }
  });

  return exports;
};
<|endoftext|>


<commit_before>//import Native.Utils //

var _elm_lang$core$Native_Scheduler = function() {

var MAX_STEPS = 10000;

// TASKS

function succeed(value)
{
	return {
		ctor: '_Task_succeed',
		value: value
	};
}

function fail(error)
{
	return {
		ctor: '_Task_fail',
		value: error
	};
}

function nativeBinding(callback)
{
	return {
		ctor: '_Task_nativeBinding',
		callback: callback,
		cancel: null
	};
}

function andThen(task, callback)
{
	return {
		ctor: '_Task_andThen',
		task: task,
		callback: callback
	};
}

function onError(task, callback)
{
	return {
		ctor: '_Task_onError',
		task: task,
		callback: callback
	};
}

function receive(callback)
{
	return {
		ctor: '_Task_receive',
		callback: callback
	};
}

// PROCESSES

function rawSpawn(task)
{
	var process = {
		ctor: '_Process',
		id: _elm_lang$core$Native_Utils.guid(),
		root: task,
		stack: null,
		mailbox: []
	};

	enqueue(process);

	return process;
}

function spawn(task)
{
	return nativeBinding(function(callback) {
		var process = rawSpawn(task);
		callback(succeed(process));
	});
}

function rawSend(process, msg)
{
	process.mailbox.push(msg);
	enqueue(process);
}

function send(process, msg)
{
	return nativeBinding(function(callback) {
		rawSend(process, msg);
		callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
	});
}

function kill(process)
{
	return nativeBinding(function(callback) {
		var root = process.root;
		if (root.ctor === '_Task_nativeBinding' && root.cancel)
		{
			root.cancel();
		}

		process.root = null;

		callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
	});
}

function sleep(time)
{
	return nativeBinding(function(callback) {
		var id = setTimeout(function() {
			callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
		}, time);

		return function() { clearTimeout(id); };
	});
}

// STEP PROCESSES

function step(numSteps, process)
{
	while (numSteps < MAX_STEPS)
	{
		var ctor = process.root.ctor;

		if (ctor === '_Task_succeed')
		{
			while (process.stack && process.stack.ctor === '_Task_onError')
			{
				process.stack = process.stack.rest;
			}
			if (process.stack === null)
			{
				break;
			}
			process.root = process.stack.callback(process.root.value);
			process.stack = process.stack.rest;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_fail')
		{
			while (process.stack && process.stack.ctor === '_Task_andThen')
			{
				process.stack = process.stack.rest;
			}
			if (process.stack === null)
			{
				break;
			}
			process.root = process.stack.callback(process.root.value);
			process.stack = process.stack.rest;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_andThen')
		{
			process.stack = {
				ctor: '_Task_andThen',
				callback: process.root.callback,
				rest: process.stack
			};
			process.root = process.root.task;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_onError')
		{
			process.stack = {
				ctor: '_Task_onError',
				callback: process.root.callback,
				rest: process.stack
			};
			process.root = process.root.task;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_nativeBinding')
		{
			process.root.cancel = process.root.callback(function(newRoot) {
				process.root = newRoot;
				enqueue(process);
			});

			break;
		}

		if (ctor === '_Task_receive')
		{
			var mailbox = process.mailbox;
			if (mailbox.length === 0)
			{
				break;
			}

			process.root = process.root.callback(mailbox.shift());
			++numSteps;
			continue;
		}

		throw new Error(ctor);
	}

	if (numSteps < MAX_STEPS)
	{
		return numSteps + 1;
	}
	enqueue(process);

	return numSteps;
}

// WORK QUEUE

var working = false;
var workQueue = [];

function enqueue(process)
{
	workQueue.push(process);

	if (!working)
	{
		setTimeout(work, 0);
		working = true;
	}
}

function work()
{
	var numSteps = 0;
	var process;
	while (numSteps < MAX_STEPS && (process = workQueue.shift()))
	{
		numSteps = step(numSteps, process);
	}
	if (!process)
	{
		working = false;
		return;
	}
	setTimeout(work, 0);
}

return {
	succeed: succeed,
	fail: fail,
	nativeBinding: nativeBinding,
	andThen: F2(andThen),
	onError: F2(onError),
	receive: receive,

	spawn: spawn,
	kill: kill,
	sleep: sleep,
	send: F2(send),

	rawSpawn: rawSpawn,
	rawSend: rawSend
};

}();<commit_msg>Fix #628 - killed processes getting run<commit_after>//import Native.Utils //

var _elm_lang$core$Native_Scheduler = function() {

var MAX_STEPS = 10000;

// TASKS

function succeed(value)
{
	return {
		ctor: '_Task_succeed',
		value: value
	};
}

function fail(error)
{
	return {
		ctor: '_Task_fail',
		value: error
	};
}

function nativeBinding(callback)
{
	return {
		ctor: '_Task_nativeBinding',
		callback: callback,
		cancel: null
	};
}

function andThen(task, callback)
{
	return {
		ctor: '_Task_andThen',
		task: task,
		callback: callback
	};
}

function onError(task, callback)
{
	return {
		ctor: '_Task_onError',
		task: task,
		callback: callback
	};
}

function receive(callback)
{
	return {
		ctor: '_Task_receive',
		callback: callback
	};
}

// PROCESSES

function rawSpawn(task)
{
	var process = {
		ctor: '_Process',
		id: _elm_lang$core$Native_Utils.guid(),
		root: task,
		stack: null,
		mailbox: []
	};

	enqueue(process);

	return process;
}

function spawn(task)
{
	return nativeBinding(function(callback) {
		var process = rawSpawn(task);
		callback(succeed(process));
	});
}

function rawSend(process, msg)
{
	process.mailbox.push(msg);
	enqueue(process);
}

function send(process, msg)
{
	return nativeBinding(function(callback) {
		rawSend(process, msg);
		callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
	});
}

function kill(process)
{
	return nativeBinding(function(callback) {
		var root = process.root;
		if (root.ctor === '_Task_nativeBinding' && root.cancel)
		{
			root.cancel();
		}

		process.root = null;

		callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
	});
}

function sleep(time)
{
	return nativeBinding(function(callback) {
		var id = setTimeout(function() {
			callback(succeed(_elm_lang$core$Native_Utils.Tuple0));
		}, time);

		return function() { clearTimeout(id); };
	});
}

// STEP PROCESSES

function step(numSteps, process)
{
	while (numSteps < MAX_STEPS)
	{
		var ctor = process.root.ctor;

		if (ctor === '_Task_succeed')
		{
			while (process.stack && process.stack.ctor === '_Task_onError')
			{
				process.stack = process.stack.rest;
			}
			if (process.stack === null)
			{
				break;
			}
			process.root = process.stack.callback(process.root.value);
			process.stack = process.stack.rest;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_fail')
		{
			while (process.stack && process.stack.ctor === '_Task_andThen')
			{
				process.stack = process.stack.rest;
			}
			if (process.stack === null)
			{
				break;
			}
			process.root = process.stack.callback(process.root.value);
			process.stack = process.stack.rest;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_andThen')
		{
			process.stack = {
				ctor: '_Task_andThen',
				callback: process.root.callback,
				rest: process.stack
			};
			process.root = process.root.task;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_onError')
		{
			process.stack = {
				ctor: '_Task_onError',
				callback: process.root.callback,
				rest: process.stack
			};
			process.root = process.root.task;
			++numSteps;
			continue;
		}

		if (ctor === '_Task_nativeBinding')
		{
			process.root.cancel = process.root.callback(function(newRoot) {
				process.root = newRoot;
				enqueue(process);
			});

			break;
		}

		if (ctor === '_Task_receive')
		{
			var mailbox = process.mailbox;
			if (mailbox.length === 0)
			{
				break;
			}

			process.root = process.root.callback(mailbox.shift());
			++numSteps;
			continue;
		}

		throw new Error(ctor);
	}

	if (numSteps < MAX_STEPS)
	{
		return numSteps + 1;
	}
	enqueue(process);

	return numSteps;
}

// WORK QUEUE

var working = false;
var workQueue = [];

function enqueue(process)
{
	workQueue.push(process);

	if (!working)
	{
		setTimeout(work, 0);
		working = true;
	}
}

function work()
{
	var numSteps = 0;
	var process;
	while (numSteps < MAX_STEPS && (process = workQueue.shift()))
	{
		if (process.root)
		{
			numSteps = step(numSteps, process);
		}
	}
	if (!process)
	{
		working = false;
		return;
	}
	setTimeout(work, 0);
}

return {
	succeed: succeed,
	fail: fail,
	nativeBinding: nativeBinding,
	andThen: F2(andThen),
	onError: F2(onError),
	receive: receive,

	spawn: spawn,
	kill: kill,
	sleep: sleep,
	send: F2(send),

	rawSpawn: rawSpawn,
	rawSend: rawSend
};

}();<|endoftext|>


<commit_before>
var loadTemplate = require('../loadTemplate')

var config = require('config')

var federate = require('../federate')
var collateObjects = require('../collateObjects')

function PrefixesEndpoint(req, callback) {

    callback(null, 200, JSON.stringify(config.get('prefixes')))
}

module.exports = federate(PrefixesEndpoint, collateObjects)

<commit_msg>Update prefixes endpoint for federation<commit_after>
var loadTemplate = require('../loadTemplate')

var config = require('config')

var federate = require('../federate')
var collateObjects = require('../collateObjects')

function PrefixesEndpoint(req, callback) {

    callback(null, 200, {
        mimeType: 'application/json',
        body: JSON.stringify(config.get('prefixes'))
    })

}

module.exports = federate(PrefixesEndpoint, collateObjects)

<|endoftext|>


<commit_before>// This file is part of Chukchi, the free web-based RSS aggregator
//
//   Copyright (C) 2013 Edward Toroshchin <chukchi-project@hades.name>
//
// Chukchi is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Chukchi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// Please see the file COPYING in the root directory of this project.
// If you are unable to locate this file, see <http://www.gnu.org/licenses/>.

!function($){

UI = {
    entries: [],
    selectedEntry: -1,
    source: null,
    unread: true
};

AllFeeds = {
    name: "All feeds",
    get: function(start, count, unread, callback) {
        Chukchi.getAllFeeds(start, count, unread, callback);
    },
    $menuitem: null
};

function handleAuth(data) {
    $(".loading").remove();
    $(".screen").hide();
    if(data.state == 1) { // not logged in
        $(".login.screen").show();
        $(".login.screen .openid").focus();
        $(".login.screen form").attr('action', Chukchi.loginUrl());
        return;
    }
    if(data.state == 2) { // logged in
        $(".main.screen").show();
        updateSubscriptions();
        setSource(AllFeeds);
        return;
    }
}

function loadMoreEntries(count) {
    UI.scrollHandler = null;

    var start = UI.nextStartOffset;
    var token = UI.token;

    UI.source.get(start, count, UI.unread, function(total, entries) {
        if(token != UI.token)
            return;

        updateSourceInfo(total);

        if(!entries) {
            console.log("no more entries");
            UI.scrollHandler = null;
            return;
        }

        $.each(entries, function(i, entry) {
            entry.unread = entry.unread || UI.unread;
            var $entry = makeEntryBlock(entry);
            $entry.appendTo($(".main.screen"));
            UI.nextStartOffset = entry.id;
            UI.entries.push($entry);
        });

        UI.scrollHandler = function(){ loadMoreEntries(10); };
        $(window).scroll();
    });
}

function makeEntryBlock(entry) {
    var $entry = $('.t .entry').clone();

    $entry.find('.feed').html(entry.feed.title);
    $entry.find('.title').html(entry.title);
    $entry.find('.date').html(moment(entry.published).fromNow());

    $entry.click(function(){
        selectEntry($(this));
    });

    if(entry.unread)
        $entry.addClass('unread');

    Chukchi.getContent(entry.content[0], function(content) {
        // TODO handle non-html, handle summary and expired content
        $entry.find('.text').html(content.data);
    });

    $entry.entry = entry;
    entry.$block = $entry;

    return $entry;
}

function makeFeedMenuItem(source) {
    if(typeof(source) == 'object') {
        var $item = $(".t .feedmenuselector").clone();
        $item.find('a').html(source.name);
        $item.click(function(){
            setSource(source);
        });
        source.$menuitem = $item;
        return $item;
    }
    var $item = $(".t .feedmenuseparator").clone();
    $item.html(source);
    return $item;
}

function makeFeedSource(subscription) {
    return {
        name: subscription.feed.title,
        get: function(start, count, unread, callback) {
            Chukchi.getEntries(subscription.feed, start, count, unread, callback);
        }
    };
}

function redrawEntries() {
    $(".page-header h1").hide();
    $(".page-header .loading").show();
    $(".main.screen .entry").remove();

    var token = (new Date).getTime();
    UI.token = token;
    UI.entries = [];
    UI.selectedEntry = -1;

    UI.nextStartOffset = 0;
    loadMoreEntries(10);
}

function reportError(err) {
    // TODO: error reporting
}

function selectEntry(entry) {
    var index = entry;
    if(typeof(entry) == 'object') {
        index = UI.entries.indexOf(entry);
    }

    $(".main.screen .entry.selected").removeClass('selected');

    if(index < 0 || index >= UI.entries.length)
    {
        UI.selectedEntry = -1;
        return;
    }
    UI.selectedEntry = index;
    var $entry = UI.entries[index];
    $entry.addClass('selected');
    $('body').animate({
        scrollTop: $entry.offset().top
    }, 200);
    setUnread($entry.entry, false);
}

function setUnread(entry, flag) {
    if(flag == entry.unread)
        return;

    Chukchi.setUnread(entry, !!flag);
    entry.unread = !!flag;
    entry.unread? entry.$block.addClass('unread')
                : entry.$block.removeClass('unread');
}

function setSource(source) {
    UI.source = source;
    $("#navbar li.active").removeClass('active');
    if(source.$menuitem)
        source.$menuitem.addClass('active');
    redrawEntries();
}

function updateSourceInfo(totalEntries) {
    $(".main.screen .loading").hide();
    var $header = $(".main.screen .page-header");

    $header.find('.source-name').html(UI.source.name);
    $header.find('small').html(totalEntries
                               + (UI.unread? ' new items' : ' items'));
    $header.find('h1').show();
}

function updateSubscriptions() {
    var $navlist = $("#navbar .nav-list");

    $navlist.find('li').remove();
    makeFeedMenuItem(AllFeeds).appendTo($navlist);
    makeFeedMenuItem("Feeds:").appendTo($navlist);

    Chukchi.getSubscriptions(function(subs) {
        $.each(subs, function(i, subscription) {
            makeFeedMenuItem(makeFeedSource(subscription)).appendTo($navlist);
        });
    });
}

$(document).ready(function(){
    Chukchi.apierror(reportError);
    Chukchi.auth(handleAuth);

    $(window).scroll(function() {
        if(!UI.scrollHandler)
            return;

        var windowHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var bodyHeight = $(document).height();

        if( scrollTop + 200 > bodyHeight - windowHeight )
            UI.scrollHandler();
    });
    $(window).keypress(function(event) {
        if(event.which == 106) { // j
            event.preventDefault();
            selectEntry(UI.selectedEntry + 1);
            return;
        }
        if(event.which == 107) { // k
            event.preventDefault();
            selectEntry(UI.selectedEntry - 1);
            return;
        }
        if(event.which == 109) { // m
            event.preventDefault();
            var $entry = UI.entries[UI.selectedEntry];
            if($entry)
                setUnread($entry.entry, !$entry.entry.unread);
            return;
        }
        console.log("keypress: " + event.which);
    });

    Chukchi.init();
});

}(window.jQuery);
// vim: sw=4:ts=4:et
<commit_msg>ui: load more entries when the bottom is reached<commit_after>// This file is part of Chukchi, the free web-based RSS aggregator
//
//   Copyright (C) 2013 Edward Toroshchin <chukchi-project@hades.name>
//
// Chukchi is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Chukchi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// Please see the file COPYING in the root directory of this project.
// If you are unable to locate this file, see <http://www.gnu.org/licenses/>.

!function($){

UI = {
    entries: [],
    selectedEntry: -1,
    source: null,
    unread: true
};

AllFeeds = {
    name: "All feeds",
    get: function(start, count, unread, callback) {
        Chukchi.getAllFeeds(start, count, unread, callback);
    },
    $menuitem: null
};

function handleAuth(data) {
    $(".loading").remove();
    $(".screen").hide();
    if(data.state == 1) { // not logged in
        $(".login.screen").show();
        $(".login.screen .openid").focus();
        $(".login.screen form").attr('action', Chukchi.loginUrl());
        return;
    }
    if(data.state == 2) { // logged in
        $(".main.screen").show();
        updateSubscriptions();
        setSource(AllFeeds);
        return;
    }
}

function loadMoreEntries(count) {
    UI.scrollHandler = null;

    var start = UI.nextStartOffset;
    var token = UI.token;

    UI.source.get(start, count, UI.unread, function(total, entries) {
        if(token != UI.token)
            return;

        updateSourceInfo(total);

        if(!entries) {
            console.log("no more entries");
            UI.scrollHandler = null;
            return;
        }

        $.each(entries, function(i, entry) {
            entry.unread = entry.unread || UI.unread;
            var $entry = makeEntryBlock(entry);
            $entry.appendTo($(".main.screen"));
            UI.nextStartOffset = entry.id;
            UI.entries.push($entry);
        });

        UI.scrollHandler = function(){ loadMoreEntries(10); };
        $(window).scroll();
    });
}

function makeEntryBlock(entry) {
    var $entry = $('.t .entry').clone();

    $entry.find('.feed').html(entry.feed.title);
    $entry.find('.title').html(entry.title);
    $entry.find('.date').html(moment(entry.published).fromNow());

    $entry.click(function(){
        selectEntry($(this));
    });

    if(entry.unread)
        $entry.addClass('unread');

    Chukchi.getContent(entry.content[0], function(content) {
        // TODO handle non-html, handle summary and expired content
        $entry.find('.text').html(content.data);
    });

    $entry.entry = entry;
    entry.$block = $entry;

    return $entry;
}

function makeFeedMenuItem(source) {
    if(typeof(source) == 'object') {
        var $item = $(".t .feedmenuselector").clone();
        $item.find('a').html(source.name);
        $item.click(function(){
            setSource(source);
        });
        source.$menuitem = $item;
        return $item;
    }
    var $item = $(".t .feedmenuseparator").clone();
    $item.html(source);
    return $item;
}

function makeFeedSource(subscription) {
    return {
        name: subscription.feed.title,
        get: function(start, count, unread, callback) {
            Chukchi.getEntries(subscription.feed, start, count, unread, callback);
        }
    };
}

function redrawEntries() {
    $(".page-header h1").hide();
    $(".page-header .loading").show();
    $(".main.screen .entry").remove();

    var token = (new Date).getTime();
    UI.token = token;
    UI.entries = [];
    UI.selectedEntry = -1;

    UI.nextStartOffset = 0;
    loadMoreEntries(10);
}

function reportError(err) {
    // TODO: error reporting
}

function selectEntry(entry) {
    var index = entry;
    if(typeof(entry) == 'object') {
        index = UI.entries.indexOf(entry);
    }

    $(".main.screen .entry.selected").removeClass('selected');

    if(UI.entries.length - index <= 3)
        loadMoreEntries(10);
    if(index < 0 || index >= UI.entries.length)
    {
        UI.selectedEntry = -1;
        return;
    }
    UI.selectedEntry = index;
    var $entry = UI.entries[index];
    $entry.addClass('selected');
    $('body').animate({
        scrollTop: $entry.offset().top
    }, 200);
    setUnread($entry.entry, false);
}

function setUnread(entry, flag) {
    if(flag == entry.unread)
        return;

    Chukchi.setUnread(entry, !!flag);
    entry.unread = !!flag;
    entry.unread? entry.$block.addClass('unread')
                : entry.$block.removeClass('unread');
}

function setSource(source) {
    UI.source = source;
    $("#navbar li.active").removeClass('active');
    if(source.$menuitem)
        source.$menuitem.addClass('active');
    redrawEntries();
}

function updateSourceInfo(totalEntries) {
    $(".main.screen .loading").hide();
    var $header = $(".main.screen .page-header");

    $header.find('.source-name').html(UI.source.name);
    $header.find('small').html(totalEntries
                               + (UI.unread? ' new items' : ' items'));
    $header.find('h1').show();
}

function updateSubscriptions() {
    var $navlist = $("#navbar .nav-list");

    $navlist.find('li').remove();
    makeFeedMenuItem(AllFeeds).appendTo($navlist);
    makeFeedMenuItem("Feeds:").appendTo($navlist);

    Chukchi.getSubscriptions(function(subs) {
        $.each(subs, function(i, subscription) {
            makeFeedMenuItem(makeFeedSource(subscription)).appendTo($navlist);
        });
    });
}

$(document).ready(function(){
    Chukchi.apierror(reportError);
    Chukchi.auth(handleAuth);

    $(window).scroll(function() {
        if(!UI.scrollHandler)
            return;

        var windowHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var bodyHeight = $(document).height();

        if( scrollTop + 200 > bodyHeight - windowHeight )
            UI.scrollHandler();
    });
    $(window).keypress(function(event) {
        if(event.which == 106) { // j
            event.preventDefault();
            selectEntry(UI.selectedEntry + 1);
            return;
        }
        if(event.which == 107) { // k
            event.preventDefault();
            selectEntry(UI.selectedEntry - 1);
            return;
        }
        if(event.which == 109) { // m
            event.preventDefault();
            var $entry = UI.entries[UI.selectedEntry];
            if($entry)
                setUnread($entry.entry, !$entry.entry.unread);
            return;
        }
        console.log("keypress: " + event.which);
    });

    Chukchi.init();
});

}(window.jQuery);
// vim: sw=4:ts=4:et
<|endoftext|>