<commit_before>// @flow
import {
  FLUSH,
  PAUSE,
  PERSIST,
  PURGE,
  REHYDRATE,
  DEFAULT_VERSION,
} from './constants'

import type {
  PersistConfig,
  MigrationManifest,
  PersistState,
  Persistoid,
} from './types'

import autoMergeLevel1 from './stateReconciler/autoMergeLevel1'
import createPersistoid from './createPersistoid'
import defaultGetStoredState from './getStoredState'
import purgeStoredState from './purgeStoredState'

type PersistPartial = { _persist: PersistState }
const DEFAULT_TIMEOUT = 5000
/*
  @TODO add validation / handling for:
  - persisting a reducer which has nested _persist
  - handling actions that fire before reydrate is called
*/
export default function persistReducer<State: Object, Action: Object>(
  config: PersistConfig,
  baseReducer: (State, Action) => State
): (State, Action) => State & PersistPartial {
  if (process.env.NODE_ENV !== 'production') {
    if (!config) throw new Error('config is required for persistReducer')
    if (!config.key) throw new Error('key is required in persistor config')
    if (!config.storage)
      throw new Error(
        "redux-persist: config.storage is required. Try using one of the provided storage engines `import storage from 'redux-persist/lib/storage'`"
      )
  }

  const version =
    config.version !== undefined ? config.version : DEFAULT_VERSION
  const debug = config.debug || false
  const stateReconciler =
    config.stateReconciler === undefined
      ? autoMergeLevel1
      : config.stateReconciler
  const getStoredState = config.getStoredState || defaultGetStoredState
  const timeout =
    config.timeout !== undefined ? config.timeout : DEFAULT_TIMEOUT
  let _persistoid = null
  let _purge = false
  let _paused = true
  const conditionalUpdate = state => {
    // update the persistoid only if we are rehydrated and not paused
    state._persist.rehydrated &&
      _persistoid &&
      !_paused &&
      _persistoid.update(state)
    return state
  }

  return (state: State, action: Action) => {
    let { _persist, ...rest } = state || {}
    let restState: State = rest

    if (action.type === PERSIST) {
      let _sealed = false
      let _rehydrate = (payload, err) => {
        // dev warning if we are already sealed
        if (process.env.NODE_ENV !== 'production' && _sealed)
          console.error(
            `redux-persist: rehydrate for "${
              config.key
            }" called after timeout.`,
            payload,
            err
          )

        // only rehydrate if we are not already sealed
        if (!_sealed) {
          action.rehydrate(config.key, payload, err)
          _sealed = true
        }
      }
      timeout &&
        setTimeout(() => {
          !_sealed &&
            _rehydrate(
              undefined,
              new Error(
                `redux-persist: persist timed out for persist key "${
                  config.key
                }"`
              )
            )
        }, timeout)

      // @NOTE PERSIST resumes if paused.
      _paused = false

      // @NOTE only ever create persistoid once, ensure we call it at least once, even if _persist has already been set
      if (!_persistoid) _persistoid = createPersistoid(config)

      // @NOTE PERSIST can be called multiple times, noop after the first
      if (_persist) return state
      if (
        typeof action.rehydrate !== 'function' ||
        typeof action.register !== 'function'
      )
        throw new Error(
          'redux-persist: either rehydrate or register is not a function on the PERSIST action. This can happen if the action is being replayed. This is an unexplored use case, please open an issue and we will figure out a resolution.'
        )

      action.register(config.key)

      getStoredState(config).then(
        restoredState => {
          const migrate = config.migrate || ((s, v) => Promise.resolve(s))
          migrate(restoredState, version).then(
            migratedState => {
              _rehydrate(migratedState)
            },
            migrateErr => {
              if (process.env.NODE_ENV !== 'production' && migrateErr)
                console.error('redux-persist: migration error', migrateErr)
              _rehydrate(undefined, migrateErr)
            }
          )
        },
        err => {
          _rehydrate(undefined, err)
        }
      )

      return {
        ...baseReducer(restState, action),
        _persist: { version, rehydrated: false },
      }
    } else if (action.type === PURGE) {
      _purge = true
      action.result(purgeStoredState(config))
      return {
        ...baseReducer(restState, action),
        _persist,
      }
    } else if (action.type === FLUSH) {
      action.result(_persistoid && _persistoid.flush())
      return {
        ...baseReducer(restState, action),
        _persist,
      }
    } else if (action.type === PAUSE) {
      _paused = true
    } else if (action.type === REHYDRATE) {
      // noop on restState if purging
      if (_purge)
        return {
          ...restState,
          _persist: { ..._persist, rehydrated: true },
        }

      // @NOTE if key does not match, will continue to default else below
      if (action.key === config.key) {
        let reducedState = baseReducer(restState, action)
        let inboundState = action.payload
        // only reconcile state if stateReconciler and inboundState are both defined
        let reconciledRest: State =
          stateReconciler !== false && inboundState !== undefined
            ? stateReconciler(inboundState, state, reducedState, config)
            : reducedState

        let newState = {
          ...reconciledRest,
          _persist: { ..._persist, rehydrated: true },
        }
        return conditionalUpdate(newState)
      }
    }

    // if we have not already handled PERSIST, straight passthrough
    if (!_persist) return baseReducer(state, action)

    // run base reducer:
    // is state modified ? return original : return updated
    let newState = baseReducer(restState, action)
    if (newState === restState) return state
    else {
      newState._persist = _persist
      return conditionalUpdate(newState)
    }
  }
}
<commit_msg>Fix issue that also newState should not be changed<commit_after>// @flow
import {
  FLUSH,
  PAUSE,
  PERSIST,
  PURGE,
  REHYDRATE,
  DEFAULT_VERSION,
} from './constants'

import type {
  PersistConfig,
  MigrationManifest,
  PersistState,
  Persistoid,
} from './types'

import autoMergeLevel1 from './stateReconciler/autoMergeLevel1'
import createPersistoid from './createPersistoid'
import defaultGetStoredState from './getStoredState'
import purgeStoredState from './purgeStoredState'

type PersistPartial = { _persist: PersistState }
const DEFAULT_TIMEOUT = 5000
/*
  @TODO add validation / handling for:
  - persisting a reducer which has nested _persist
  - handling actions that fire before reydrate is called
*/
export default function persistReducer<State: Object, Action: Object>(
  config: PersistConfig,
  baseReducer: (State, Action) => State
): (State, Action) => State & PersistPartial {
  if (process.env.NODE_ENV !== 'production') {
    if (!config) throw new Error('config is required for persistReducer')
    if (!config.key) throw new Error('key is required in persistor config')
    if (!config.storage)
      throw new Error(
        "redux-persist: config.storage is required. Try using one of the provided storage engines `import storage from 'redux-persist/lib/storage'`"
      )
  }

  const version =
    config.version !== undefined ? config.version : DEFAULT_VERSION
  const debug = config.debug || false
  const stateReconciler =
    config.stateReconciler === undefined
      ? autoMergeLevel1
      : config.stateReconciler
  const getStoredState = config.getStoredState || defaultGetStoredState
  const timeout =
    config.timeout !== undefined ? config.timeout : DEFAULT_TIMEOUT
  let _persistoid = null
  let _purge = false
  let _paused = true
  const conditionalUpdate = state => {
    // update the persistoid only if we are rehydrated and not paused
    state._persist.rehydrated &&
      _persistoid &&
      !_paused &&
      _persistoid.update(state)
    return state
  }

  return (state: State, action: Action) => {
    let { _persist, ...rest } = state || {}
    let restState: State = rest

    if (action.type === PERSIST) {
      let _sealed = false
      let _rehydrate = (payload, err) => {
        // dev warning if we are already sealed
        if (process.env.NODE_ENV !== 'production' && _sealed)
          console.error(
            `redux-persist: rehydrate for "${
              config.key
            }" called after timeout.`,
            payload,
            err
          )

        // only rehydrate if we are not already sealed
        if (!_sealed) {
          action.rehydrate(config.key, payload, err)
          _sealed = true
        }
      }
      timeout &&
        setTimeout(() => {
          !_sealed &&
            _rehydrate(
              undefined,
              new Error(
                `redux-persist: persist timed out for persist key "${
                  config.key
                }"`
              )
            )
        }, timeout)

      // @NOTE PERSIST resumes if paused.
      _paused = false

      // @NOTE only ever create persistoid once, ensure we call it at least once, even if _persist has already been set
      if (!_persistoid) _persistoid = createPersistoid(config)

      // @NOTE PERSIST can be called multiple times, noop after the first
      if (_persist) return state
      if (
        typeof action.rehydrate !== 'function' ||
        typeof action.register !== 'function'
      )
        throw new Error(
          'redux-persist: either rehydrate or register is not a function on the PERSIST action. This can happen if the action is being replayed. This is an unexplored use case, please open an issue and we will figure out a resolution.'
        )

      action.register(config.key)

      getStoredState(config).then(
        restoredState => {
          const migrate = config.migrate || ((s, v) => Promise.resolve(s))
          migrate(restoredState, version).then(
            migratedState => {
              _rehydrate(migratedState)
            },
            migrateErr => {
              if (process.env.NODE_ENV !== 'production' && migrateErr)
                console.error('redux-persist: migration error', migrateErr)
              _rehydrate(undefined, migrateErr)
            }
          )
        },
        err => {
          _rehydrate(undefined, err)
        }
      )

      return {
        ...baseReducer(restState, action),
        _persist: { version, rehydrated: false },
      }
    } else if (action.type === PURGE) {
      _purge = true
      action.result(purgeStoredState(config))
      return {
        ...baseReducer(restState, action),
        _persist,
      }
    } else if (action.type === FLUSH) {
      action.result(_persistoid && _persistoid.flush())
      return {
        ...baseReducer(restState, action),
        _persist,
      }
    } else if (action.type === PAUSE) {
      _paused = true
    } else if (action.type === REHYDRATE) {
      // noop on restState if purging
      if (_purge)
        return {
          ...restState,
          _persist: { ..._persist, rehydrated: true },
        }

      // @NOTE if key does not match, will continue to default else below
      if (action.key === config.key) {
        let reducedState = baseReducer(restState, action)
        let inboundState = action.payload
        // only reconcile state if stateReconciler and inboundState are both defined
        let reconciledRest: State =
          stateReconciler !== false && inboundState !== undefined
            ? stateReconciler(inboundState, state, reducedState, config)
            : reducedState

        let newState = {
          ...reconciledRest,
          _persist: { ..._persist, rehydrated: true },
        }
        return conditionalUpdate(newState)
      }
    }

    // if we have not already handled PERSIST, straight passthrough
    if (!_persist) return baseReducer(state, action)

    // run base reducer:
    // is state modified ? return original : return updated
    let newState = baseReducer(restState, action)
    if (newState === restState) return state
    return conditionalUpdate({ ...newState, _persist })
  }
}
<|endoftext|>


<commit_before>/** Created by hhj on 1/29/16. */
import uniqBy from 'lodash/uniqBy'
import myRest from '../lib/rest/index'
import createFetch from '../lib/rest/createFetch'
import { ZarizeniFactory } from './models/Zarizeni'
import { UmisteniFactory } from './models/Umisteni'
import { Lokalita } from './models/Lokalita'
import { NepiOp } from './models/NepiOp'
import { Udalost } from './models/Udalost'
import { Sort } from './models/Sort'
import { Pagination } from './models/Pagination'

export { getSubState, getItem, getItems } from '../lib/rest'

const serverBaseUrl = process.env.SERVER_BASE_URL
  || (process.env.IS_BROWSER ? window.SERVER_BASE_URL : null)
  || 'http://localhost:8089/api'

const rest = myRest({
  zarizeni: {
    url: '/zarizeni/:id/:nested',
    extraParams: { include: 'umisteni.lokalita' },
    itemTransformer: item => ZarizeniFactory(item),
    defaultState: { sort: new Sort({ dir: true, by: 'createdAt' }) },
    isStaticCollection: true
  },
  portyZarizeni: {
    url: '/zarizeni/:zarizeni_id/netvision/porty'
  },
  previousNetvisionIdentity: {
    url: '/zarizeni/:zarizeni_id/previous_netvision_identity'
  },
  umisteni: {
    url: '/umisteni/:id',
    extraParams: { include: 'lokalita.nepi_opy' },
    itemTransformer: item => UmisteniFactory(item),
    defaultState: { pagination: new Pagination({ perPage: 1000000 }) }
    // itemTransformer: item => item,
  },
  lokalita: {
    url: '/lokalita/:id',
    extraParams: { include: 'nepi_opy_count,umistena_zarizeni_count' },
    itemTransformer: item => new Lokalita(item),
    defaultState: { pagination: new Pagination({ perPage: 10 }) }
  },
  lokalitaForAutocomplete: {
    url: '/lokalita/:id',
    itemTransformer: item => new Lokalita(item),
    defaultState: { pagination: new Pagination({ perPage: 1000 }) }
  },
  zarizeniNaLokalite: {
    url: '/zarizeni/:id',
    itemTransformer: item => ZarizeniFactory(item),
    defaultState: { pagination: new Pagination({ perPage: 10000 }) }
  },
  nepiOpyNaLokalite: {
    url: '/nepi_op/:id',
    itemTransformer: item => new NepiOp(item),
    idField: 'ixop',
    defaultState: { pagination: new Pagination({ perPage: 10000 }) }
  },
  akrloks: {
    url: '/lokalita/:id',
    // itemTransformer: item => (item.akrlok ? item.akrlok.toLowerCase() : ''),
    collectionTransformer: collection => uniqBy((collection || []), item => item.akrlok),
    itemTransformer: item => new Lokalita(item),
    extraParams: { fields: 'akrlok,obec', 'akrlok-not': null, sort: 'obec' },
    defaultState: { pagination: new Pagination({ perPage: 10000000 }) },
    idField: 'akrlok'
  },
  udalost: {
    url: '/udalost/:id',
    itemTransformer: item => new Udalost(item),
  },
  testEndpoint: {
    url: '/test/:id'
  }
}).use('fetch', createFetch(serverBaseUrl))

export default rest

// export const actions = rest.actions
// export const reducers = rest.reducers
<commit_msg>feat: group udalost list by udalost.data<commit_after>/** Created by hhj on 1/29/16. */
import uniqBy from 'lodash/uniqBy'
import myRest from '../lib/rest/index'
import createFetch from '../lib/rest/createFetch'
import { ZarizeniFactory } from './models/Zarizeni'
import { UmisteniFactory } from './models/Umisteni'
import { Lokalita } from './models/Lokalita'
import { NepiOp } from './models/NepiOp'
import { Udalost } from './models/Udalost'
import { Sort } from './models/Sort'
import { Pagination } from './models/Pagination'

export { getSubState, getItem, getItems } from '../lib/rest'

const serverBaseUrl = process.env.SERVER_BASE_URL
  || (process.env.IS_BROWSER ? window.SERVER_BASE_URL : null)
  || 'http://localhost:8089/api'

const rest = myRest({
  zarizeni: {
    url: '/zarizeni/:id/:nested',
    extraParams: { include: 'umisteni.lokalita' },
    itemTransformer: item => ZarizeniFactory(item),
    defaultState: { sort: new Sort({ dir: true, by: 'createdAt' }) },
    isStaticCollection: true
  },
  portyZarizeni: {
    url: '/zarizeni/:zarizeni_id/netvision/porty'
  },
  previousNetvisionIdentity: {
    url: '/zarizeni/:zarizeni_id/previous_netvision_identity'
  },
  umisteni: {
    url: '/umisteni/:id',
    extraParams: { include: 'lokalita.nepi_opy' },
    itemTransformer: item => UmisteniFactory(item),
    defaultState: { pagination: new Pagination({ perPage: 1000000 }) }
    // itemTransformer: item => item,
  },
  lokalita: {
    url: '/lokalita/:id',
    extraParams: { include: 'nepi_opy_count,umistena_zarizeni_count' },
    itemTransformer: item => new Lokalita(item),
    defaultState: { pagination: new Pagination({ perPage: 10 }) }
  },
  lokalitaForAutocomplete: {
    url: '/lokalita/:id',
    itemTransformer: item => new Lokalita(item),
    defaultState: { pagination: new Pagination({ perPage: 1000 }) }
  },
  zarizeniNaLokalite: {
    url: '/zarizeni/:id',
    itemTransformer: item => ZarizeniFactory(item),
    defaultState: { pagination: new Pagination({ perPage: 10000 }) }
  },
  nepiOpyNaLokalite: {
    url: '/nepi_op/:id',
    itemTransformer: item => new NepiOp(item),
    idField: 'ixop',
    defaultState: { pagination: new Pagination({ perPage: 10000 }) }
  },
  akrloks: {
    url: '/lokalita/:id',
    // itemTransformer: item => (item.akrlok ? item.akrlok.toLowerCase() : ''),
    collectionTransformer: collection => uniqBy((collection || []), item => item.akrlok),
    itemTransformer: item => new Lokalita(item),
    extraParams: { fields: 'akrlok,obec', 'akrlok-not': null, sort: 'obec' },
    defaultState: { pagination: new Pagination({ perPage: 10000000 }) },
    idField: 'akrlok'
  },
  udalost: {
    url: '/udalost/:id',
    itemTransformer: item => new Udalost(item),
    extraParams: { group: 'data' },
  },
  testEndpoint: {
    url: '/test/:id'
  }
}).use('fetch', createFetch(serverBaseUrl))

export default rest

// export const actions = rest.actions
// export const reducers = rest.reducers
<|endoftext|>


<commit_before>import React, {
  Component,
  StyleSheet
} from 'react-native';

import { LineChart } from 'react-native-ios-charts';

const config = {
  dataSets: [{
    values: [-1, 1, -1],
    drawValues: false,
    colors: ['rgb(199, 255, 140)'],
    label: 'Sine function',
    drawCubic: true,
    drawCircles: false,
    lineWidth: 2
  }, {
    values: [1, -1, 1],
    drawValues: false,
    colors: ['rgb(255, 247, 141)'],
    label: 'Cosine function',
    drawCubic: true,
    drawCircles: false,
    lineWidth: 2
  }],
  backgroundColor: 'transparent',
  labels: ['Jan', 'Feb', 'Mar'],
  minOffset: 20,
  scaleYEnabled: false,
  legend: {
    textSize: 12
  },
  xAxis: {
    axisLineWidth: 0,
    drawLabels: false,
    position: 'bottom',
    drawGridLines: false
  },
  leftAxis: {
    customAxisMax: 1,
    customAxisMin: -1,
    labelCount: 11,
    startAtZero: false,
    spaceTop: 0.1,
    spaceBottom: 0.1
  },
  rightAxis: {
    enabled: false,
    drawGridLines: false
  },
  valueFormatter: {
    minimumSignificantDigits: 1,
    type: 'regular',
    maximumDecimalPlaces: 1
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch'
  }
});

export default class Line extends Component {
  static displayName = 'Line';

  render() {
    return (
      <LineChart config={config} style={styles.container}/>
    );
  }
}
<commit_msg>fixed line chart in charts explorer<commit_after>import React, {
  Component,
  StyleSheet
} from 'react-native';

import { LineChart } from 'react-native-ios-charts';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch'
  }
});

export default class Line extends Component {
  static displayName = 'Line';

  render() {
    const config = {
      dataSets: [{
        values: [-1, 1, -1],
        drawValues: false,
        colors: ['rgb(199, 255, 140)'],
        label: 'Sine function',
        drawCubic: true,
        drawCircles: false,
        lineWidth: 2
      }, {
        values: [1, -1, 1],
        drawValues: false,
        colors: ['rgb(255, 247, 141)'],
        label: 'Cosine function',
        drawCubic: true,
        drawCircles: false,
        lineWidth: 2
      }],
      backgroundColor: 'transparent',
      labels: ['Jan', 'Feb', 'Mar'],
      minOffset: 20,
      scaleYEnabled: false,
      legend: {
        textSize: 12
      },
      xAxis: {
        axisLineWidth: 0,
        drawLabels: false,
        position: 'bottom',
        drawGridLines: false
      },
      leftAxis: {
        customAxisMax: 1,
        customAxisMin: -1,
        labelCount: 11,
        startAtZero: false,
        spaceTop: 0.1,
        spaceBottom: 0.1
      },
      rightAxis: {
        enabled: false,
        drawGridLines: false
      },
      valueFormatter: {
        minimumSignificantDigits: 1,
        type: 'regular',
        maximumDecimalPlaces: 1
      }
    };
    return (
      <LineChart config={config} style={styles.container}/>
    );
  }
}
<|endoftext|>


<commit_before>define([ 'jquery', 'user_race_stats/component' ], function($, UserRaceStats) {
  'use strict';

  describe('User race stats', function() {

    before(function() {
      $('body').append('

');
      this.instance = new UserRaceStats('#test');
    });

    it('has datagrid table', function() {
      this.instance.$node.find('table.datagrid').length.should.equal(1);
    });

    it('has empty datagrid table tbody', function() {
      this.instance.$node.find('table.datagrid tbody').text().should.equal('0 wierszy');
    });

    after(function() {
      this.instance.teardown();
      $('#test').remove();
    });

  });
});
<commit_msg>New tests for user race stats added.<commit_after>define([ 'jquery', 'user_race_stats/component' ], function($, UserRaceStats) {
  'use strict';

  describe('User race stats', function() {

    describe('Data not provided', function() {

      before(function() {
        $('body').append('

');
        this.instance = new UserRaceStats('#test');
      });

      it('has datagrid table', function() {
        this.instance.$node.find('table.datagrid').length.should.equal(1);
      });

      it('has datagrid with proper id', function() {
        this.instance.$node.find('table.datagrid').attr('id').should.equal('cnr-races-stats');
      });

      it('has datagrid table head with proper label', function() {
        this.instance.$node.find('table.datagrid thead .datagrid-header-title').text().should.equal('Statystyki uczestników wyścigów');
      });

      it('has datagrid table body with proper message', function() {
        this.instance.$node.find('table.datagrid tbody').text().should.equal('0 wierszy');
      });

      after(function() {
        this.instance.teardown();
        $('#test').remove();
      });
    });

    describe('Data provided', function() {

      before(function() {
        $('body').append('

');
        $('#test').data('stats', [ {
          total_time : '04:02:33',
          total_odo : '123',
          races : '2',
          avg_speed : '21',
          nick : 'test user',
          avatar_file_name : 'http://www.czasnarower.pl/photo/avatar/avatar_default.jpg',
          url_view : 'http://www.czasnarower/uzytkownik/123'
        }, {
          total_time : '05:02:33',
          total_odo : '120,5',
          races : '3',
          avg_speed : '18,5',
          nick : 'test user2',
          avatar_file_name : 'http://www.czasnarower.pl/photo/avatar/avatar_default.jpg',
          url_view : 'http://www.czasnarower/uzytkownik/323'
        } ]);
        this.instance = new UserRaceStats('#test');
      });

      it('has datagrid with two rows', function() {
        this.instance.$node.find('table.datagrid tbody tr').length.should.equal(2);
      });

      it('has datagrid with five columns', function() {
        this.instance.$node.find('table.datagrid tbody tr:first td').length.should.equal(5);
      });

      it('has datagrid sorted by total time column', function() {
        this.instance.$node.find('table.datagrid tbody tr:first > td:nth-child(2)').text().should.equal('05:02:33');
      });

      it('has datagrid with image in first column', function() {
        this.instance.$node.find('table.datagrid tbody tr:first > td:nth-child(1) img').attr('src').should.equal('http://www.czasnarower.pl/photo/avatar/avatar_default.jpg');
      });

      it('has datagrid with link to user profile in first column', function() {
        this.instance.$node.find('table.datagrid tbody tr:first > td:nth-child(1) a').attr('href').should.equal('http://www.czasnarower/uzytkownik/323');
      });

      after(function() {
        this.instance.teardown();
        $('#test').remove();
      });
    });

  });
});
<|endoftext|>


<commit_before>let userName = null;

var cards = ['M1.png', 'M2.png', 'M3.png', 'M4.png', 'M5.png', 'M6.png', 'M7.png', 'M8.png', 'P1.png', 'P2.png', 'P3.png', 'P4.png', 'P5.png', 'P6.png', 'P7.png', 'P8.png', 'T1.png', 'T2.png', 'T3.png', 'T4.png', 'T5.png', 'T6.png', 'T7.png', 'T8.png', 'Z1.png', 'Z2.png', 'Z3.png', 'Z4.png', 'Z5.png', 'Z6.png', 'Z7.png', 'Z8.png'];

var hand = [];
var state = "elol";
var talon = [];

function shuffle(arra1) {
    var ctr = arra1.length, temp, index;
    while (ctr > 0) {
        index = Math.floor(Math.random() * ctr);
        ctr--;
        temp = arra1[ctr];
        arra1[ctr] = arra1[index];
        arra1[index] = temp;
    }
    return arra1;
}

function moveCardUp(x){
    x.style.bottom = "60px";
}
function moveCardBack(x){
    x.style.bottom = "20px";
}

function clearTable(){
    cards.forEach(c => {
        var id = c.substring(0,2);
        x = document.getElementById(id);
        x.style.display = "none";
    });
}
function playcard(id){
    var tid = id + ".png";
    if (state == "talonozas"){
        if (hand.length > 10) {

        }
    }
    if (state == "lejatszas"){
        var x = document.getElementById(id);
        x.style.display = "none";
        id = id + ".png";
        sock.emit('playcard', id);
        var tmhand = [];
        hand.forEach(c => {
            if (c != id){
                tmhand.push(c);
            }
        });
        hand = tmhand;
        showCards(hand);
    }
}
function showCards (arr){
    arr.sort();
    for (i = 0; i < arr.length; i++){
        var id = arr[i].substring(0,2);
        x = document.getElementById(id);
        x.style.display = "block";
        x.style.left = (20 + i * 60) + "px";
        x.style.zIndex = i;
    }
}

const sock = io();

const writeEvent = (text) => {
    //
 element
    const parent = document.querySelector('#events');
    //
 element
    const el = document.createElement('li');
    el.innerHTML = text;
    parent.appendChild(el);
    parent.scrollTop = parent.scrollHeight;
};
const writePlayerList = (text) => {
    document.getElementById("player-list").innerHTML = text;
};
const onFormSubmitted = (e) => {
    e.preventDefault();
    const input = document.querySelector('#chat');
    const text = input.value;
    input.value = '';

    sock.emit('message', userName + ": " + text);
}
const onStartGame = (e) => {
    e.preventDefault();
    sock.emit('start');
}
const onBedobom = (e) => {
    e.preventDefault();
    sock.emit('bedobom', hand);
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": bedobta");
}
const onMegyek = (e) => {
    e.preventDefault();
    sock.emit('megyek');
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": megy tovabb");
}
const onJatszok = (e) => {
    e.preventDefault();
    sock.emit('jatszok');
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": jatszik");
}

const parent = document.querySelector('#gameplace');
cards.forEach(imageFile => {
    var id = imageFile.substring(0,2);

    const g = document.createElement('div');
    g.setAttribute("id", id);
    g.setAttribute("class", "largecard");
    g.setAttribute("style", "display: none; bottom: 20px");
    g.setAttribute("onclick", "playcard(this.id)");
    g.setAttribute("onmouseover", "moveCardUp(this)");
    g.setAttribute("onmouseout", "moveCardBack(this)");
    p = document.createElement("img");
    p.setAttribute("src", "cards/" + imageFile);
    g.appendChild(p);
    parent.appendChild(g);
    // var d = document.getElementById(id);
    // d.style.display = "hide";
});
var butt_arr = ["bedobom", "megyek", "jatszok"];
var spacer = 0;
butt_arr.forEach(val=> {
    const dv = document.createElement('div');
    dv.setAttribute("id", val + "-butt");
    dv.setAttribute("class", "elolrol-butt");
    dv.setAttribute("style", "display: none; bottom: 300px; left: " + (spacer+100) + "px");
    const fr = document.createElement('form');
    fr.setAttribute("id", val + "-form");
    const bt = document.createElement('button');
    bt.innerText = val.charAt(0).toUpperCase() + val.slice(1);
    fr.appendChild(bt);
    dv.appendChild(fr);
    parent.appendChild(dv);
    spacer+=120;
})
document.querySelector('#start-game').addEventListener('submit', onStartGame);
document.querySelector('#bedobom-form').addEventListener('submit', onBedobom);
document.querySelector('#megyek-form').addEventListener('submit', onMegyek);
document.querySelector('#jatszok-form').addEventListener('submit', onJatszok);
document.querySelector('#chat-form').addEventListener('submit', onFormSubmitted);

const onEntrySubmitted = (e) => {
    e.preventDefault();
    const input = document.querySelector('#name');
    userName = input.value;
    if (userName){

        // const addButtonListeners = () => {
        //     ['rock', 'paper', 'scissors'].forEach((id) =>{
        //         const button = document.getElementById(id);
        //         button.addEventListener('click', () => {
        //             sock.emit('turn', id);
        //         });
        //     });
        // };
        var x = document.getElementById("entry");
        x.style.display = "none";
        x = document.getElementById("mainblock");
        x.style.display = "flex";
        var x = document.getElementById("start-game");
        x.style.display = "none";
        writeEvent('Otlapos Ulti beszelgetes');

        sock.on('message', (text) => {
            writeEvent(text);
        });
        sock.on('plist', (text) => {
            writePlayerList("Belepett jatekosok:
" + text);
        });
        sock.on('canstart', () => {
            var x = document.getElementById("start-game");
            x.style.display = "block";
        });
        sock.on('elolrol', (subarr)=>{
            clearTable();
            hand = [];
            hand = hand.concat(subarr);
            showCards(hand);
            butt_arr.forEach(x => {
                x = document.getElementById(x + "-butt");
                x.style.display = "block";
            });
        });
        sock.on('hatulrol', (arr) => {
            clearTable();
            hand = hand.concat(arr);
            showCards(hand);
            state = "talonozas";
        });
        sock.on('nezelod', () => {
            document.removeEventListener('submit', onBedobom);
            document.removeEventListener('submit', onMegyek);
            document.removeEventListener('submit', onJatszok);
            clearTable();
        });

        //addButtonListeners();
        sock.emit('name', userName);
    }

};

if (userName == null){
    var x = document.getElementById("mainblock");
    x.style.display = "none";
    document.querySelector('#entry-form').addEventListener('submit', onEntrySubmitted);
}<commit_msg>Yesterday's changes<commit_after>let userName = null;

var cards = ['M1.png', 'M2.png', 'M3.png', 'M4.png', 'M5.png', 'M6.png', 'M7.png', 'M8.png', 'P1.png', 'P2.png', 'P3.png', 'P4.png', 'P5.png', 'P6.png', 'P7.png', 'P8.png', 'T1.png', 'T2.png', 'T3.png', 'T4.png', 'T5.png', 'T6.png', 'T7.png', 'T8.png', 'Z1.png', 'Z2.png', 'Z3.png', 'Z4.png', 'Z5.png', 'Z6.png', 'Z7.png', 'Z8.png'];

var hand = [];
var state = "elol";
var talon = [];
var clicked = "";

function shuffle(arra1) {
    var ctr = arra1.length, temp, index;
    while (ctr > 0) {
        index = Math.floor(Math.random() * ctr);
        ctr--;
        temp = arra1[ctr];
        arra1[ctr] = arra1[index];
        arra1[index] = temp;
    }
    return arra1;
}

function moveCardUp(x){
    //if (hand.includes(x.id + ".png")){
    //if (x.id != clicked){
        var pos = x.style.bottom;
        pos = parseInt(pos.replace("px", "")) + 30;
        x.style.bottom = pos + "px";
    //}
}
function moveCardBack(x){
    //if (hand.includes(x.id + ".png")){
    //if (x.id != clicked){
        var pos = x.style.bottom;
        pos = parseInt(pos.replace("px", "")) - 30;
        x.style.bottom = pos + "px";
    //}
}

function clearTable(){
    cards.forEach(c => {
        var id = c.substring(0,2);
        x = document.getElementById(id);
        x.style.display = "none";
    });
}

function clearTablePart(arr){
    arr.forEach(c => {
        var id = c.substring(0,2);
        x = document.getElementById(id);
        x.style.display = "none";
    });
}
function playcard(id){
    var tid = id + ".png";
    if (state == "talonozas"){
        if (hand.includes(tid)) {
            if (hand.length > 10){
                var tmhand = [];
                clicked = id;
                //console.log(talon);
                hand.forEach(c => {
                    //var x = document.getElementById(tid.substring(0,2));
                    //x.setAttribute("onmouseout", "");
                    if (c != tid){
                        tmhand.push(c);
                    }
                    else{
                        talon.push(c);

                    }
                });
                hand = tmhand;
                //console.log(talon);
                //talon = tmtalon;
                clearTable();
                showCards(hand);
                showTalon(talon);
            }
        }
        else {
            if (talon.length > 0 && talon.includes(tid)){
                var tmtalon = [];
                clicked = id;
                talon.forEach(c => {
                    if (c != tid){
                        tmtalon.push(c);
                    }
                    else{
                        hand.push(c);

                    }
                });
                talon = tmtalon;
                clearTable();
                showCards(hand);
                showTalon(talon);
            }
        }
    }
    if (state == "lejatszas"){
        var x = document.getElementById(id);
        x.style.display = "none";
        sock.emit('playcard', tid);
        var tmhand = [];
        hand.forEach(c => {
            if (c != tid){
                tmhand.push(c);
            }
        });
        hand = tmhand;
        showCards(hand);
    }
}
function showCards (arr){
    arr.sort();
    for (var i = 0; i < arr.length; i++){
        var id = arr[i].substring(0,2);
        var x = document.getElementById(id);
        x.style.left = (20 + i * 60) + "px";
        x.style.zIndex = i;
        //x.setAttribute("onmouseout", "moveCardBack(this)");
        //x.onmouseout = "moveCardBack(this)";
        x.style.bottom = "20px";
        if (id == clicked){
            x.style.bottom = "50px";
        }
        x.style.display = "block";
    }
}
function showTalon (arr){
    //clearTablePart(arr);
    arr.sort();
    for (var j = 0; j < arr.length; j++){
        var id = arr[j].substring(0,2);
        var x = document.getElementById(id);
        x.style.left = (200 + j * 130) + "px";
        x.style.zIndex = j+12;
        //x.setAttribute("onmouseout", "moveCardBack(this)");
        //x.onmouseout = "moveCardBack(this)";
        x.style.bottom = "300px";
        if (id == clicked){
            x.style.bottom = "330px";
        }
        x.style.display = "block";
    }
}

const sock = io();

const writeEvent = (text) => {
    //
 element
    const parent = document.querySelector('#events');
    //
 element
    const el = document.createElement('li');
    el.innerHTML = text;
    parent.appendChild(el);
    parent.scrollTop = parent.scrollHeight;
};
const writePlayerList = (text) => {
    document.getElementById("player-list").innerHTML = text;
};
const onFormSubmitted = (e) => {
    e.preventDefault();
    const input = document.querySelector('#chat');
    const text = input.value;
    input.value = '';

    sock.emit('message', userName + ": " + text);
}
const onStartGame = (e) => {
    e.preventDefault();
    sock.emit('start');
}
const onBedobom = (e) => {
    e.preventDefault();
    sock.emit('bedobom', hand);
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": bedobta");
}
const onMegyek = (e) => {
    e.preventDefault();
    sock.emit('megyek');
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": megy tovabb");
}
const onJatszok = (e) => {
    e.preventDefault();
    sock.emit('jatszok');
    butt_arr.forEach(x => {
        x = document.getElementById(x + "-butt");
        x.style.display = "none";
    });
    sock.emit('message', userName + ": jatszik");
}

const parent = document.querySelector('#gameplace');
cards.forEach(imageFile => {
    var id = imageFile.substring(0,2);

    const g = document.createElement('div');
    g.setAttribute("id", id);
    g.setAttribute("class", "largecard");
    g.setAttribute("style", "display: none; bottom: 20px");
    g.setAttribute("onclick", "playcard(this.id)");
    g.setAttribute("onmouseover", "moveCardUp(this)");
    g.setAttribute("onmouseout", "moveCardBack(this)");
    p = document.createElement("img");
    p.setAttribute("src", "cards/" + imageFile);
    g.appendChild(p);
    parent.appendChild(g);
    // var d = document.getElementById(id);
    // d.style.display = "hide";
});
var butt_arr = ["bedobom", "megyek", "jatszok"];
var spacer = 0;
butt_arr.forEach(val=> {
    const dv = document.createElement('div');
    dv.setAttribute("id", val + "-butt");
    dv.setAttribute("class", "elolrol-butt");
    dv.setAttribute("style", "display: none; bottom: 300px; left: " + (spacer+100) + "px");
    const fr = document.createElement('form');
    fr.setAttribute("id", val + "-form");
    const bt = document.createElement('button');
    bt.innerText = val.charAt(0).toUpperCase() + val.slice(1);
    fr.appendChild(bt);
    dv.appendChild(fr);
    parent.appendChild(dv);
    spacer+=120;
})
document.querySelector('#start-game').addEventListener('submit', onStartGame);
document.querySelector('#bedobom-form').addEventListener('submit', onBedobom);
document.querySelector('#megyek-form').addEventListener('submit', onMegyek);
document.querySelector('#jatszok-form').addEventListener('submit', onJatszok);
document.querySelector('#chat-form').addEventListener('submit', onFormSubmitted);

const onEntrySubmitted = (e) => {
    e.preventDefault();
    const input = document.querySelector('#name');
    userName = input.value;
    if (userName){

        // const addButtonListeners = () => {
        //     ['rock', 'paper', 'scissors'].forEach((id) =>{
        //         const button = document.getElementById(id);
        //         button.addEventListener('click', () => {
        //             sock.emit('turn', id);
        //         });
        //     });
        // };
        var x = document.getElementById("entry");
        x.style.display = "none";
        x = document.getElementById("mainblock");
        x.style.display = "flex";
        var x = document.getElementById("start-game");
        x.style.display = "none";
        writeEvent('Otlapos Ulti beszelgetes');

        sock.on('message', (text) => {
            writeEvent(text);
        });
        sock.on('plist', (text) => {
            writePlayerList("Belepett jatekosok:
" + text);
        });
        sock.on('canstart', () => {
            var x = document.getElementById("start-game");
            x.style.display = "block";
        });
        sock.on('elolrol', (subarr)=>{
            clearTable();
            hand = [];
            hand = hand.concat(subarr);
            showCards(hand);
            butt_arr.forEach(x => {
                x = document.getElementById(x + "-butt");
                x.style.display = "block";
            });
        });
        sock.on('hatulrol', (arr) => {
            clearTable();
            hand = hand.concat(arr);
            showCards(hand);
            state = "talonozas";
        });
        sock.on('nezelod', () => {
            clearTable();
        });

        //addButtonListeners();
        sock.emit('name', userName);
    }

};

if (userName == null){
    var x = document.getElementById("mainblock");
    x.style.display = "none";
    document.querySelector('#entry-form').addEventListener('submit', onEntrySubmitted);
}<|endoftext|>


<commit_before>const fs = require('fs');
const Promise = require('bluebird');
const writeFile = Promise.promisify(fs.writeFile);
const UglifyJS = require('uglify-js');
const {
  getASTJSON,
  getComponentsJS,
  getDataJS,
  getHTML
} = require('./parse');
const css = require('./css');
const bundleJS = require('./bundle-js');

let output;

const build = (opts, paths, inputConfig) => {
  // always store source in opts.inputString
  if (paths.IDYLL_INPUT_FILE) {
    opts.inputString = fs.readFileSync(paths.IDYLL_INPUT_FILE, 'utf8');
  }

  return Promise.try(
    // this is all synchronous so we wrap it with Promise.try
    // to start a Promise chain and turn any synchronous exceptions into a rejection
    () => {
      const ast = compile(opts.inputString, opts.compilerOptions);
      output = {
        ast: getASTJSON(ast),
        components: getComponentsJS(ast, paths, inputConfig),
        css: css(opts),
        data: getDataJS(ast, paths.DATA_DIR),
        html: getHTML(ast, fs.readFileSync(paths.HTML_TEMPLATE_FILE, 'utf8'))
      };
    }
  )
  .then(() => {
    // write everything but JS to disk
    return Promise.all([
      writeFile(paths.AST_OUTPUT_FILE, output.ast),
      writeFile(paths.COMPONENTS_OUTPUT_FILE, output.components),
      writeFile(paths.CSS_OUTPUT_FILE, output.css),
      writeFile(paths.DATA_OUTPUT_FILE, output.data),
      writeFile(paths.HTML_OUTPUT_FILE, output.html),
    ]);
  })
  .then(() => {
    return bundleJS(paths); // create index.js bundle
  })
  .then((js) => {
    // minify bundle if necessary and store it
    if (opts.minify) {
      js = UglifyJS.minify(js, {fromString: true}).code;
    }
    output.js = js;
  })
  .then(() => {
    writeFile(paths.JS_OUTPUT_FILE, output.js); // write JS to disk
  })
  .then(() => {
    return output; // return all results
  });
}

const updateCSS = (opts, paths) => {
  output.css = css(opts);
  return writeFile(paths.CSS_OUTPUT_FILE, output.css)
    .then(() => {
      return output; // return all results
    });
}

module.exports = {
  build,
  updateCSS
}
<commit_msg>Require the compiler. Duh.<commit_after>const fs = require('fs');
const Promise = require('bluebird');
const writeFile = Promise.promisify(fs.writeFile);
const compile = require('idyll-compiler');
const UglifyJS = require('uglify-js');
const {
  getASTJSON,
  getComponentsJS,
  getDataJS,
  getHTML
} = require('./parse');
const css = require('./css');
const bundleJS = require('./bundle-js');

let output;

const build = (opts, paths, inputConfig) => {
  // always store source in opts.inputString
  if (paths.IDYLL_INPUT_FILE) {
    opts.inputString = fs.readFileSync(paths.IDYLL_INPUT_FILE, 'utf8');
  }

  return Promise.try(
    // this is all synchronous so we wrap it with Promise.try
    // to start a Promise chain and turn any synchronous exceptions into a rejection
    () => {
      const ast = compile(opts.inputString, opts.compilerOptions);
      output = {
        ast: getASTJSON(ast),
        components: getComponentsJS(ast, paths, inputConfig),
        css: css(opts),
        data: getDataJS(ast, paths.DATA_DIR),
        html: getHTML(ast, fs.readFileSync(paths.HTML_TEMPLATE_FILE, 'utf8'))
      };
    }
  )
  .then(() => {
    // write everything but JS to disk
    return Promise.all([
      writeFile(paths.AST_OUTPUT_FILE, output.ast),
      writeFile(paths.COMPONENTS_OUTPUT_FILE, output.components),
      writeFile(paths.CSS_OUTPUT_FILE, output.css),
      writeFile(paths.DATA_OUTPUT_FILE, output.data),
      writeFile(paths.HTML_OUTPUT_FILE, output.html),
    ]);
  })
  .then(() => {
    return bundleJS(paths); // create index.js bundle
  })
  .then((js) => {
    // minify bundle if necessary and store it
    if (opts.minify) {
      js = UglifyJS.minify(js, {fromString: true}).code;
    }
    output.js = js;
  })
  .then(() => {
    writeFile(paths.JS_OUTPUT_FILE, output.js); // write JS to disk
  })
  .then(() => {
    return output; // return all results
  });
}

const updateCSS = (opts, paths) => {
  output.css = css(opts);
  return writeFile(paths.CSS_OUTPUT_FILE, output.css)
    .then(() => {
      return output; // return all results
    });
}

module.exports = {
  build,
  updateCSS
}
<|endoftext|>


<commit_before>function deleteUser(email) {
  $.ajax({
    url: "/zebedee/users?email=" + email,
    dataType: 'json',
    contentType: 'application/json',
    type: 'DELETE',
    success: function () {
      console.log('User deleted');
      viewController('users');
    },
    error: function (response) {
      if (response.status === 403 || response.status === 401) {
        alert("You are not permitted to delete users.")
      } else {
        handleApiError(response);
      }
    }
  });
}<commit_msg>alert user when they have successfully deleted a user.<commit_after>function deleteUser(email) {
  $.ajax({
    url: "/zebedee/users?email=" + email,
    dataType: 'json',
    contentType: 'application/json',
    type: 'DELETE',
    success: function () {
      console.log('User deleted');
      alert('User deleted');
      viewController('users');
    },
    error: function (response) {
      if (response.status === 403 || response.status === 401) {
        alert("You are not permitted to delete users.")
      } else {
        handleApiError(response);
      }
    }
  });
}<|endoftext|>


<commit_before>var vec2 = require('../math/vec2')
,   Solver = require('./Solver')
,   Utils = require('../utils/Utils')
,   FrictionEquation = require('../equations/FrictionEquation');

module.exports = GSSolver;

/**
 * Iterative Gauss-Seidel constraint equation solver.
 *
 * @class GSSolver
 * @constructor
 * @extends Solver
 * @param {Object} [options]
 * @param {Number} [options.iterations=10]
 * @param {Number} [options.tolerance=0]
 */
function GSSolver(options){
    Solver.call(this,options,Solver.GS);
    options = options || {};

    /**
     * The number of iterations to do when solving. More gives better results, but is more expensive.
     * @property iterations
     * @type {Number}
     */
    this.iterations = options.iterations || 10;

    /**
     * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster.
     * @property tolerance
     * @type {Number}
     */
    this.tolerance = options.tolerance || 1e-10;

    this.arrayStep = 30;
    this.lambda = new Utils.ARRAY_TYPE(this.arrayStep);
    this.Bs =     new Utils.ARRAY_TYPE(this.arrayStep);
    this.invCs =  new Utils.ARRAY_TYPE(this.arrayStep);

    /**
     * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
     * @property useZeroRHS
     * @type {Boolean}
     */
    this.useZeroRHS = false;

    /**
     * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example.
     * The solver will use less iterations if the solution is below the .tolerance.
     * @property frictionIterations
     * @type {Number}
     */
    this.frictionIterations = 0;

    /**
     * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations.
     * @property {Number} usedIterations
     */
    this.usedIterations = 0;
}
GSSolver.prototype = new Solver();

function setArrayZero(array){
    for(var i=0; i!==array.length; i++){
        array[i] = 0.0;
    }
}

/**
 * Solve the system of equations
 * @method solve
 * @param  {Number}  h       Time step
 * @param  {World}   world    World to solve
 */
GSSolver.prototype.solve = function(h, world){

    this.sortEquations();

    var iter = 0,
        maxIter = this.iterations,
        maxFrictionIter = this.frictionIterations,
        equations = this.equations,
        Neq = equations.length,
        tolSquared = Math.pow(this.tolerance*Neq, 2),
        bodies = world.bodies,
        Nbodies = world.bodies.length,
        add = vec2.add,
        set = vec2.set,
        useZeroRHS = this.useZeroRHS,
        lambda = this.lambda;

    this.usedIterations = 0;

    // Things that does not change during iteration can be computed once
    if(lambda.length < Neq){
        lambda = this.lambda =  new Utils.ARRAY_TYPE(Neq + this.arrayStep);
        this.Bs =               new Utils.ARRAY_TYPE(Neq + this.arrayStep);
        this.invCs =            new Utils.ARRAY_TYPE(Neq + this.arrayStep);
    }
    setArrayZero(lambda);
    var invCs = this.invCs,
        Bs = this.Bs,
        lambda = this.lambda;

    for(var i=0; i!==equations.length; i++){
        var c = equations[i];
        if(c.timeStep !== h || c.needsUpdate){
            c.timeStep = h;
            c.update();
        }
        Bs[i] =     c.computeB(c.a,c.b,h);
        invCs[i] =  c.computeInvC(c.epsilon);
    }

    var q, B, c, deltalambdaTot,i,j;

    if(Neq !== 0){

        // Reset vlambda
        for(i=0; i!==Nbodies; i++){
            bodies[i].resetConstraintVelocity();
        }

        if(maxFrictionIter){
            // Iterate over contact equations to get normal forces
            for(iter=0; iter!==maxFrictionIter; iter++){

                // Accumulate the total error for each iteration.
                deltalambdaTot = 0.0;

                for(j=0; j!==Neq; j++){
                    c = equations[j];

                    if(c instanceof FrictionEquation){
                        //continue;
                    }

                    var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
                    deltalambdaTot += Math.abs(deltalambda);
                }

                this.usedIterations++;

                // If the total error is small enough - stop iterate
                if(deltalambdaTot*deltalambdaTot <= tolSquared){
                    break;
                }
            }

            // Set computed friction force
            for(j=0; j!==Neq; j++){
                var eq = equations[j];
                if(eq instanceof FrictionEquation){
                    var f = eq.contactEquation.multiplier * eq.frictionCoefficient;
                    eq.maxForce =  f;
                    eq.minForce = -f;
                }
            }
        }

        // Iterate over all equations
        for(iter=0; iter!==maxIter; iter++){

            // Accumulate the total error for each iteration.
            deltalambdaTot = 0.0;

            for(j=0; j!==Neq; j++){
                c = equations[j];

                var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
                deltalambdaTot += Math.abs(deltalambda);
            }

            this.usedIterations++;

            // If the total error is small enough - stop iterate
            if(deltalambdaTot*deltalambdaTot <= tolSquared){
                break;
            }
        }

        // Add result to velocity
        for(i=0; i!==Nbodies; i++){
            bodies[i].addConstraintVelocity();
        }

        // Set the .multiplier property of each equation
        var l = Neq;
        var invDt = 1/h;
        while(l--){
            equations[l].multiplier = lambda[l] * invDt;
        }
    }
};

GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){
    // Compute iteration
    var B = Bs[j],
        invC = invCs[j],
        lambdaj = lambda[j],
        GWlambda = eq.computeGWlambda();

    var maxForce = eq.maxForce,
        minForce = eq.minForce;

    if(useZeroRHS){
        B = 0;
    }

    var deltalambda = invC * ( B - GWlambda - eps * lambdaj );

    // Clamp if we are not within the min/max interval
    var lambdaj_plus_deltalambda = lambdaj + deltalambda;
    if(lambdaj_plus_deltalambda < minForce*dt){
        deltalambda = minForce*dt - lambdaj;
    } else if(lambdaj_plus_deltalambda > maxForce*dt){
        deltalambda = maxForce*dt - lambdaj;
    }
    lambda[j] += deltalambda;
    //eq.multiplier = lambda[j] / dt;
    eq.addToWlambda(deltalambda);

    return deltalambda;
};
<commit_msg>update multipliers for the friction solve too<commit_after>var vec2 = require('../math/vec2')
,   Solver = require('./Solver')
,   Utils = require('../utils/Utils')
,   FrictionEquation = require('../equations/FrictionEquation');

module.exports = GSSolver;

/**
 * Iterative Gauss-Seidel constraint equation solver.
 *
 * @class GSSolver
 * @constructor
 * @extends Solver
 * @param {Object} [options]
 * @param {Number} [options.iterations=10]
 * @param {Number} [options.tolerance=0]
 */
function GSSolver(options){
    Solver.call(this,options,Solver.GS);
    options = options || {};

    /**
     * The number of iterations to do when solving. More gives better results, but is more expensive.
     * @property iterations
     * @type {Number}
     */
    this.iterations = options.iterations || 10;

    /**
     * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster.
     * @property tolerance
     * @type {Number}
     */
    this.tolerance = options.tolerance || 1e-10;

    this.arrayStep = 30;
    this.lambda = new Utils.ARRAY_TYPE(this.arrayStep);
    this.Bs =     new Utils.ARRAY_TYPE(this.arrayStep);
    this.invCs =  new Utils.ARRAY_TYPE(this.arrayStep);

    /**
     * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
     * @property useZeroRHS
     * @type {Boolean}
     */
    this.useZeroRHS = false;

    /**
     * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example.
     * The solver will use less iterations if the solution is below the .tolerance.
     * @property frictionIterations
     * @type {Number}
     */
    this.frictionIterations = 0;

    /**
     * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations.
     * @property {Number} usedIterations
     */
    this.usedIterations = 0;
}
GSSolver.prototype = new Solver();

function setArrayZero(array){
    for(var i=0; i!==array.length; i++){
        array[i] = 0.0;
    }
}

/**
 * Solve the system of equations
 * @method solve
 * @param  {Number}  h       Time step
 * @param  {World}   world    World to solve
 */
GSSolver.prototype.solve = function(h, world){

    this.sortEquations();

    var iter = 0,
        maxIter = this.iterations,
        maxFrictionIter = this.frictionIterations,
        equations = this.equations,
        Neq = equations.length,
        tolSquared = Math.pow(this.tolerance*Neq, 2),
        bodies = world.bodies,
        Nbodies = world.bodies.length,
        add = vec2.add,
        set = vec2.set,
        useZeroRHS = this.useZeroRHS,
        lambda = this.lambda;

    this.usedIterations = 0;

    // Things that does not change during iteration can be computed once
    if(lambda.length < Neq){
        lambda = this.lambda =  new Utils.ARRAY_TYPE(Neq + this.arrayStep);
        this.Bs =               new Utils.ARRAY_TYPE(Neq + this.arrayStep);
        this.invCs =            new Utils.ARRAY_TYPE(Neq + this.arrayStep);
    }
    setArrayZero(lambda);
    var invCs = this.invCs,
        Bs = this.Bs,
        lambda = this.lambda;

    for(var i=0; i!==equations.length; i++){
        var c = equations[i];
        if(c.timeStep !== h || c.needsUpdate){
            c.timeStep = h;
            c.update();
        }
        Bs[i] =     c.computeB(c.a,c.b,h);
        invCs[i] =  c.computeInvC(c.epsilon);
    }

    var q, B, c, deltalambdaTot,i,j;

    if(Neq !== 0){

        // Reset vlambda
        for(i=0; i!==Nbodies; i++){
            bodies[i].resetConstraintVelocity();
        }

        if(maxFrictionIter){
            // Iterate over contact equations to get normal forces
            for(iter=0; iter!==maxFrictionIter; iter++){

                // Accumulate the total error for each iteration.
                deltalambdaTot = 0.0;

                for(j=0; j!==Neq; j++){
                    c = equations[j];

                    if(c instanceof FrictionEquation){
                        //continue;
                    }

                    var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
                    deltalambdaTot += Math.abs(deltalambda);
                }

                this.usedIterations++;

                // If the total error is small enough - stop iterate
                if(deltalambdaTot*deltalambdaTot <= tolSquared){
                    break;
                }
            }

            GSSolver.updateMultipliers(equations, lambda, 1/h);

            // Set computed friction force
            for(j=0; j!==Neq; j++){
                var eq = equations[j];
                if(eq instanceof FrictionEquation){
                    var f = eq.contactEquation.multiplier * eq.frictionCoefficient;
                    eq.maxForce =  f;
                    eq.minForce = -f;
                }
            }
        }

        // Iterate over all equations
        for(iter=0; iter!==maxIter; iter++){

            // Accumulate the total error for each iteration.
            deltalambdaTot = 0.0;

            for(j=0; j!==Neq; j++){
                c = equations[j];

                var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
                deltalambdaTot += Math.abs(deltalambda);
            }

            this.usedIterations++;

            // If the total error is small enough - stop iterate
            if(deltalambdaTot*deltalambdaTot <= tolSquared){
                break;
            }
        }

        // Add result to velocity
        for(i=0; i!==Nbodies; i++){
            bodies[i].addConstraintVelocity();
        }

        GSSolver.updateMultipliers(equations, lambda, 1/h);
    }
};

// Sets the .multiplier property of each equation
GSSolver.updateMultipliers = function(equations, lambda, invDt){
    // Set the .multiplier property of each equation
    var l = equations.length;
    while(l--){
        equations[l].multiplier = lambda[l] * invDt;
    }
};

GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){
    // Compute iteration
    var B = Bs[j],
        invC = invCs[j],
        lambdaj = lambda[j],
        GWlambda = eq.computeGWlambda();

    var maxForce = eq.maxForce,
        minForce = eq.minForce;

    if(useZeroRHS){
        B = 0;
    }

    var deltalambda = invC * ( B - GWlambda - eps * lambdaj );

    // Clamp if we are not within the min/max interval
    var lambdaj_plus_deltalambda = lambdaj + deltalambda;
    if(lambdaj_plus_deltalambda < minForce*dt){
        deltalambda = minForce*dt - lambdaj;
    } else if(lambdaj_plus_deltalambda > maxForce*dt){
        deltalambda = maxForce*dt - lambdaj;
    }
    lambda[j] += deltalambda;
    //eq.multiplier = lambda[j] / dt;
    eq.addToWlambda(deltalambda);

    return deltalambda;
};
<|endoftext|>


<commit_before>// アカウント登録画面
var win = Ti.UI.currentWindow;

(function(){
	//ユーザ名form
	var name_form = Ti.UI.createTextField({
		color: '#333333',
		hintText: 'ユーザー名',
		height: '10%',
		top: '12%',
		left: '5%',
		width: '75%',
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	//パスワードform
	var pass_form = Ti.UI.createTextField({
		color: '#333333',
		hintText: 'パスワード',
		height: '10%',
		top: '25%',
		left: '5%',
		width: '75%',
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	// 送信ボタン
	var button3 = Ti.UI.createButton({
		title: '登録',
		top: '45%',
		left: '22%',
		width: '40%',
		height: '13%',
		font:{fontSize:26},
	});
	//戻るボタン
	var button4 = Ti.UI.createButton({
		title: '戻る',
		top: '0.5%',
		left: '1%',
		width: '18%',
		height: '8.5%'
	});

	win.add(name_form);
	win.add(pass_form);
	win.add(button3);
	win.add(button4);

	//登録ボタンを押した時の処理
	button3.addEventListener('click', function(e){
		var name = name_form.getValue();
		var pass = pass_form.getValue();
		var account = Ti.Network.createHTTPClient(); //APIを利用するための記述
		var url = "http://www31092u.sakura.ne.jp/~g031i043/takizawa/account.php/"+ name + "/" + pass;
		account.open("GET", url);
		account.setRequestHeader('Content-type', 'application/json; charset=utf-8');

		account.onload = function() {
			Ti.API.info("Received text: " + this.responseText);
			var new_user = JSON.parse(this.responseText);
			var new_user_id = new_user.user_id;
			if(new_user_id == "error"){
				alert("エラー");
			}
			else{
			Ti.App.Properties.setInt('id', new_user_id); //登録したユーザーのidを端末登録
			var id = Ti.App.Properties.getInt('id'); //端末に登録したidの呼び出し
			}
			var labelNewUserid = Titanium.UI.createLabel({
				text:new_user_id,
				font:{fontSize:20,fontFamily:'Helvetica Neue'},
				textAlign:'center',
				width:'auto'
			});
			Ti.API.info(labelNewUserid);
			//win2.add(labelNewUserid);
		}
		account.send();
		var id = Ti.App.Properties.getInt('id');
		var main_win = Titanium.UI.createWindow({
			url:'takizawa_trip.js',
			user_id:id
		});

		Ti.API.info("id::::"+ id);

		if(id != null){
		main_win.open();
		}
	});
	//戻るボタンが押された時の処理
	button4.addEventListener('click', function(e){
		win.close();
	});
})();<commit_msg>varidation add<commit_after>// アカウント登録画面
var win = Ti.UI.currentWindow;

(function(){
	//ユーザ名form
	var name_form = Ti.UI.createTextField({
		color: '#333333',
		hintText: 'ユーザー名',
		height: '10%',
		top: '12%',
		left: '5%',
		width: '75%',
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	//パスワードform
	var pass_form = Ti.UI.createTextField({
		color: '#333333',
		hintText: 'パスワード',
		height: '10%',
		top: '25%',
		left: '5%',
		width: '75%',
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	// 送信ボタン
	var button3 = Ti.UI.createButton({
		title: '登録',
		top: '45%',
		left: '22%',
		width: '40%',
		height: '13%',
		font:{fontSize:26},
	});
	//戻るボタン
	var button4 = Ti.UI.createButton({
		title: '戻る',
		top: '0.5%',
		left: '1%',
		width: '18%',
		height: '8.5%'
	});

	win.add(name_form);
	win.add(pass_form);
	win.add(button3);
	win.add(button4);

	//登録ボタンを押した時の処理
	button3.addEventListener('click', function(e){
		var name = name_form.getValue();
		var pass = pass_form.getValue();
		var account = Ti.Network.createHTTPClient(); //APIを利用するための記述
		var url = "http://www31092u.sakura.ne.jp/~g031i043/takizawa/account.php/"+ name + "/" + pass;
		account.open("GET", url);
		account.setRequestHeader('Content-type', 'application/json; charset=utf-8');

		account.onload = function() {
			Ti.API.info("Received text: " + this.responseText);
			var new_user = JSON.parse(this.responseText);
			var new_user_id = new_user.user_id;
			if(new_user_id == "error"){
				alert("すでに登録されているユーザー名です。");
			}
			else{
				Ti.App.Properties.setInt('id', new_user_id); //登録したユーザーのidを端末登録
				var id = Ti.App.Properties.getInt('id'); //端末に登録したidの呼び出し

				var labelNewUserid = Titanium.UI.createLabel({
					text:new_user_id,
					font:{fontSize:20,fontFamily:'Helvetica Neue'},
					textAlign:'center',
					width:'auto'
				});
				Ti.API.info(labelNewUserid);
			//win2.add(labelNewUserid);
				var id = Ti.App.Properties.getInt('id');
				var main_win = Titanium.UI.createWindow({
					url:'takizawa_trip.js',
					user_id:id
				});

				Ti.API.info("id::::"+ id);

				if(id != null){
					main_win.open();
				}
			}
		}
		account.send();

	});
	//戻るボタンが押された時の処理
	button4.addEventListener('click', function(e){
		win.close();
	});
})();<|endoftext|>


<commit_before>const meta = {
  title: 'Vue Select | VueJS Select2/Chosen Component',
  description: 'A well-tested, native Vue.js component that provides similar functionality to Select2/Chosen without the overhead of jQuery.',
  icon: 'static/vue-logo.png',
};

module.exports = {
  title: 'VueSelect',
  description: meta.description,
  head: [
    [
      'link',
      {
        href: '//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Roboto Mono',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    [
      'link',
      {
        href: '//fonts.googleapis.com/css?family=Dosis:300&text=Vue Select',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    [
      'link',
      {
        href: 'https://cdnjs.cloudflare.com/ajax/libs/octicons/4.4.0/font/octicons.min.css',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    ['meta', {name: 'title', content: meta.title}],
    ['meta', {name: 'description', content: meta.description}],
    ['link', {rel: 'icon', href: meta.icon, type: 'image/png'}],
    ['meta', {property: 'og:image', content: meta.icon}],
    ['meta', {property: 'twitter:image', content: meta.icon}],
    ['meta', {name: 'description', content: meta.description}],
    ['meta', {property: 'og:description', content: ''}],
    ['meta', {property: 'twitter:description', content: meta.description}],
    ['meta', {property: 'twitter:title', content: meta.title}],
    ['meta', {property: 'og:title', content: meta.title}],
    ['meta', {property: 'og:site_name', content: meta.title}],
    [
      'meta',
      {property: 'og:url', content: 'http://sagalbot.github.io/vue-select/'}],
  ],
  serviceWorker: true,
  ga: 'UA-12818324-8',
  themeConfig: {
    repo: 'sagalbot/vue-select',
    editLinks: true,
    docsDir: 'docs',
    nav: [
      {text: 'Docs', link: '/guide/'},
    ],
    sidebar: {
      '/docs/': [
        {
          title: 'Getting Started',
          collapsable: false,
          children: [
            ['getting-started/install', 'Installation'],
            ['getting-started/options', 'Dropdown Options'],
            ['getting-started/values', 'Selecting Values'],
            ['getting-started/localization', 'Localization'],
          ],
        },
        {
          title: 'Digging Deeper',
          collapsable: false,
          children: [
            ['digging-deeper/templating', 'Templating & Slots'],
            ['digging-deeper/vuex', 'Vuex'],
            ['digging-deeper/ajax', 'AJAX'],
            ['digging-deeper/examples', 'Examples'],
          ],
        },
        {
          title: 'API',
          collapsable: false,
          children: [
            ['api/props', 'Props'],
            ['api/slots', 'Slots'],
            ['api/events', 'Events']
          ],
        },
      ],
    },
  },

};
<commit_msg>ditch the top nav<commit_after>const meta = {
  title: 'Vue Select | VueJS Select2/Chosen Component',
  description: 'A well-tested, native Vue.js component that provides similar functionality to Select2/Chosen without the overhead of jQuery.',
  icon: 'static/vue-logo.png',
};

module.exports = {
  title: 'VueSelect',
  description: meta.description,
  head: [
    [
      'link',
      {
        href: '//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Roboto Mono',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    [
      'link',
      {
        href: '//fonts.googleapis.com/css?family=Dosis:300&text=Vue Select',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    [
      'link',
      {
        href: 'https://cdnjs.cloudflare.com/ajax/libs/octicons/4.4.0/font/octicons.min.css',
        rel: 'stylesheet',
        type: 'text/css',
      }],
    ['meta', {name: 'title', content: meta.title}],
    ['meta', {name: 'description', content: meta.description}],
    ['link', {rel: 'icon', href: meta.icon, type: 'image/png'}],
    ['meta', {property: 'og:image', content: meta.icon}],
    ['meta', {property: 'twitter:image', content: meta.icon}],
    ['meta', {name: 'description', content: meta.description}],
    ['meta', {property: 'og:description', content: ''}],
    ['meta', {property: 'twitter:description', content: meta.description}],
    ['meta', {property: 'twitter:title', content: meta.title}],
    ['meta', {property: 'og:title', content: meta.title}],
    ['meta', {property: 'og:site_name', content: meta.title}],
    [
      'meta',
      {property: 'og:url', content: 'http://sagalbot.github.io/vue-select/'}],
  ],
  serviceWorker: true,
  ga: 'UA-12818324-8',
  themeConfig: {
    repo: 'sagalbot/vue-select',
    editLinks: true,
    docsDir: 'docs',
    sidebar: {
      '/docs/': [
        {
          title: 'Getting Started',
          collapsable: false,
          children: [
            ['getting-started/install', 'Installation'],
            ['getting-started/options', 'Dropdown Options'],
            ['getting-started/values', 'Selecting Values'],
            ['getting-started/localization', 'Localization'],
          ],
        },
        {
          title: 'Digging Deeper',
          collapsable: false,
          children: [
            ['digging-deeper/templating', 'Templating & Slots'],
            ['digging-deeper/vuex', 'Vuex'],
            ['digging-deeper/ajax', 'AJAX'],
            ['digging-deeper/examples', 'Examples'],
          ],
        },
        {
          title: 'API',
          collapsable: false,
          children: [
            ['api/props', 'Props'],
            ['api/slots', 'Slots'],
            ['api/events', 'Events']
          ],
        },
      ],
    },
  },

};
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Douban Group Dingbot
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Douban Group topics auto comments.
// @author       You
// @match        https://www.douban.com/group/topic/*
// @grant        window.close
// ==/UserScript==

(function() {
  'use strict';

  function random_int (min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
  }

  var topic = 'PPResume';
  var title = document.getElementsByTagName('h1')[0].textContent;
  var is_ppresume_topic = (title.toUpperCase().indexOf(topic.toUpperCase()) == -1 ? false : true);

  if (! is_ppresume_topic) {
    console.log("This is not a " + topic + " topic, you've made a wrong choice, my master...");
    return;
  }

  var words = ['喵', '汪', '嗷', '咩', '哞', '呱',
               '吱', '喔', '叽', '嗡', '咿', '嘶',
               '喳', '嘎', '咕', '哇', '呜', '嗥'];

  var has_captcha = document.getElementById('captcha_image');
  if (has_captcha) {
    console.log("This page has captcha image, I can't post for you, master, sorry...");
    return;
  }
  var textarea = document.querySelector('textarea[id=last]');
  if (! textarea) {
    console.log("You've just posted a comment already, I'll close the window and exit...");
    setTimeout(function () { window.close(); }, 3000);
    return;
  }

  textarea.innerHTML = words[random_int(0, words.length)];

  var submit_button = document.querySelector('input[name=submit_btn]');
  submit_button.click();
})();
<commit_msg>Add an option to toggle on/off filter by topic.<commit_after>// ==UserScript==
// @name         Douban Group Dingbot
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Douban Group topics auto comments.
// @author       You
// @match        https://www.douban.com/group/topic/*
// @grant        window.close
// ==/UserScript==

(function() {
  'use strict';

  function random_int (min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min;
  }

  var filter_by_topic = true;   // whether or not to filter post by topic
  var topic = 'PPResume';
  var title = document.getElementsByTagName('h1')[0].textContent;
  var is_ppresume_topic = (title.toUpperCase().indexOf(topic.toUpperCase()) == -1 ? false : true);

  if (filter_by_topic) {
    if (! is_ppresume_topic) {
      console.log("This is not a " + topic + " topic, you've made a wrong choice, my master...");
      return;
    }
  }

  var words = ['喵', '汪', '嗷', '咩', '哞', '呱',
               '吱', '喔', '叽', '嗡', '咿', '嘶',
               '喳', '嘎', '咕', '哇', '呜', '嗥'];

  var has_captcha = document.getElementById('captcha_image');
  if (has_captcha) {
    console.log("This page has captcha image, I can't post for you, master, sorry...");
    return;
  }
  var textarea = document.querySelector('textarea[id=last]');
  if (! textarea) {
    console.log("You've just posted a comment already, I'll close the window and exit...");
    setTimeout(function () { window.close(); }, 3000);
    return;
  }

  textarea.innerHTML = words[random_int(0, words.length)];

  var submit_button = document.querySelector('input[name=submit_btn]');
  submit_button.click();
})();
<|endoftext|>


<commit_before>module.exports = {
  title: "Alfred documentation",
  description:
    "Documentation of Alfred, an app for BAM alignment statistics, feature counting and annotation",
  themeConfig: {
    repo: "tobiasrausch/alfred",
    nav: [
      { text: "Home", link: "/" },
      { text: "Installation", link: "/installation/" },
      { text: "Usage", link: "/cli/" },
      { text: "Web App", link: "/webapp/" },
      { text: "FAQ", link: "/faq/" }
    ],
    sidebar: ["/installation/", "/cli/", "/webapp/", "/faq/"]
  },
  plugins: {
    "@vuepress/back-to-top": true
  }
};
<commit_msg>docs: set base url for deployment<commit_after>module.exports = {
  title: "Alfred documentation",
  description:
    "Documentation of Alfred, an app for BAM alignment statistics, feature counting and annotation",
  base: "/docs/alfred/",
  themeConfig: {
    repo: "tobiasrausch/alfred",
    nav: [
      { text: "Home", link: "/" },
      { text: "Installation", link: "/installation/" },
      { text: "Usage", link: "/cli/" },
      { text: "Web App", link: "/webapp/" },
      { text: "FAQ", link: "/faq/" }
    ],
    sidebar: ["/installation/", "/cli/", "/webapp/", "/faq/"]
  },
  plugins: {
    "@vuepress/back-to-top": true
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as history from 'history';

import useUrlRouting from './use-url-routing';

Enzyme.configure({ adapter: new Adapter() });

describe('useUrlRouting', () => {
  const pushMock = jest.fn();

  history.createBrowserHistory = () => ({
    push: pushMock,
    listen: jest.fn(),
    replace: jest.fn()
  });
  describe('navigateToNext', () => {
    it('navigates to next slideElement when navigateToNext is called', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 2, 1: 0, 2: 0, 3: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=0&slideElement=1');
    });
    it('navigates to next slide when navigateToNext is called and no slideElements', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0, 1: 0, 2: 0, 3: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=1&slideElement=-1');
    });
    it('url doesnt change when navigateToNext is called and no slideElements or slides left', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).not.toBeCalled();
    });
    it('if loop === true then when navigateToNext is called and no slideElements or slides left it goes to first slide', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0, 1: 0 },
        currentSlide: 1,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: true,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=0&slideElement=-1');
    });
  });
});
<commit_msg>task/testing<commit_after>import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as history from 'history';

import useUrlRouting from './use-url-routing';

Enzyme.configure({ adapter: new Adapter() });

describe('useUrlRouting', () => {
  const pushMock = jest.fn();

  history.createBrowserHistory = () => ({
    push: pushMock,
    listen: jest.fn(),
    replace: jest.fn(),
    url: ''
  });
  describe('navigateToNext', () => {
    it('navigates to next slideElement when navigateToNext is called', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 2, 1: 0, 2: 0, 3: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=0&slideElement=1');
    });
    it('navigates to next slide when navigateToNext is called and no slideElements', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0, 1: 0, 2: 0, 3: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=1&slideElement=-1');
    });
    it('url doesnt change when navigateToNext is called and no slideElements or slides left', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0 },
        currentSlide: 0,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).not.toBeCalled();
    });
    it('if loop === true then when navigateToNext is called and no slideElements or slides left it goes to first slide', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0, 1: 0 },
        currentSlide: 1,
        currentSlideElement: 0,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: true,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToNext } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to next button"
              onClick={() => navigateToNext()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to next button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?slide=0&slideElement=-1');
    });
  });
  describe('navigateToPrevious', () => {
    it('navigates to prev slideElement when navigateToPrevious is called', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 2, 1: 2, 2: 0, 3: 0 },
        currentSlide: 1,
        currentSlideElement: 2,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToPrevious } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to prev button"
              onClick={() => navigateToPrevious()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to prev button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?immediate=true&slide=1&slideElement=1');
    });
    it('navigates to prev slide when navigateToPrevious is called when no more slideElements remaining', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 2, 1: 2, 2: 0, 3: 0 },
        currentSlide: 1,
        currentSlideElement: -1,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToPrevious } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to prev button"
              onClick={() => navigateToPrevious()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to prev button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith('?immediate=true&slide=0&slideElement=1');
    });
    it('navigates to prev slide when navigateToPrevious is called when no more slideElements remaining', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0 },
        currentSlide: 0,
        currentSlideElement: -1,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: false,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToPrevious } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to prev button"
              onClick={() => navigateToPrevious()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to prev button"]')
        .simulate('click');
      expect(pushMock).not.toBeCalled();
    });
    it('navigates to prev slide when navigateToPrevious is called when no more slideElements remaining', () => {
      const options = {
        dispatch: jest.fn(),
        slideElementMap: { 0: 0, 1: 0 },
        currentSlide: 0,
        currentSlideElement: -1,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: true,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { navigateToPrevious } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="navigate to prev button"
              onClick={() => navigateToPrevious()}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component
        .find('[data-testid="navigate to prev button"]')
        .simulate('click');
      expect(pushMock).toBeCalledWith(
        '?immediate=true&slide=1&slideElement=-1'
      );
    });
  });
  describe('toggleMode', () => {
    it('When calling toggleMode with payload it calls dispatch with that mode', () => {
      const dispatchCallback = jest.fn();
      const options = {
        dispatch: dispatchCallback,
        slideElementMap: { 0: 0, 1: 0 },
        currentSlide: 0,
        currentSlideElement: -1,
        currentPresenterMode: false,
        currentOverviewMode: false,
        currentExportMode: false,
        currentPrintMode: false,
        loop: true,
        animationsWhenGoingBack: false,
        onUrlChange: jest.fn()
      };
      const TestComponent = () => {
        const { toggleMode } = useUrlRouting(options);
        return (
          <>
            <button
              data-testid="toggle mode button"
              onClick={() => toggleMode('fullScreen')}
            ></button>
          </>
        );
      };
      const component = mount(<TestComponent />);
      component.find('[data-testid="toggle mode button"]').simulate('click');
      expect(dispatchCallback).toBeCalledWith({
        type: 'TOGGLE_MODE',
        payload: { mode: 'fullScreen' }
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Boilerplate that all Plugins share - and should not be used
 * directly. It also shows which methods final plugins should implement/override,
 * this deciding on structure.
 *
 * @param {object} main Uppy core object
 * @param {object} object with plugin options
 * @return {array | string} files or success/fail message
 */
export default class Plugin {

  constructor (core, opts) {
    this.core = core
    this.opts = opts
    this.type = 'none'
    this.name = this.constructor.name
  }

  // setProgress (percentage, current, total) {
  //   var finalPercentage = percentage
  //
  //   // if (current !== undefined && total !== undefined) {
  //   //   var percentageOfTotal = (percentage / total);
  //   //   // finalPercentage = percentageOfTotal;
  //   //   if (current > 1) {
  //   //     finalPercentage = percentage + (100 / (total * current));
  //   //   } else {
  //   //     finalPercentage = percentage;
  //   //   }
  //   // }
  //
  //   this.core.setProgress(this, finalPercentage)
  // }

  /**
   * Check if supplied `target` is a `string` or an `object`.
   * If object (that means its a plugin), search `plugins` for
   * a plugin with same name and return its target.
   *
   * @param {String|Object} target
   *
   */
  getTarget (target) {
    if (typeof target === 'string') {
      this.core.log('string is a target')
      return target
    } else {
      this.core.log('plugin is a target')

      let pluginTargets

      for (const pluginType in this.core.plugins) {
        const plugins = this.core.plugins[pluginType]
        plugins.forEach(plugin => {
          if (plugin.constructor.name === target.name) {
            pluginTargets = plugin.targets
          }
        })
      }

      return pluginTargets
    }
  }

  extractFiles (results) {
    console.log({
      class: 'Plugin',
      method: 'extractFiles',
      results: results
    })

    // check if the results array is empty
    // if (!results || !results.count) {
    //   return results
    // }

    const files = []
    results.forEach(result => {
      try {
        Array.from(result.files).forEach(file => files.push(file))
      } catch (e) {
        console.log(e)
      }
    })

    // const files = [];
    // for (let i in results) {
    //   for (let j in results[i].files) {
    //     files.push(results[i].files.item(j));
    //   for (let j in results[i].files) {
    //     // files.push(results[i].files.item(j));
    //   }
    // }

    // return Array.from(fileList);
    return files
  }

  run (results) {
    return results
  }

  install () {
    return
  }
}
<commit_msg>Refactoring of `getTarget()`<commit_after>/**
 * Boilerplate that all Plugins share - and should not be used
 * directly. It also shows which methods final plugins should implement/override,
 * this deciding on structure.
 *
 * @param {object} main Uppy core object
 * @param {object} object with plugin options
 * @return {array | string} files or success/fail message
 */
export default class Plugin {

  constructor (core, opts) {
    this.core = core
    this.opts = opts
    this.type = 'none'
    this.name = this.constructor.name
  }

  // setProgress (percentage, current, total) {
  //   var finalPercentage = percentage
  //
  //   // if (current !== undefined && total !== undefined) {
  //   //   var percentageOfTotal = (percentage / total);
  //   //   // finalPercentage = percentageOfTotal;
  //   //   if (current > 1) {
  //   //     finalPercentage = percentage + (100 / (total * current));
  //   //   } else {
  //   //     finalPercentage = percentage;
  //   //   }
  //   // }
  //
  //   this.core.setProgress(this, finalPercentage)
  // }

  /**
   * Check if supplied `target` is a `string` or an `object`.
   * If object (that means its a plugin), search `plugins` for
   * a plugin with same name and return its target.
   *
   * @param {String|Object} target
   *
   */
  getTarget (target) {
    if (typeof target === 'string') {
      this.core.log('string is a target')
      return target
    } else {
      this.core.log('plugin is a target')

      let pluginTargets

      Object.keys(this.core.plugins).forEach(pluginType => {
        const plugins = this.core.plugins[pluginType]
        plugins.forEach(plugin => {
          if (plugin.constructor.name === target.name) {
            pluginTargets = plugin.targets
          }
        })
      })

      return pluginTargets
    }
  }

  extractFiles (results) {
    console.log({
      class: 'Plugin',
      method: 'extractFiles',
      results: results
    })

    // check if the results array is empty
    // if (!results || !results.count) {
    //   return results
    // }

    const files = []
    results.forEach(result => {
      try {
        Array.from(result.files).forEach(file => files.push(file))
      } catch (e) {
        console.log(e)
      }
    })

    // const files = [];
    // for (let i in results) {
    //   for (let j in results[i].files) {
    //     files.push(results[i].files.item(j));
    //   for (let j in results[i].files) {
    //     // files.push(results[i].files.item(j));
    //   }
    // }

    // return Array.from(fileList);
    return files
  }

  run (results) {
    return results
  }

  install () {
    return
  }
}
<|endoftext|>