<commit_before>/**
 * @flow
 * @private
 */

import createLog from 'silk-log';
import fs from 'mz/fs';
import events from 'events';

import bindings from './player';

import type {PlayerType} from './player';

const log = createLog('audioplayer');
const GAIN_MIN = 0.0;
const GAIN_MAX = 1.0;

/**
 * The available media states
 *

 *
idle      - Audio playback hasn't started yet

 *
preparing - Audio is preparing for playback

 *
prepared  - Audio stream is being prepared to play

 *
playing   - Audio playback has started

 *
stopped   - Audio playback has stopped

 *
paused    - Audio playback has paused

 *

 * @memberof silk-audioplayer
 */
type MediaState =
  'idle' |
  'preparing' |
  'prepared' |
  'playing' |
  'paused' |
  'stopped';

/**
 * Information about an audio file
 *
 * @memberof silk-audioplayer
 * @property {string} name name of the audio file
 */
type FileInfo = {
  name: string;
};

/**
 * This module provides an interface to play audio files or audio streams.
 *
 *
 *
 * Valid and invalid states
 *

 *

 * Method
 * Valid States
 * Comments
 *

 *

 * endOfStream
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * getCurrentPosition
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * getDuration
 * {preparing, prepared, playing, paused}
 * Successful invoke of this method in a valid state does not change the
 * player state.
 *

 *

 * getInfo
 * {preparing, prepared, playing, paused, stopped}
 * Successful invoke of this method in a valid state does not change the
 * player state.
 *

 *

 * getState
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * pause
 * {playing}
 * Successful invoke of this method in a valid state transfers the player
 * to the paused state. Calling this method in an invalid state transfers
 * the player to the stopped state.
 *

 *

 * play
 * {idle, stopped}
 * Successful invoke of this method in a valid state transfers the player
 * through preparing, prepared and playing state. Calling
 * this method in an invalid state transfers the player to the stopped
 * state.
 *

 *

 * resume
 * {paused}
 * Successful invoke of this method in a valid state transfers the player
 * to the playing state. Calling this method in an invalid state transfers
 * the player to the stopped state.
 *

 *

 * setVolume
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * stop
 * {preparing, prepared, playing, paused}
 * Successful invoke of this method in a valid as well as invalid state
 * transfers the player to the stopped state.
 *

 *

 * write
 * {idle, stopped}
 * Successful invoke of this method in a valid state transfers the player
 * through preparing, prepared and playing state. Calling
 * this method in an invalid state transfers the player to the stopped
 * state.
 *

 *

 *
 * @module silk-audioplayer
 *
 * @example
 * Example1 - Play an audio file
 *
 * const Player = require('silk-audioplayer').default;
 * const log = require('silk-alog');
 * const player = new Player();
 *
 * player.setVolume(1.0);
 * player.play('data/media/test.mp3')
 * .then(() => log.info('Done playing'))
 * .catch(err => log.error(err));
 *
 * player.on('started', () => {
 *   player.pause();
 *   log.info(`getState ${player.getState()}`);
 *
 *   player.setVolume(0.5);
 *   player.resume();
 *
 *   log.info(`getState ${player.getState()}`);
 *   log.info(`getCurrentPosition ${player.getCurrentPosition()}`);
 *   log.info(`getDuration ${player.getDuration()}`);
 *   log.info(`getInfo ${JSON.stringify(player.getInfo())}`);
 * });
 *
 *
 * Example2 - Play an audio stream
 *
 * const Player = require('silk-audioplayer').default;
 * const https = require('https');
 * const log = require('silk-alog');
 * const player = new Player();
 *
 * https.get('https://test.mp3', (res) => {
 *  res.once('error', (err) => log.error(err));
 *  res.on('data', data => player.write(data));
 *  res.once('end', () => {
 *    if (res.statusCode !== 200) {
 *      log.error(`status code ${res.statusCode}, error \'${res.statusMessage}\'`);
 *    } else {
 *      log.info(`Request complete`);
 *      player.endOfStream();
 *    }
 *  });
 * });
 */

export default class Player extends events.EventEmitter {

  _gain: number = GAIN_MAX;
  _player: PlayerType = null;
  _mediaState: MediaState = 'idle';
  _fileName: string = '';
  _playPromiseAccept: ?(value: Promise<void> | void) => void = null;
  _playPromiseReject: ?(error: Error) => void = null;

  constructor() {
    super();
    this._player = new bindings.Player();
    this._player.addEventListener((event, err) => {
      // process.nextTick doesn't work here as the caller of this
      // callback needs to finish before the nextTick happens, which isn't
      // the case here.
      setTimeout(() => this._nativeEventListener(event, err), 0);
    });
  }

  /**
   * Sets the specified output gain value on all channels of this sound file.
   * Gain values are clamped to the closed interval [0.0, 1.0]. A value of 0.0
   * results in zero gain (silence), and a value of 1.0 means signal unchanged.
   * The default value is 1.0. Audio player volume can be set before or during
   * the playback.
   *
   * @param gain output gain for all channels
   * @memberof silk-audioplayer
   * @instance
   */
  setVolume(gain: number) {
    this._gain = this._clampGain(gain);
    this._player.setVolume(this._gain);
  }

  /**
   * @private
   */
  _clampGain(gainOrLevel: number) {
    if (isNaN(parseFloat(gainOrLevel))) {
      throw new Error(`${gainOrLevel} is not a valid floating point number`);
    }
    if (gainOrLevel < GAIN_MIN) {
      gainOrLevel = GAIN_MIN;
    } else if (gainOrLevel > GAIN_MAX) {
      gainOrLevel = GAIN_MAX;
    }
    return gainOrLevel;
  }

  /**
   * Play an audio file.
   *
   * @param fileName Name of the audio file to play
   * @return {Promise} Return a promise that is fulfilled when the sound is
   *                   done playing.
   * @memberof silk-audioplayer
   * @instance
   */
  async play(fileName: string): Promise<void> {
    let exists = await fs.exists(fileName);
    if (!exists) {
      this._mediaState = 'stopped';
      throw new Error(`${fileName} not found`);
    }

    if ((this._mediaState !== 'idle') && (this._mediaState !== 'stopped')) {
      this._mediaState = 'stopped';
      throw new Error(`Invalid state for play operation`);
    }

    this._fileName = fileName;

    return new Promise((resolve, reject) => {
      this._playPromiseAccept = resolve;
      this._playPromiseReject = reject;

      this._mediaState = 'preparing';
      this._player.setDataSource(bindings.DATA_SOURCE_TYPE_FILE, fileName);
      this._player.start();
    });
  }

  /**
   * Write audio buffer to the player's queue to be played. This method is
   * analagous to play method but for streaming uses cases instead of audio
   * files.
   *
   * @param chunk buffer containing audio data to be played
   * @memberof silk-audioplayer
   * @instance
   */
  write(chunk: Buffer) {
    // Prepare stream player with BufferedDataSource
    if ((this._mediaState === 'idle') || (this._mediaState === 'stopped')) {
      this._mediaState = 'preparing';
      this._player.setDataSource(bindings.DATA_SOURCE_TYPE_BUFFER);
      this._player.start();
    }

    if (this._player.write(chunk, chunk.length) <= 0) {
      this._onError(`Failed to queue buffer to play`);
      return;
    }
  }

  /**
   * Stop the currently playing audio file or an audio stream. Same
   * instance of audioplayer can be reused to play another file or stream after
   * the current instance has finished playback or has been stopped by calling
   * stop on audioplayer.
   * @memberof silk-audioplayer
   * @instance
   */
  stop() {
    if ((this._mediaState === 'idle') || (this._mediaState === 'stopped')) {
      this._onError(`Invalid state for stop operation`);
      return;
    }
    this._player.stop();
  }

  /**
   * Pause the currently playing audio file or an audio stream
   * @memberof silk-audioplayer
   * @instance
   */
  pause() {
    if (this._mediaState !== 'playing') {
      this._onError(`Invalid state for pause operation`);
      return;
    }
    this._player.pause();
  }

  /**
   * Resume the currently paused audio file or an audio stream
   * @memberof silk-audioplayer
   * @instance
   */
  resume() {
    if (this._mediaState !== 'paused') {
      this._onError(`Invalid state for resume operation`);
      return;
    }
    this._player.resume();
  }

  /**
   * Gets the current state of audio player
   * @return {MediaState} the current audio player state
   * @memberof silk-audioplayer
   * @instance
   */
  getState(): MediaState {
    return this._mediaState;
  }

  /**
   * Gets the current playback position
   * @return {number} the current position in milliseconds
   * @memberof silk-audioplayer
   * @instance
   */
  getCurrentPosition(): number {
    return this._player.getCurrentPosition();
  }

  /**
   * Gets the duration of the file or an audio stream.
   * @return {number} the duration in milliseconds
   * @memberof silk-audioplayer
   * @instance
   */
  getDuration(): number {
    return this._player.getDuration();
  }

  /**
   * Gets the information about an audio file being played
   * @return {FileInfo}
   * @memberof silk-audioplayer
   * @instance
   */
  getInfo(): FileInfo {
    return {
      name: this._fileName,
    };
  }

  /**
   * Mark the end of audio stream. This API doesn't stop the audio streaming
   * but rather tells the audio player to stop when all the buffers in the audio
   * queue are done playing.
   *
   * @memberof silk-audioplayer
   * @instance
   */
  endOfStream() {
    this._player.endOfStream();
  }

  /**
   * @private
   */
  _nativeEventListener = (event: string, err: string) => {
    log.debug(`received event: ${event}`);

    switch (event) {
    case 'prepared':
      /**
       * This event is emitted when audio player is ready to play back audio
       *
       * @event prepared
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'prepared';
      break;
    case 'started':
      /**
       * This event is emitted when audio playback has started
       *
       * @event started
       * @memberof silk-audioplayer
       * @instance
       */
      if (this._mediaState === 'paused') {
        /**
         * This event is emitted when audio playback has resumed
         *
         * @event resumed
         * @memberof silk-audioplayer
         * @instance
         */
        event = 'resumed';
      }
      this._mediaState = 'playing';
      break;
    case 'paused':
      /**
       * This event is emitted when audio playback has paused
       *
       * @event paused
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'paused';
      break;
    case 'done':
      /**
       * This event is emitted when audio playback has finished
       *
       * @event done
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'stopped';
      if (this._playPromiseAccept) {
        this._playPromiseAccept();
        this._playPromiseAccept = null;
        this._playPromiseReject = null;
      }
      break;
    case 'error':
      /**
       * This event is emitted when there is an error in audio playback
       *
       * @event error
       * @property {Error} error reason
       * @memberof silk-audioplayer
       * @instance
       */
      this._player.stop(); // Stop player if not already
      this._mediaState = 'stopped';
      if (this._playPromiseReject) {
        this._playPromiseReject(new Error(err));
        this._playPromiseAccept = null;
        this._playPromiseReject = null;
      }
      break;
    default:
      log.warn(`Unknown event ${event}`);
      break;
    }
    this.emit(event, new Error(err));
  };

  _onError(err: string) {
    log.debug(`Error`, err);
    this._nativeEventListener('error', err);
  }
}
<commit_msg>Don't throw error for invalid states<commit_after>/**
 * @flow
 * @private
 */

import createLog from 'silk-log';
import fs from 'mz/fs';
import events from 'events';

import bindings from './player';

import type {PlayerType} from './player';

const log = createLog('audioplayer');
const GAIN_MIN = 0.0;
const GAIN_MAX = 1.0;

/**
 * The available media states
 *

 *
idle      - Audio playback hasn't started yet

 *
preparing - Audio is preparing for playback

 *
prepared  - Audio stream is being prepared to play

 *
playing   - Audio playback has started

 *
stopped   - Audio playback has stopped

 *
paused    - Audio playback has paused

 *

 * @memberof silk-audioplayer
 */
type MediaState =
  'idle' |
  'preparing' |
  'prepared' |
  'playing' |
  'paused' |
  'stopped';

/**
 * Information about an audio file
 *
 * @memberof silk-audioplayer
 * @property {string} name name of the audio file
 */
type FileInfo = {
  name: string;
};

/**
 * This module provides an interface to play audio files or audio streams.
 *
 *
 *
 * Valid and invalid states
 *

 *

 * Method
 * Valid States
 * Comments
 *

 *

 * endOfStream
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * getCurrentPosition
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * getDuration
 * {preparing, prepared, playing, paused}
 * Successful invoke of this method in a valid state does not change the
 * player state.
 *

 *

 * getInfo
 * {preparing, prepared, playing, paused, stopped}
 * Successful invoke of this method in a valid state does not change the
 * player state.
 *

 *

 * getState
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * pause
 * {playing}
 * Successful invoke of this method in a valid state transfers the player
 * to the paused state. Calling this method in an invalid state transfers
 * the player to the stopped state.
 *

 *

 * play
 * {idle, stopped}
 * Successful invoke of this method in a valid state transfers the player
 * through preparing, prepared and playing state. Calling
 * this method in an invalid state transfers the player to the stopped
 * state.
 *

 *

 * resume
 * {paused}
 * Successful invoke of this method in a valid state transfers the player
 * to the playing state. Calling this method in an invalid state transfers
 * the player to the stopped state.
 *

 *

 * setVolume
 * any
 * This method can be called in any state and calling it does not change the
 * player state.
 *

 *

 * stop
 * {preparing, prepared, playing, paused}
 * Successful invoke of this method in a valid as well as invalid state
 * transfers the player to the stopped state.
 *

 *

 * write
 * {idle, stopped}
 * Successful invoke of this method in a valid state transfers the player
 * through preparing, prepared and playing state. Calling
 * this method in an invalid state transfers the player to the stopped
 * state.
 *

 *

 *
 * @module silk-audioplayer
 *
 * @example
 * Example1 - Play an audio file
 *
 * const Player = require('silk-audioplayer').default;
 * const log = require('silk-alog');
 * const player = new Player();
 *
 * player.setVolume(1.0);
 * player.play('data/media/test.mp3')
 * .then(() => log.info('Done playing'))
 * .catch(err => log.error(err));
 *
 * player.on('started', () => {
 *   player.pause();
 *   log.info(`getState ${player.getState()}`);
 *
 *   player.setVolume(0.5);
 *   player.resume();
 *
 *   log.info(`getState ${player.getState()}`);
 *   log.info(`getCurrentPosition ${player.getCurrentPosition()}`);
 *   log.info(`getDuration ${player.getDuration()}`);
 *   log.info(`getInfo ${JSON.stringify(player.getInfo())}`);
 * });
 *
 *
 * Example2 - Play an audio stream
 *
 * const Player = require('silk-audioplayer').default;
 * const https = require('https');
 * const log = require('silk-alog');
 * const player = new Player();
 *
 * https.get('https://test.mp3', (res) => {
 *  res.once('error', (err) => log.error(err));
 *  res.on('data', data => player.write(data));
 *  res.once('end', () => {
 *    if (res.statusCode !== 200) {
 *      log.error(`status code ${res.statusCode}, error \'${res.statusMessage}\'`);
 *    } else {
 *      log.info(`Request complete`);
 *      player.endOfStream();
 *    }
 *  });
 * });
 */

export default class Player extends events.EventEmitter {

  _gain: number = GAIN_MAX;
  _player: PlayerType = null;
  _mediaState: MediaState = 'idle';
  _fileName: string = '';
  _playPromiseAccept: ?(value: Promise<void> | void) => void = null;
  _playPromiseReject: ?(error: Error) => void = null;

  constructor() {
    super();
    this._player = new bindings.Player();
    this._player.addEventListener((event, err) => {
      // process.nextTick doesn't work here as the caller of this
      // callback needs to finish before the nextTick happens, which isn't
      // the case here.
      setTimeout(() => this._nativeEventListener(event, err), 0);
    });
  }

  /**
   * Sets the specified output gain value on all channels of this sound file.
   * Gain values are clamped to the closed interval [0.0, 1.0]. A value of 0.0
   * results in zero gain (silence), and a value of 1.0 means signal unchanged.
   * The default value is 1.0. Audio player volume can be set before or during
   * the playback.
   *
   * @param gain output gain for all channels
   * @memberof silk-audioplayer
   * @instance
   */
  setVolume(gain: number) {
    this._gain = this._clampGain(gain);
    this._player.setVolume(this._gain);
  }

  /**
   * @private
   */
  _clampGain(gainOrLevel: number) {
    if (isNaN(parseFloat(gainOrLevel))) {
      throw new Error(`${gainOrLevel} is not a valid floating point number`);
    }
    if (gainOrLevel < GAIN_MIN) {
      gainOrLevel = GAIN_MIN;
    } else if (gainOrLevel > GAIN_MAX) {
      gainOrLevel = GAIN_MAX;
    }
    return gainOrLevel;
  }

  /**
   * Play an audio file.
   *
   * @param fileName Name of the audio file to play
   * @return {Promise} Return a promise that is fulfilled when the sound is
   *                   done playing.
   * @memberof silk-audioplayer
   * @instance
   */
  async play(fileName: string): Promise<void> {
    let exists = await fs.exists(fileName);
    if (!exists) {
      this._mediaState = 'stopped';
      throw new Error(`${fileName} not found`);
    }

    if ((this._mediaState !== 'idle') && (this._mediaState !== 'stopped')) {
      this._mediaState = 'stopped';
      throw new Error(`Invalid state for play operation`);
    }

    this._fileName = fileName;

    return new Promise((resolve, reject) => {
      this._playPromiseAccept = resolve;
      this._playPromiseReject = reject;

      this._mediaState = 'preparing';
      this._player.setDataSource(bindings.DATA_SOURCE_TYPE_FILE, fileName);
      this._player.start();
    });
  }

  /**
   * Write audio buffer to the player's queue to be played. This method is
   * analagous to play method but for streaming uses cases instead of audio
   * files.
   *
   * @param chunk buffer containing audio data to be played
   * @memberof silk-audioplayer
   * @instance
   */
  write(chunk: Buffer) {
    // Prepare stream player with BufferedDataSource
    if ((this._mediaState === 'idle') || (this._mediaState === 'stopped')) {
      this._mediaState = 'preparing';
      this._player.setDataSource(bindings.DATA_SOURCE_TYPE_BUFFER);
      this._player.start();
    }

    if (this._player.write(chunk, chunk.length) <= 0) {
      this._onError(`Failed to queue buffer to play`);
      return;
    }
  }

  /**
   * Stop the currently playing audio file or an audio stream. Same
   * instance of audioplayer can be reused to play another file or stream after
   * the current instance has finished playback or has been stopped by calling
   * stop on audioplayer.
   * @memberof silk-audioplayer
   * @instance
   */
  stop() {
    if ((this._mediaState === 'idle') || (this._mediaState === 'stopped')) {
      return;
    }
    this._player.stop();
  }

  /**
   * Pause the currently playing audio file or an audio stream
   * @memberof silk-audioplayer
   * @instance
   */
  pause() {
    if (this._mediaState !== 'playing') {
      return;
    }
    this._player.pause();
  }

  /**
   * Resume the currently paused audio file or an audio stream
   * @memberof silk-audioplayer
   * @instance
   */
  resume() {
    if (this._mediaState !== 'paused') {
      return;
    }
    this._player.resume();
  }

  /**
   * Gets the current state of audio player
   * @return {MediaState} the current audio player state
   * @memberof silk-audioplayer
   * @instance
   */
  getState(): MediaState {
    return this._mediaState;
  }

  /**
   * Gets the current playback position
   * @return {number} the current position in milliseconds
   * @memberof silk-audioplayer
   * @instance
   */
  getCurrentPosition(): number {
    return this._player.getCurrentPosition();
  }

  /**
   * Gets the duration of the file or an audio stream.
   * @return {number} the duration in milliseconds
   * @memberof silk-audioplayer
   * @instance
   */
  getDuration(): number {
    return this._player.getDuration();
  }

  /**
   * Gets the information about an audio file being played
   * @return {FileInfo}
   * @memberof silk-audioplayer
   * @instance
   */
  getInfo(): FileInfo {
    return {
      name: this._fileName,
    };
  }

  /**
   * Mark the end of audio stream. This API doesn't stop the audio streaming
   * but rather tells the audio player to stop when all the buffers in the audio
   * queue are done playing.
   *
   * @memberof silk-audioplayer
   * @instance
   */
  endOfStream() {
    this._player.endOfStream();
  }

  /**
   * @private
   */
  _nativeEventListener = (event: string, err: string) => {
    log.debug(`received event: ${event}`);

    switch (event) {
    case 'prepared':
      /**
       * This event is emitted when audio player is ready to play back audio
       *
       * @event prepared
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'prepared';
      break;
    case 'started':
      /**
       * This event is emitted when audio playback has started
       *
       * @event started
       * @memberof silk-audioplayer
       * @instance
       */
      if (this._mediaState === 'paused') {
        /**
         * This event is emitted when audio playback has resumed
         *
         * @event resumed
         * @memberof silk-audioplayer
         * @instance
         */
        event = 'resumed';
      }
      this._mediaState = 'playing';
      break;
    case 'paused':
      /**
       * This event is emitted when audio playback has paused
       *
       * @event paused
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'paused';
      break;
    case 'done':
      /**
       * This event is emitted when audio playback has finished
       *
       * @event done
       * @memberof silk-audioplayer
       * @instance
       */
      this._mediaState = 'stopped';
      if (this._playPromiseAccept) {
        this._playPromiseAccept();
        this._playPromiseAccept = null;
        this._playPromiseReject = null;
      }
      break;
    case 'error':
      /**
       * This event is emitted when there is an error in audio playback
       *
       * @event error
       * @property {Error} error reason
       * @memberof silk-audioplayer
       * @instance
       */
      this._player.stop(); // Stop player if not already
      this._mediaState = 'stopped';
      if (this._playPromiseReject) {
        this._playPromiseReject(new Error(err));
        this._playPromiseAccept = null;
        this._playPromiseReject = null;
      }
      break;
    default:
      log.warn(`Unknown event ${event}`);
      break;
    }
    this.emit(event, new Error(err));
  };

  _onError(err: string) {
    log.debug(`Error`, err);
    this._nativeEventListener('error', err);
  }
}
<|endoftext|>


<commit_before>// Declare collections.
MaintMode = new Mongo.Collection('maintenance-mode');

// Startup functions.
Meteor.startup(function () {
  // Add default maintenance mode document if missing.
  if (!MaintMode.find().count()) {
    MaintMode.insert( { status: false, message: "This site is currently under maintenance. We should be back shortly. Thank you for your patience." } );
  }
});

<commit_msg>Method to return the current maint mode status<commit_after>// Declare collections.
MaintMode = new Mongo.Collection('maintenance-mode');

// Startup functions.
Meteor.startup(function () {
  // Add default maintenance mode document if missing.
  if (!MaintMode.find().count()) {
    MaintMode.insert( { status: false, message: "This site is currently under maintenance. We should be back shortly. Thank you for your patience." } );
  }
});

// Method for checking maintenance mode status.
Meteor.methods({
  MaintModeStatus: function () {
    return MaintMode.findOne();
  }
});
<|endoftext|>


<commit_before>/*
 * Load files *locally* (GeoJSON, KML, GPX) into the map
 * using the HTML5 File API.
 *
 * Requires Pavel Shramov's GPX.js
 * https://github.com/shramov/leaflet-plugins/blob/d74d67/layer/vector/GPX.js
 */
var FileLoader = L.Class.extend({
    includes: L.Mixin.Events,
    options: {
        layerOptions: {}
    },

    initialize: function (map, options) {
        this._map = map;
        L.Util.setOptions(this, options);

        this._parsers = {
            'geojson': this._loadGeoJSON,
            'gpx': this._convertToGeoJSON,
            'kml': this._convertToGeoJSON
        };
    },

    load: function (file /* File */) {
        // Check file extension
        var ext = file.name.split('.').pop(),
            parser = this._parsers[ext];
        if (!parser) {
            window.alert("Unsupported file type " + file.type + '(' + ext + ')');
            return;
        }
        // Read selected file using HTML5 File API
        var reader = new FileReader();
        reader.onload = L.Util.bind(function (e) {
            this.fire('data:loading', {filename: file.name, format: ext});
            var layer = parser.call(this, e.target.result, ext);
            this.fire('data:loaded', {layer: layer, filename: file.name, format: ext});
        }, this);
        reader.readAsText(file);
    },

    _loadGeoJSON: function (content) {
        if (typeof content == 'string') {
            content = JSON.parse(content);
        }
        return L.geoJson(content, this.options.layerOptions).addTo(this._map);
    },

    _convertToGeoJSON: function (content, format) {
        // Format is either 'gpx' or 'kml'
        if (typeof content == 'string') {
            content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
        }
        var geojson = toGeoJSON[format](content);
        return this._loadGeoJSON(geojson);
    }
});

L.Control.FileLayerLoad = L.Control.extend({
    statics: {
        TITLE: 'Load local file (GPX, KML, GeoJSON)',
        LABEL: '⌅'
    },
    options: {
        position: 'topleft',
        fitBounds: true,
        layerOptions: {}
    },

    initialize: function (options) {
        L.Util.setOptions(this, options);
        this.loader = null;
    },

    onAdd: function (map) {
        this.loader = new FileLoader(map, {layerOptions: this.options.layerOptions});

        this.loader.on('data:loaded', function (e) {
            // Fit bounds after loading
            if (this.options.fitBounds) {
                window.setTimeout(function () {
                    map.fitBounds(e.layer.getBounds()).zoomOut();
                }, 500);
            }
        }, this);

        // Initialize Drag-and-drop
        this._initDragAndDrop(map);

        // Initialize map control
        return this._initContainer();
    },

    _initDragAndDrop: function (map) {
        var fileLoader = this.loader,
            dropbox = map._container;

        var callbacks = {
            dragenter: function () {
                map.scrollWheelZoom.disable();
            },
            dragleave: function () {
                map.scrollWheelZoom.enable();
            },
            dragover: function (e) {
                e.stopPropagation();
                e.preventDefault();
            },
            drop: function (e) {
                e.stopPropagation();
                e.preventDefault();

                var files = Array.prototype.slice.apply(e.dataTransfer.files),
                    i = files.length;
                setTimeout(function(){
                    fileLoader.load(files.shift());
                    if (files.length > 0) {
                        setTimeout(arguments.callee, 25);
                    }
                }, 25);
                map.scrollWheelZoom.enable();
            }
        };
        for (var name in callbacks)
            dropbox.addEventListener(name, callbacks[name], false);
    },

    _initContainer: function () {
        // Create an invisible file input
        var fileInput = L.DomUtil.create('input', 'hidden', container);
        fileInput.type = 'file';
        fileInput.accept = '.gpx,.kml,.geojson';
        fileInput.style.display = 'none';
        // Load on file change
        var fileLoader = this.loader;
        fileInput.addEventListener("change", function (e) {
            fileLoader.load(this.files[0]);
        }, false);

        // Create a button, and bind click on hidden file input
        var zoomName = 'leaflet-control-filelayer leaflet-control-zoom',
            barName = 'leaflet-bar',
            partName = barName + '-part',
            container = L.DomUtil.create('div', zoomName + ' ' + barName);
        var link = L.DomUtil.create('a', zoomName + '-in ' + partName, container);
        link.innerHTML = L.Control.FileLayerLoad.LABEL;
        link.href = '#';
        link.title = L.Control.FileLayerLoad.TITLE;

        var stop = L.DomEvent.stopPropagation;
        L.DomEvent
            .on(link, 'click', stop)
            .on(link, 'mousedown', stop)
            .on(link, 'dblclick', stop)
            .on(link, 'click', L.DomEvent.preventDefault)
            .on(link, 'click', function (e) {
                fileInput.click();
                e.preventDefault();
            });
        return container;
    }
});

L.Control.fileLayerLoad = function (options) {
    return new L.Control.FileLayerLoad(options);
};
<commit_msg>Delete leaflet.filelayer.js<commit_after><|endoftext|>


<commit_before>(function () {
  app = angular.module('app',[]);

  app.controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = [];

    $scope.onClick = function(playlist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", playlist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(playlist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  });

  app.controller('NewPLCtrl', function($scope) {
    $scope.onClick = function() {
      $("#new-sporklist").css("visibility", "visible");
      $("#new-sporklist").focus();
      $('#new-sporklist').keyup(function(e){
        if(e.keyCode == 13) {
            var sporklist = Parse.Object.extend("Sporklist");
            var newList = new sporklist();
            newList.set("name", $("#new-sporklist").val());
            newList.set("author", parseUser.getUsername());

            $(this).css("visibility", "hidden");
            $(this).val("");
        }
      });
    };
  });

  app.controller('MainCtrl',function($scope) {
    /* The defaults for the home page.
     * The only thing that should show is the sidebar and the fb login.
     */
    $scope.user = false;
    $scope.friend = false;
    $scope.sporklist = false;
    $scope.search = false;
    $scope.map = false;
  });

  app.controller('MeCtrl', function($scope) {
    $scope.name = "";
    $scope.friendList = [];
    $scope.onClick = function(friend) {
      updateFriend(friend);
    };
  });

  app.controller('FriendCtrl', function($scope) {
    $scope.name = "";
    $scope.sporklists = [];

    $scope.onClick = function(sporklist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", sporklist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(sporklist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  })

  app.controller('sporkCtrl', function($scope) {
    $scope.name = "";
    $scope.restaurants = [];
  });

  app.controller('SearchCtrl', function($scope) {
    $scope.results = [];
  });

}());
<commit_msg>working on adding playlists<commit_after>(function () {
  app = angular.module('app',[]);

  app.controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = [];

    $scope.onClick = function(playlist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", playlist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(playlist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  });

  app.controller('NewPLCtrl', function($scope) {
    $scope.onClick = function() {
      $("#new-sporklist").css("visibility", "visible");
      $("#new-sporklist").focus();
      $('#new-sporklist').keyup(function(e){
        if(e.keyCode == 13) {
            var sporklist = Parse.Object.extend("Sporklist");
            var newList = new sporklist();
            newList.set("name", $("#new-sporklist").val());
            newList.set("author", parseUser.getUsername());
            newList.save();

            $(this).css("visibility", "hidden");
            $(this).val("");
        }
      });
    };
  });

  app.controller('MainCtrl',function($scope) {
    /* The defaults for the home page.
     * The only thing that should show is the sidebar and the fb login.
     */
    $scope.user = false;
    $scope.friend = false;
    $scope.sporklist = false;
    $scope.search = false;
    $scope.map = false;
  });

  app.controller('MeCtrl', function($scope) {
    $scope.name = "";
    $scope.friendList = [];
    $scope.onClick = function(friend) {
      updateFriend(friend);
    };
  });

  app.controller('FriendCtrl', function($scope) {
    $scope.name = "";
    $scope.sporklists = [];

    $scope.onClick = function(sporklist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", sporklist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(sporklist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  })

  app.controller('sporkCtrl', function($scope) {
    $scope.name = "";
    $scope.restaurants = [];
  });

  app.controller('SearchCtrl', function($scope) {
    $scope.results = [];
  });

}());
<|endoftext|>


<commit_before>"use strict";

goog.provide("Entry");

Entry = {};

Entry.block = {};

Entry.TEXT_ALIGN_CENTER = 0;

Entry.TEXT_ALIGN_LEFT = 1;

Entry.TEXT_ALIGN_RIGHT = 2;

Entry.TEXT_ALIGNS = ["center", "left", "right"];

Entry.clipboard = null;

/**
 * Load project
 * @param {?Project} project
 */
Entry.loadProject = function(project) {
    if (!project) {
        project = Entry.getStartProject(Entry.mediaFilePath);
    }

    if (this.type == 'workspace')
        Entry.stateManager.startIgnore();
    Entry.projectId = project._id;
    Entry.variableContainer.setVariables(project.variables);
    Entry.variableContainer.setMessages(project.messages);
    Entry.scene.addScenes(project.scenes);
    Entry.stage.initObjectContainers();
    Entry.variableContainer.setFunctions(project.functions);
    Entry.container.setObjects(project.objects);
    Entry.FPS = project.speed ? project.speed : 60;
    createjs.Ticker.setFPS(Entry.FPS);

    if (!Entry.engine.projectTimer)
        Entry.variableContainer.generateTimer();

    if (Object.keys(Entry.container.inputValue).length === 0)
        Entry.variableContainer.generateAnswer();
    Entry.start();
    if (this.options.programmingMode) {

        var mode = this.options.programmingMode;
        if (Entry.Utils.isNumber(mode)) {
            var pMode = mode;
            mode = {};

            this.mode = mode;
            if (pMode == 0) {
                mode.boardType = Entry.Workspace.MODE_BOARD;
                mode.textType = -1;
            } else if (pMode == 1) { // Python in Text Coding
                mode.boardType = Entry.Workspace.MODE_VIMBOARD;
                mode.textType = Entry.Vim.TEXT_TYPE_PY;
                mode.runType = Entry.Vim.WORKSPACE_MODE;
            } else if (pMode == 2) { // Javascript in Text Coding
                mode.boardType = Entry.Workspace.MODE_VIMBOARD;
                mode.textType = Entry.Vim.TEXT_TYPE_JS;
                mode.runType = Entry.Vim.MAZE_MODE;
            }
            Entry.getMainWS().setMode(mode);
        }
    }

    Entry.Loader.isLoaded() && Entry.Loader.handleLoad();

    if (this.type == 'workspace')
        Entry.stateManager.endIgnore();

    if (project.interface && Entry.options.loadInterface)
        Entry.loadInterfaceState(project.interface);

    if (window.parent && window.parent.childIframeLoaded)
        window.parent.childIframeLoaded();
    return project;
};

Entry.clearProject = function() {
    Entry.stop();
    Entry.projectId = null;
    Entry.type !== 'invisible' && Entry.playground && Entry.playground.changeViewMode('code');
    Entry.variableContainer.clear();
    Entry.container.clear();
    Entry.scene.clear();
};

/**
 * Export project
 * @param {?Project} project
 */
Entry.exportProject = function(project) {
    if (!project) project = {};

    if (!Entry.engine.isState('stop'))
        Entry.engine.toggleStop();

    if (Entry.Func &&
        Entry.Func.workspace &&
        Entry.Func.workspace.visible ) {
        Entry.Func.cancelEdit();
    }

    //Entry.stage.handle.setVisible(false);
    //Entry.stage.update();

    project.objects = Entry.container.toJSON();
    project.scenes = Entry.scene.toJSON();
    project.variables = Entry.variableContainer.getVariableJSON();
    project.messages = Entry.variableContainer.getMessageJSON();
    project.functions = Entry.variableContainer.getFunctionJSON();
    project.scenes = Entry.scene.toJSON();
    project.speed = Entry.FPS;
    project.interface = Entry.captureInterfaceState();
    return project;
};

/**
 * inject blocks to Entry menu.
 * Available block is different by object type.
 * @param {!string} objectType
 * @param {!string} blockText
 */
Entry.setBlockByText = function(objectType, blockText) {
    var blockJSON = [];
    var xml = jQuery.parseXML(blockText);
    var categories = xml.getElementsByTagName('category');
    for (var i = 0; i < categories.length; i++) {
        var category = categories[i];
        var json = {category: category.getAttribute("id"), blocks: []};
        var blocks = category.childNodes;
        for (var j = 0; j < blocks.length; j++) {
            var b = blocks[j];
            if (b.tagName &&
                (b.tagName.toUpperCase() == 'BLOCK' ||
                 b.tagName.toUpperCase() == 'BTN')) {
                json.blocks.push(b.getAttribute('type'));
            }
        }
        blockJSON.push(json);
    }
    Entry.playground.setBlockMenu(blockJSON);
};

/**
 * inject blocks to Entry menu.
 * Available block is different by object type.
 * @param {!string} objectType
 * @param {!xml} XML
 */
Entry.setBlock = function(objectType, XML) {
    Entry.playground.setMenuBlock(objectType, XML);
};

Entry.enableArduino = function() {
    return;
};

/**
 * initialize sound
 * @param {sound object} sound
 */
Entry.initSound = function(sound) {
    if (sound.fileurl) {
        sound.path = sound.fileurl;
    } else {
        sound.path = Entry.defaultPath + '/uploads/' + sound.filename.substring(0,2)+'/'+
            sound.filename.substring(2,4)+'/'+sound.filename+sound.ext;
    }

    Entry.soundQueue.loadFile({
        id: sound.id,
        src: sound.path,
        type: createjs.LoadQueue.SOUND
    });
};

/**
 * This method is called when window closed;
 * @param {event} e
 */
Entry.beforeUnload = function(e) {
    Entry.hw.closeConnection();
    Entry.variableContainer.updateCloudVariables();
    if (Entry.type == 'workspace') {
        if (localStorage && Entry.interfaceState) {
            localStorage.setItem('workspace-interface',
                                 JSON.stringify(Entry.captureInterfaceState()));
        }
        if (!Entry.stateManager.isSaved())
            return Lang.Workspace.project_changed;
    }
};

Entry.captureInterfaceState = function() {
    var interfaceState = JSON.parse(JSON.stringify(Entry.interfaceState))
    var playground = Entry.playground;
    if (Entry.type == 'workspace' &&
        playground && playground.object) {
        interfaceState.object = playground.object.id;
    }

    return interfaceState;
};

/**
 * load interface state by localstorage
 */
Entry.loadInterfaceState = function(interfaceState) {
    if (Entry.type == 'workspace') {
        if (interfaceState) {
            Entry.container.selectObject(interfaceState.object, true);
        } else if (localStorage &&
            localStorage.getItem('workspace-interface')) {
            var interfaceModel = localStorage.getItem('workspace-interface');
            interfaceState = JSON.parse(interfaceModel);
        } else {
            interfaceState = {
                menuWidth: 280,
                canvasWidth: 480
            };
        }
        this.resizeElement(interfaceState);
    }
};

/**
 * Resize element's size.
 * @param {!json} interfaceModel
 */
Entry.resizeElement = function(interfaceModel) {
    var mainWorkspace = Entry.getMainWS();
    if (!mainWorkspace)
        return;

    if (!interfaceModel)
        interfaceModel = this.interfaceState;

    if (Entry.type == 'workspace') {
        var interfaceState = this.interfaceState;
        if (!interfaceModel.canvasWidth && interfaceState.canvasWidth)
            interfaceModel.canvasWidth = interfaceState.canvasWidth;
        if (!interfaceModel.menuWidth &&
            this.interfaceState.menuWidth)
            interfaceModel.menuWidth = interfaceState.menuWidth;

        if (Entry.engine.speedPanelOn)
            Entry.engine.toggleSpeedPanel();

        var canvasSize = interfaceModel.canvasWidth;
        if (!canvasSize)            canvasSize = 400;
        else if (canvasSize < 325)  canvasSize = 325;
        else if (canvasSize > 720)  canvasSize = 720;
        interfaceModel.canvasWidth = canvasSize;

        var canvasHeight = canvasSize*9/16;

        Entry.engine.view_.style.width = canvasSize + 'px';
        Entry.engine.view_.style.height = canvasHeight + 'px';
        Entry.engine.view_.style.top = '40px';
        Entry.stage.canvas.canvas.style.width = canvasSize + 'px';
        if (canvasSize >= 400) {
            Entry.engine.view_.removeClass("collapsed");
        } else {
            Entry.engine.view_.addClass("collapsed");
        }
        Entry.playground.view_.style.left = (canvasSize + 0.5) + 'px';

        Entry.propertyPanel.resize(canvasSize);

        var addButton = Entry.engine.view_.getElementsByClassName('entryAddButtonWorkspace_w')[0];
        if (addButton) {
            if (Entry.objectAddable) {
                addButton.style.top = (canvasHeight + 25) + 'px';
                addButton.style.width = (canvasSize * 0.7) + 'px';
            }
        }
        var pauseButton = Entry.engine.view_.getElementsByClassName('entryPauseButtonWorkspace_w')[0];
        if (pauseButton) {
            if (Entry.objectAddable) {
                pauseButton.style.top = (canvasHeight + 25) + 'px';
                pauseButton.style.width = (canvasSize * 0.7) + 'px';
            }
        }

        var runButton = Entry.engine.view_.getElementsByClassName('entryRunButtonWorkspace_w')[0];
        if (runButton) {
            if (Entry.objectAddable) {
                /*runButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                runButton.style.top = (canvasHeight + 25) + 'px';
                runButton.style.left = (canvasSize * 0.7) + 'px';
                runButton.style.width = (canvasSize * 0.3) + 'px';
            } else {
                runButton.style.left = '2px';
                /*runButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                runButton.style.top = (canvasHeight + 25) + 'px';
                runButton.style.width = (canvasSize - 4) + 'px';
            }
        }

        var stopButton = Entry.engine.view_.getElementsByClassName('entryStopButtonWorkspace_w')[0];
        if (stopButton) {
            if (Entry.objectAddable) {
                /*stopButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                stopButton.style.top = (canvasHeight + 25) + 'px';
                stopButton.style.left = (canvasSize * 0.7) + 'px';
                stopButton.style.width = (canvasSize * 0.3) + 'px';
                //console.log('runButton top,left = ' + runButton.style.top + ',' + runButton.style.left);
            } else {
                stopButton.style.left = '2px';
                /*stopButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                stopButton.style.top = (canvasHeight + 25) + 'px';
                stopButton.style.width = (canvasSize) + 'px';
            }
        }

        var menuWidth = interfaceModel.menuWidth;
        if (!menuWidth) menuWidth = 264;
        else if (menuWidth < 244)
            menuWidth = 244;
        else if (menuWidth > 400)
            menuWidth = 400;
        interfaceModel.menuWidth = menuWidth;

        var blockMenu = mainWorkspace.blockMenu;
        var adjust = blockMenu.hasCategory() ? -64 : 0;

        $('.blockMenuContainer').css({width: (menuWidth + adjust) + 'px'});
        $('.blockMenuContainer>svg').css({width: (menuWidth + adjust) + 'px'});
        blockMenu.setWidth();
        $('.entryWorkspaceBoard').css({left: (menuWidth) + 'px'});
        Entry.playground.resizeHandle_.style.left = (menuWidth) + 'px';
        Entry.playground.variableViewWrapper_.style.width = menuWidth + 'px';

        this.interfaceState = interfaceModel;
    }

    Entry.windowResized.notify();
};

/**
 * @return {Number} return up time time stamp
 */
Entry.getUpTime = function() {
    return new Date().getTime() - this.startTime;
};

/**
 * @param {String} activityType
 */
Entry.addActivity = function(activityType) {
    if (Entry.stateManager)
        Entry.stateManager.addActivity(activityType);
};

Entry.startActivityLogging = function() {
    if (Entry.reporter)
        Entry.reporter.start(
            Entry.projectId,
            window.user ? window.user._id : null,
            Entry.startTime);
};

/**
 * return activity log
 * @return {object}
 */
Entry.getActivityLog = function() {
    var log = {};
    if (Entry.stateManager)
        log.activityLog = Entry.stateManager.activityLog_;
    return log;
};
//block drag mode for Entry.BlockView
Entry.DRAG_MODE_NONE = 0;
Entry.DRAG_MODE_MOUSEDOWN = 1;
Entry.DRAG_MODE_DRAG = 2;

Entry.cancelObjectEdit = function(e) {
    var object = Entry.playground.object;
    if (!object) return;
    var objectView = object.view_;
    var target = e.target;
    var isCurrent = $(objectView).find(target).length !== 0;
    var tagName = target.tagName.toUpperCase();
    var type = e.type
    if (!object.isEditing || (tagName === 'INPUT' && isCurrent || type === 'touchstart'))
        return;
    object.editObjectValues(false);
};

Entry.generateFunctionSchema = function(functionId) {
    functionId = 'func_' + functionId;
    if (Entry.block[functionId]) return;
    var blockSchema = function () {};
    var blockPrototype = Entry.block.function_general;
    blockSchema.prototype = blockPrototype;
    blockSchema = new blockSchema();
    blockSchema.changeEvent = new Entry.Event();
    blockSchema.template = Lang.template.function_general;

    Entry.block[functionId] = blockSchema;
};

Entry.getMainWS = function() {
    var ret;
    if (Entry.mainWorkspace)
        ret = Entry.mainWorkspace
    else if (Entry.playground && Entry.playground.mainWorkspace)
        ret = Entry.playground.mainWorkspace
    return ret;
};

Entry.getDom = function(query) {
    if (!query) return this.view_;

    query = JSON.parse(JSON.stringify(query));
    if (query.length > 1) {
        var key = query.shift();
        return this[key].getDom(query);
    } else {
    }
};
window.Entry = Entry;
<commit_msg>issue https://github.com/boolgom/Entry/issues/7101 소리재생불가 오류관련<commit_after>"use strict";

goog.provide("Entry");

Entry = {};

Entry.block = {};

Entry.TEXT_ALIGN_CENTER = 0;

Entry.TEXT_ALIGN_LEFT = 1;

Entry.TEXT_ALIGN_RIGHT = 2;

Entry.TEXT_ALIGNS = ["center", "left", "right"];

Entry.clipboard = null;

/**
 * Load project
 * @param {?Project} project
 */
Entry.loadProject = function(project) {
    if (!project) {
        project = Entry.getStartProject(Entry.mediaFilePath);
    }

    if (this.type == 'workspace')
        Entry.stateManager.startIgnore();
    Entry.projectId = project._id;
    Entry.variableContainer.setVariables(project.variables);
    Entry.variableContainer.setMessages(project.messages);
    Entry.scene.addScenes(project.scenes);
    Entry.stage.initObjectContainers();
    Entry.variableContainer.setFunctions(project.functions);
    Entry.container.setObjects(project.objects);
    Entry.FPS = project.speed ? project.speed : 60;
    createjs.Ticker.setFPS(Entry.FPS);

    if (!Entry.engine.projectTimer)
        Entry.variableContainer.generateTimer();

    if (Object.keys(Entry.container.inputValue).length === 0)
        Entry.variableContainer.generateAnswer();
    Entry.start();
    if (this.options.programmingMode) {

        var mode = this.options.programmingMode;
        if (Entry.Utils.isNumber(mode)) {
            var pMode = mode;
            mode = {};

            this.mode = mode;
            if (pMode == 0) {
                mode.boardType = Entry.Workspace.MODE_BOARD;
                mode.textType = -1;
            } else if (pMode == 1) { // Python in Text Coding
                mode.boardType = Entry.Workspace.MODE_VIMBOARD;
                mode.textType = Entry.Vim.TEXT_TYPE_PY;
                mode.runType = Entry.Vim.WORKSPACE_MODE;
            } else if (pMode == 2) { // Javascript in Text Coding
                mode.boardType = Entry.Workspace.MODE_VIMBOARD;
                mode.textType = Entry.Vim.TEXT_TYPE_JS;
                mode.runType = Entry.Vim.MAZE_MODE;
            }
            Entry.getMainWS().setMode(mode);
        }
    }

    Entry.Loader.isLoaded() && Entry.Loader.handleLoad();

    if (this.type == 'workspace')
        Entry.stateManager.endIgnore();

    if (project.interface && Entry.options.loadInterface)
        Entry.loadInterfaceState(project.interface);

    if (window.parent && window.parent.childIframeLoaded)
        window.parent.childIframeLoaded();
    return project;
};

Entry.clearProject = function() {
    Entry.stop();
    Entry.projectId = null;
    Entry.type !== 'invisible' && Entry.playground && Entry.playground.changeViewMode('code');
    Entry.variableContainer.clear();
    Entry.container.clear();
    Entry.scene.clear();
};

/**
 * Export project
 * @param {?Project} project
 */
Entry.exportProject = function(project) {
    if (!project) project = {};

    if (!Entry.engine.isState('stop'))
        Entry.engine.toggleStop();

    if (Entry.Func &&
        Entry.Func.workspace &&
        Entry.Func.workspace.visible ) {
        Entry.Func.cancelEdit();
    }

    //Entry.stage.handle.setVisible(false);
    //Entry.stage.update();

    project.objects = Entry.container.toJSON();
    project.scenes = Entry.scene.toJSON();
    project.variables = Entry.variableContainer.getVariableJSON();
    project.messages = Entry.variableContainer.getMessageJSON();
    project.functions = Entry.variableContainer.getFunctionJSON();
    project.scenes = Entry.scene.toJSON();
    project.speed = Entry.FPS;
    project.interface = Entry.captureInterfaceState();
    return project;
};

/**
 * inject blocks to Entry menu.
 * Available block is different by object type.
 * @param {!string} objectType
 * @param {!string} blockText
 */
Entry.setBlockByText = function(objectType, blockText) {
    var blockJSON = [];
    var xml = jQuery.parseXML(blockText);
    var categories = xml.getElementsByTagName('category');
    for (var i = 0; i < categories.length; i++) {
        var category = categories[i];
        var json = {category: category.getAttribute("id"), blocks: []};
        var blocks = category.childNodes;
        for (var j = 0; j < blocks.length; j++) {
            var b = blocks[j];
            if (b.tagName &&
                (b.tagName.toUpperCase() == 'BLOCK' ||
                 b.tagName.toUpperCase() == 'BTN')) {
                json.blocks.push(b.getAttribute('type'));
            }
        }
        blockJSON.push(json);
    }
    Entry.playground.setBlockMenu(blockJSON);
};

/**
 * inject blocks to Entry menu.
 * Available block is different by object type.
 * @param {!string} objectType
 * @param {!xml} XML
 */
Entry.setBlock = function(objectType, XML) {
    Entry.playground.setMenuBlock(objectType, XML);
};

Entry.enableArduino = function() {
    return;
};

/**
 * initialize sound
 * @param {sound object} sound
 */
Entry.initSound = function(sound) {
    if (!sound || !sound.duration || sound.duration == 0) return;
    if (sound.fileurl) {
        sound.path = sound.fileurl;
    } else {
        sound.path = Entry.defaultPath + '/uploads/' + sound.filename.substring(0,2)+'/'+
            sound.filename.substring(2,4)+'/'+sound.filename+sound.ext;
    }

    Entry.soundQueue.loadFile({
        id: sound.id,
        src: sound.path,
        type: createjs.LoadQueue.SOUND
    });
};

/**
 * This method is called when window closed;
 * @param {event} e
 */
Entry.beforeUnload = function(e) {
    Entry.hw.closeConnection();
    Entry.variableContainer.updateCloudVariables();
    if (Entry.type == 'workspace') {
        if (localStorage && Entry.interfaceState) {
            localStorage.setItem('workspace-interface',
                                 JSON.stringify(Entry.captureInterfaceState()));
        }
        if (!Entry.stateManager.isSaved())
            return Lang.Workspace.project_changed;
    }
};

Entry.captureInterfaceState = function() {
    var interfaceState = JSON.parse(JSON.stringify(Entry.interfaceState))
    var playground = Entry.playground;
    if (Entry.type == 'workspace' &&
        playground && playground.object) {
        interfaceState.object = playground.object.id;
    }

    return interfaceState;
};

/**
 * load interface state by localstorage
 */
Entry.loadInterfaceState = function(interfaceState) {
    if (Entry.type == 'workspace') {
        if (interfaceState) {
            Entry.container.selectObject(interfaceState.object, true);
        } else if (localStorage &&
            localStorage.getItem('workspace-interface')) {
            var interfaceModel = localStorage.getItem('workspace-interface');
            interfaceState = JSON.parse(interfaceModel);
        } else {
            interfaceState = {
                menuWidth: 280,
                canvasWidth: 480
            };
        }
        this.resizeElement(interfaceState);
    }
};

/**
 * Resize element's size.
 * @param {!json} interfaceModel
 */
Entry.resizeElement = function(interfaceModel) {
    var mainWorkspace = Entry.getMainWS();
    if (!mainWorkspace)
        return;

    if (!interfaceModel)
        interfaceModel = this.interfaceState;

    if (Entry.type == 'workspace') {
        var interfaceState = this.interfaceState;
        if (!interfaceModel.canvasWidth && interfaceState.canvasWidth)
            interfaceModel.canvasWidth = interfaceState.canvasWidth;
        if (!interfaceModel.menuWidth &&
            this.interfaceState.menuWidth)
            interfaceModel.menuWidth = interfaceState.menuWidth;

        if (Entry.engine.speedPanelOn)
            Entry.engine.toggleSpeedPanel();

        var canvasSize = interfaceModel.canvasWidth;
        if (!canvasSize)            canvasSize = 400;
        else if (canvasSize < 325)  canvasSize = 325;
        else if (canvasSize > 720)  canvasSize = 720;
        interfaceModel.canvasWidth = canvasSize;

        var canvasHeight = canvasSize*9/16;

        Entry.engine.view_.style.width = canvasSize + 'px';
        Entry.engine.view_.style.height = canvasHeight + 'px';
        Entry.engine.view_.style.top = '40px';
        Entry.stage.canvas.canvas.style.width = canvasSize + 'px';
        if (canvasSize >= 400) {
            Entry.engine.view_.removeClass("collapsed");
        } else {
            Entry.engine.view_.addClass("collapsed");
        }
        Entry.playground.view_.style.left = (canvasSize + 0.5) + 'px';

        Entry.propertyPanel.resize(canvasSize);

        var addButton = Entry.engine.view_.getElementsByClassName('entryAddButtonWorkspace_w')[0];
        if (addButton) {
            if (Entry.objectAddable) {
                addButton.style.top = (canvasHeight + 25) + 'px';
                addButton.style.width = (canvasSize * 0.7) + 'px';
            }
        }
        var pauseButton = Entry.engine.view_.getElementsByClassName('entryPauseButtonWorkspace_w')[0];
        if (pauseButton) {
            if (Entry.objectAddable) {
                pauseButton.style.top = (canvasHeight + 25) + 'px';
                pauseButton.style.width = (canvasSize * 0.7) + 'px';
            }
        }

        var runButton = Entry.engine.view_.getElementsByClassName('entryRunButtonWorkspace_w')[0];
        if (runButton) {
            if (Entry.objectAddable) {
                /*runButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                runButton.style.top = (canvasHeight + 25) + 'px';
                runButton.style.left = (canvasSize * 0.7) + 'px';
                runButton.style.width = (canvasSize * 0.3) + 'px';
            } else {
                runButton.style.left = '2px';
                /*runButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                runButton.style.top = (canvasHeight + 25) + 'px';
                runButton.style.width = (canvasSize - 4) + 'px';
            }
        }

        var stopButton = Entry.engine.view_.getElementsByClassName('entryStopButtonWorkspace_w')[0];
        if (stopButton) {
            if (Entry.objectAddable) {
                /*stopButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                stopButton.style.top = (canvasHeight + 25) + 'px';
                stopButton.style.left = (canvasSize * 0.7) + 'px';
                stopButton.style.width = (canvasSize * 0.3) + 'px';
                //console.log('runButton top,left = ' + runButton.style.top + ',' + runButton.style.left);
            } else {
                stopButton.style.left = '2px';
                /*stopButton.style.top = (canvasHeight + 24 + 40 + 4) + 'px';*/
                stopButton.style.top = (canvasHeight + 25) + 'px';
                stopButton.style.width = (canvasSize) + 'px';
            }
        }

        var menuWidth = interfaceModel.menuWidth;
        if (!menuWidth) menuWidth = 264;
        else if (menuWidth < 244)
            menuWidth = 244;
        else if (menuWidth > 400)
            menuWidth = 400;
        interfaceModel.menuWidth = menuWidth;

        var blockMenu = mainWorkspace.blockMenu;
        var adjust = blockMenu.hasCategory() ? -64 : 0;

        $('.blockMenuContainer').css({width: (menuWidth + adjust) + 'px'});
        $('.blockMenuContainer>svg').css({width: (menuWidth + adjust) + 'px'});
        blockMenu.setWidth();
        $('.entryWorkspaceBoard').css({left: (menuWidth) + 'px'});
        Entry.playground.resizeHandle_.style.left = (menuWidth) + 'px';
        Entry.playground.variableViewWrapper_.style.width = menuWidth + 'px';

        this.interfaceState = interfaceModel;
    }

    Entry.windowResized.notify();
};

/**
 * @return {Number} return up time time stamp
 */
Entry.getUpTime = function() {
    return new Date().getTime() - this.startTime;
};

/**
 * @param {String} activityType
 */
Entry.addActivity = function(activityType) {
    if (Entry.stateManager)
        Entry.stateManager.addActivity(activityType);
};

Entry.startActivityLogging = function() {
    if (Entry.reporter)
        Entry.reporter.start(
            Entry.projectId,
            window.user ? window.user._id : null,
            Entry.startTime);
};

/**
 * return activity log
 * @return {object}
 */
Entry.getActivityLog = function() {
    var log = {};
    if (Entry.stateManager)
        log.activityLog = Entry.stateManager.activityLog_;
    return log;
};
//block drag mode for Entry.BlockView
Entry.DRAG_MODE_NONE = 0;
Entry.DRAG_MODE_MOUSEDOWN = 1;
Entry.DRAG_MODE_DRAG = 2;

Entry.cancelObjectEdit = function(e) {
    var object = Entry.playground.object;
    if (!object) return;
    var objectView = object.view_;
    var target = e.target;
    var isCurrent = $(objectView).find(target).length !== 0;
    var tagName = target.tagName.toUpperCase();
    var type = e.type
    if (!object.isEditing || (tagName === 'INPUT' && isCurrent || type === 'touchstart'))
        return;
    object.editObjectValues(false);
};

Entry.generateFunctionSchema = function(functionId) {
    functionId = 'func_' + functionId;
    if (Entry.block[functionId]) return;
    var blockSchema = function () {};
    var blockPrototype = Entry.block.function_general;
    blockSchema.prototype = blockPrototype;
    blockSchema = new blockSchema();
    blockSchema.changeEvent = new Entry.Event();
    blockSchema.template = Lang.template.function_general;

    Entry.block[functionId] = blockSchema;
};

Entry.getMainWS = function() {
    var ret;
    if (Entry.mainWorkspace)
        ret = Entry.mainWorkspace
    else if (Entry.playground && Entry.playground.mainWorkspace)
        ret = Entry.playground.mainWorkspace
    return ret;
};

Entry.getDom = function(query) {
    if (!query) return this.view_;

    query = JSON.parse(JSON.stringify(query));
    if (query.length > 1) {
        var key = query.shift();
        return this[key].getDom(query);
    } else {
    }
};
window.Entry = Entry;
<|endoftext|>


<commit_before>import Duration from 'duration'
import shortid from 'shortid'
import moment from 'moment'
import parser from './parser'

export const hashPattern = /(#\w+[\w-]*)/g
export const version = 1
export default class Entry {
  constructor(message, opts = {}) {
    let {
      date = new Date(),
    } = opts

    if (typeof message === 'object')
      return this._fromJSON(message)

    this.version = version
    this._id = shortid.generate()
    this.message = message
    this.parse(message, date)
    this.parseTags(message)
  }

  _fromJSON(doc) {
    Object.assign(this, doc)
    const start = new Date(this.from)
    const end = new Date(this.to)
    const text = this.time
    this.setDates({start, end, text})
    this.tags = new Set(doc.tags)
    return this
  }

  parse(msg, date) {
    let d = parser(msg, date)
    if (d.isValid) this.setDates(d)
  }

  parseTags(message) {
    // Set makes things unique
    this.tags = new Set(message.match(hashPattern))
  }

  setDates(opts) {
    this.hasDates = true
    this.from = opts.start
    this.fromArr = moment(this.from).toArray()
    this.to = opts.end
    this.time = opts.text
    this.toArr = moment(this.to).toArray()
    this.duration = new Duration(this.from, this.to)
  }

  getDates() {
    let from = this.from
    let to = this.to
    return {from, to}
  }

  toJSON() {
    return {
      _id: this._id,
      version: this.version,
      message: this.message,
      hasDates: this.hasDates,
      from: this.from,
      fromArr: this.fromArr,
      to: this.to,
      toArr: this.toArr,
      time: this.time,
      tags: [...this.tags],
      duration: this.duration ? {
        seconds: this.duration.seconds,
        from: this.duration.from,
        to: this.duration.to
      } : null
    }
  }

  static fromJSON(doc) {
    let e = new Entry(doc)

    return e
  }
}
<commit_msg>fix: entry docs are v2<commit_after>import Duration from 'duration'
import shortid from 'shortid'
import moment from 'moment'
import parser from './parser'

export const hashPattern = /(#\w+[\w-]*)/g
export const version = 2
export default class Entry {
  constructor(message, opts = {}) {
    let {
      date = new Date(),
    } = opts

    if (typeof message === 'object')
      return this._fromJSON(message)

    this.version = version
    this._id = shortid.generate()
    this.message = message
    this.parse(message, date)
    this.parseTags(message)
  }

  _fromJSON(doc) {
    Object.assign(this, doc)
    const start = new Date(this.from)
    const end = new Date(this.to)
    const text = this.time
    this.setDates({start, end, text})
    this.tags = new Set(doc.tags)
    return this
  }

  parse(msg, date) {
    let d = parser(msg, date)
    if (d.isValid) this.setDates(d)
  }

  parseTags(message) {
    // Set makes things unique
    this.tags = new Set(message.match(hashPattern))
  }

  setDates(opts) {
    this.hasDates = true
    this.from = opts.start
    this.fromArr = moment(this.from).toArray()
    this.to = opts.end
    this.time = opts.text
    this.toArr = moment(this.to).toArray()
    this.duration = new Duration(this.from, this.to)
  }

  getDates() {
    let from = this.from
    let to = this.to
    return {from, to}
  }

  toJSON() {
    return {
      _id: this._id,
      version: this.version,
      message: this.message,
      hasDates: this.hasDates,
      from: this.from,
      fromArr: this.fromArr,
      to: this.to,
      toArr: this.toArr,
      time: this.time,
      tags: [...this.tags],
      duration: this.duration ? {
        seconds: this.duration.seconds,
        from: this.duration.from,
        to: this.duration.to
      } : null
    }
  }

  static fromJSON(doc) {
    let e = new Entry(doc)

    return e
  }
}
<|endoftext|>


<commit_before>User = //to export it to other namespace
class User {
    constructor(name, availabilities, assignments = [], _id) {
        this.name = name;
        this.availabilities = availabilities; //Array<Availability>
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
        this.assignments = assignments;
    }

    toString() {
        return '(' + this.name + ', ' + this.availabilities + ')';
    }
}

UserRepository =
class UserRepository {
    static findOne(userId) {
        var user = Users.findOne(userId);
        return new User(user.name, user.availabilities, user.assignments, user._id); //TODO trouver un moyen plus NoSQL de faire ca ?
    }
}

Availability = //to export it to other namespace
class Availability {
    constructor(start, end) {
        this.start = start;
        this.end = end;
    }
}

Task = //to export it to other namespace
class Task {
    constructor(name, timeSlots, assignments = [], _id) {
        this.name = name;
        this.timeSlots = timeSlots; //Array<Timeslot>
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
        this.assignments = assignments;
    }
}

TaskRepository =
class TaskRepository {
    static findOne(taskId) {
        var task = Tasks.findOne(taskId);
        return new Task(task.name, task.timeSlots, task.assignments, task._id); //TODO trouver un moyen plus NoSQL de faire ca ?
    }
}

TimeSlot = //to export it to other namespace
class TimeSlot { //must inherit Availabilty
    constructor(start, end, peopleNeeded) {
        this.start = start;
        this.end = end;
        this.peopleNeeded = peopleNeeded; //Array<PeopleNeed>
        if (typeof _id !== "undefined") this._id = _id
        else this._id = new Meteor.Collection.ObjectID()._str;
    }
}

TimeSlotService =
class TimeSlotService {
    static read(timeSlot) {
        return new TimeSlot(timeSlot.start, timeSlot.end, timeSlot.peopleNeeded, timeSlot._id);
    }

    static getTimeSlot(task, timeSlotId) {
        console.info("TimeSlotService.getTimeSlot timeSlot", timeSlotId, "for task", task);
        var found;
        task.timeSlots.forEach(timeSlot => {
            if (timeSlot._id === timeSlotId) {
                found =  TimeSlotService.read(timeSlot);
                return false;
            }
        });
        return found;
    }
}

PeopleNeed = {
    JUNKRESP: "junkResp",
    SOFT: "soft",
    SOFTDRIVINGLICENSE: "softDrivingLicense"
};

AssignmentType = {
    USERTOTASK: "userToTask",
    TASKTOUSER: "taskToUser",
    ALL: "all"
};

Assignment = //to export it to other namespace
class Assignment {
    constructor(userId, taskId, timeSlotId, _id) {
        this.userId = userId;
        this.taskId = taskId;
        this.timeSlotId = timeSlotId;
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
    }

}

AssignmentService =
class AssignmentService {
    static read(assigment) {
        return new Assignment(assigment.userId, assigment.taskId, assigment.timeSlotId, assigment._id);
    }

    static getTimeSlot(task, timeSlotId) {
        for (var timeSlot in task.timeSlots) {
            if (timeSlot._id === timeSlotId) {
                return new TimeSlot();
            }
        }
        return null;
    }
}

UserAssignment = //to export it to other namespace
class UserAssignment { //stored along with a user to a direct access
    constructor(taskName, start, end, assignmentId) {
        this.taskName = taskName;
        this.start = start;
        this.end = end;
        this.assignmentId = assignmentId;
    }

}

TaskAssignment = //to export it to other namespace
class TaskAssignment { //stored along with a task to a direct access
    constructor(userName, start, end, assignmentId) {
        this.userName = userName;
        this.start = start;
        this.end = end;
        this.assignmentId = assignmentId;
    }

}

AssignmentRepository =
class AssignmentRepository {
    static findOne(assignmentId) {
        var assignment = Assignments.findOne(assignmentId);
        return new Assignment(assignment.userId, assignment.taskId, assignment.timeSlotId, assignment._id);
    }
}

<commit_msg>nothing<commit_after>User = //to export it to other namespace
class User {
    constructor(name, availabilities, assignments = [], _id) {
        this.name = name;
        this.availabilities = availabilities; //Array<Availability>
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
        this.assignments = assignments;
    }

    toString() {
        return '(' + this.name + ', ' + this.availabilities + ')';
    }
}

UserRepository =
class UserRepository {
    static findOne(userId) {
        var user = Users.findOne(userId);
        return new User(user.name, user.availabilities, user.assignments, user._id); //TODO trouver un moyen plus NoSQL de faire ca ?
    }
}

Availability = //to export it to other namespace
class Availability {
    constructor(start, end) {
        this.start = start;
        this.end = end;
    }
}

Task = //to export it to other namespace
class Task {
    constructor(name, timeSlots, assignments = [], _id) {
        this.name = name;
        this.timeSlots = timeSlots; //Array<Timeslot>
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
        this.assignments = assignments;
    }
}

TaskRepository =
class TaskRepository {
    static findOne(taskId) {
        var task = Tasks.findOne(taskId);
        return new Task(task.name, task.timeSlots, task.assignments, task._id); //TODO trouver un moyen plus NoSQL de faire ca ?
    }
}

TimeSlot = //to export it to other namespace
class TimeSlot { //must inherit Availabilty
    constructor(start, end, peopleNeeded) {
        this.start = start;
        this.end = end;
        this.peopleNeeded = peopleNeeded; //Array<PeopleNeed>
        if (typeof _id !== "undefined") this._id = _id
        else this._id = new Meteor.Collection.ObjectID()._str;
    }
}

TimeSlotService =
class TimeSlotService {
    static read(timeSlot) {
        return new TimeSlot(timeSlot.start, timeSlot.end, timeSlot.peopleNeeded, timeSlot._id);
    }

    static getTimeSlot(task, timeSlotId) {
        console.info("TimeSlotService.getTimeSlot timeSlot", timeSlotId, "for task", task);
        var found;
        task.timeSlots.forEach(timeSlot => {
            if (timeSlot._id === timeSlotId) {
                found =  TimeSlotService.read(timeSlot);
                return false;
            }
        });
        return found;
    }
}

PeopleNeed = {
    JUNKRESP: "junkResp",
    SOFT: "soft",
    SOFTDRIVINGLICENSE: "softDrivingLicense"
};

AssignmentType = {
    USERTOTASK: "userToTask",
    TASKTOUSER: "taskToUser",
    ALL: "all"
};

Assignment = //to export it to other namespace
class Assignment {
    constructor(userId, taskId, timeSlotId, _id) {
        this.userId = userId;
        this.taskId = taskId;
        this.timeSlotId = timeSlotId;
        if (typeof _id !== "undefined") this._id = _id; //if undefined, Assignment is not yet stored in DB
    }

}

AssignmentService =
class AssignmentService {
    static read(assigment) {
        return new Assignment(assigment.userId, assigment.taskId, assigment.timeSlotId, assigment._id);
    }

    static getTimeSlot(task, timeSlotId) {
        for (var timeSlot in task.timeSlots) {
            if (timeSlot._id === timeSlotId) {
                return new TimeSlot();
            }
        }
        return null;
    }
}

UserAssignment = //to export it to other namespace
class UserAssignment { //stored along with a user to a direct access
    constructor(taskName, start, end, assignmentId) {
        this.taskName = taskName;
        this.start = start;
        this.end = end;
        this.assignmentId = assignmentId;
    }

}

TaskAssignment = //to export it to other namespace
class TaskAssignment { //stored along with a task to a direct access
    constructor(userName, start, end, assignmentId) {
        this.userName = userName;
        this.start = start;
        this.end = end;
        this.assignmentId = assignmentId;
    }

}

AssignmentRepository =
class AssignmentRepository {
    static findOne(assignmentId) {
        var assignment = Assignments.findOne(assignmentId);
        return new Assignment(assignment.userId, assignment.taskId, assignment.timeSlotId, assignment._id);
    }
}

<|endoftext|>


<commit_before>var Diagnostics = {

    command: function(methodName) {
        log("Diagnostics.command(" + methodName +")");
        deferred = doSimpleXMLHttpRequest(this.base+methodName);
        deferred.addCallback(function (res) {
            response = res.responseText;
            if(response.indexOf("Traceback") != -1) {
                this.setError("Python error: \n" + response);
            }
        });
        deferred.addErrback(function (err) {
            this.setError("Error: " + repr(err));
        });
    },

    setStatus: function(statusText) {
        replaceChildNodes(getElement(this.idbase + "status"),
                          SPAN(null, statusText));
    },

    setError: function(errorText) {
        replaceChildNodes(getElement(this.idbase + "error"),
                          SPAN(null, errorText));
    },

    doFixedFlash: function() {
        Diagnostics.command('doFixedFlash');
    },

}

<commit_msg>added base variable for diagnostics.js.  I forgot to do this the first time.<commit_after>var Diagnostics = {
    base:   "/expt/",
    idbase: "diagnostics_",

    command: function(methodName) {
        log("Diagnostics.command(" + methodName +")");
        deferred = doSimpleXMLHttpRequest(this.base+methodName);
        deferred.addCallback(function (res) {
            response = res.responseText;
            if(response.indexOf("Traceback") != -1) {
                this.setError("Python error: \n" + response);
            }
        });
        deferred.addErrback(function (err) {
            this.setError("Error: " + repr(err));
        });
    },

    setStatus: function(statusText) {
        replaceChildNodes(getElement(this.idbase + "status"),
                          SPAN(null, statusText));
    },

    setError: function(errorText) {
        replaceChildNodes(getElement(this.idbase + "error"),
                          SPAN(null, errorText));
    },

    doFixedFlash: function() {
        Diagnostics.command('doFixedFlash');
    },

}

<|endoftext|>


<commit_before>let blockConfigs, blocks

switch (process.env.HOST) {
	case 'jprokop':
		blockConfigs = {
			volume0: {
				extend: 'volume',
				sinkIndex: 0,
				volumeIndexFormat: 'sinkIndex'
			},
			volume1: {
				extend: 'volume',
				sinkIndex: 1,
				volumeIndexFormat: 'sinkIndex',
				hideWhenNotRunning: true
			}
		}
		blocks = [
			'system-update',
			'volume0',
			'volume1',
			'date-time'
		]
		break;
	case 'jprokop-tp13':
	default:
		blockConfigs = {
			volume0: {
				extend: 'volume',
				sinkIndex: 0,
				volumeIndexFormat: 'activePort'
			}
		}
		blocks = [
			'system-update',
			'volume0',
			'date-time'
		]
		break;
}

module.exports = {
	blockConfigs,
	blocks
}
<commit_msg>Fix getting of hostname in bar config<commit_after>const os = require('os')
let blockConfigs, blocks

switch (os.hostname()) {
	case 'jprokop':
		blockConfigs = {
			volume0: {
				extend: 'volume',
				sinkIndex: 0,
				volumeIndexFormat: 'sinkIndex'
			},
			volume1: {
				extend: 'volume',
				sinkIndex: 1,
				volumeIndexFormat: 'sinkIndex',
				hideWhenNotRunning: true
			}
		}
		blocks = [
			'system-update',
			'volume0',
			'volume1',
			'date-time'
		]
		break;
	case 'jprokop-tp13':
	default:
		blockConfigs = {
			volume0: {
				extend: 'volume',
				sinkIndex: 0,
				volumeIndexFormat: 'activePort'
			}
		}
		blocks = [
			'system-update',
			'volume0',
			'date-time'
		]
		break;
}

module.exports = {
	blockConfigs,
	blocks
}
<|endoftext|>


<commit_before>
class BCBProcess extends CommonProcess {
  constructor() {
    super({
      name: `${Project.NAME} Process`
    });

    this.initProcess();
  }

  initProcess() {
    this.initPopover();
  }

  initPopover() {
    {
      new PopoverController({
        name: 'ID Popover',
        selector: '#login-id-help',
        help: 'IDを入力してください'
      });
      new PopoverController({
        name: 'Password Popover',
        selector: '#login-password-help',
        help: 'パスワードを入力してください'
      });
      new PopoverController({
        name: 'Login Check Popover',
        selector: '#login-check-help',
        help: '共有デバイスでは設定に注意してください。'
      });
    }
  }
}
<commit_msg>Update some popover in BCBProcess<commit_after>
class BCBProcess extends CommonProcess {
  constructor() {
    super({
      name: `${Project.NAME} Process`
    });

    this.initProcess();
  }

  initProcess() {
    this.initPopover();
  }

  initPopover() {
    {
      new PopoverController({
        name: 'ID Popover',
        selector: '#login-id-help',
        help: 'ID を入力してください。'
      });
      new PopoverController({
        name: 'Password Popover',
        selector: '#login-password-help',
        help: 'パスワード を入力してください。'
      });
      new PopoverController({
        name: 'Login Check Popover',
        selector: '#login-check-help',
        help: '共有デバイスでは設定に注意してください。'
      });
    }
  }
}
<|endoftext|>