<commit_before>CLASS({
  package: 'foam.ui',
  name: 'SwipeAltView',
  extendsModel: 'View',

  requires: [
    'foam.input.touch.GestureTarget'
  ],

  properties: [
    {
      name: 'views',
      type: 'Array',
      subType: 'ViewChoice',
      view: 'ArrayView',
      factory: function() { return []; },
      help: 'View Choices'
    },
    {
      name: 'index',
      help: 'The index of the currently selected view',
      defaultValue: 0,
      preSet: function(old, nu) {
        if (nu < 0) return 0;
        if (nu >= this.views.length) return this.views.length - 1;
        return nu;
      },
      postSet: function(oldValue, viewChoice) {
        this.views[oldValue].view().deepPublish(this.ON_HIDE);
        // ON_SHOW is called after the animation is done.
        this.snapToCurrent(Math.abs(oldValue - viewChoice));
      },
      hidden: true
    },
    {
      name: 'headerView',
      help: 'Optional View to be displayed in header.',
      factory: function() {
        return this.X.ChoiceListView.create({
          choices: this.views.map(function(x) {
            return x.label;
          }),
          index$: this.index$,
          className: 'swipeAltHeader foamChoiceListView horizontal'
        });
      }
    },
    {
      name: 'data',
      help: 'Generic data field for the views. Proxied to all the child views.',
      postSet: function(old, nu) {
        this.views.forEach(function(c) {
          c.view().data = nu;
        });
      }
    },
    {
      name: 'slider',
      help: 'Internal element which gets translated around',
      hidden: true
    },
    {
      name: 'width',
      help: 'Set when we know the width',
      hidden: true
    },
    {
      name: 'x',
      help: 'X coordinate of the translation',
      hidden: true,
      postSet: function(old, nu) {
        // TODO: Other browsers.
        this.slider.style['-webkit-transform'] = 'translate3d(-' +
            nu + 'px, 0, 0)';
      }
    },
    {
      name: 'swipeGesture',
      hidden: true,
      transient: true,
      factory: function() {
        return this.GestureTarget.create({
          containerID: this.id,
          handler: this,
          gesture: 'horizontalScroll'
        });
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.views.forEach(function(choice, index) {
        if ( index != self.index )
          choice.view().deepPublish(self.ON_HIDE);
      });
      this.views[this.index].view().deepPublish(this.ON_SHOW);
    },

    // The general structure of the carousel is:
    // - An outer div (this.$), with position: relative.
    // - A second div (this.slider) with position: relative.
    //   This is the div that gets translated to and fro.
    // - A set of internal divs (this.slider.children) for the child views.
    //   These are positioned inside the slider right next to each other,
    //   and they have the same width as the outer div.
    //   At most two of these can be visible at a time.
    //
    // If the width is not set yet, this renders a fake carousel. It has the
    // outer, slider and inner divs, but there's only one inner div and it
    // can't slide yet. Shortly thereafter, the slide is expanded and the
    // other views are added. This should be imperceptible to the user.
    toHTML: function() {
      var str  = [];
      var viewChoice = this.views[this.index];

      if ( this.headerView ) {
        str.push(this.headerView.toHTML());
        this.addChild(this.headerView);
      }

      str.push('
');
      str.push('
');
      str.push('
');

      str.push(viewChoice.view().toHTML());

      str.push('
');
      str.push('
');
      str.push('
');

      return str.join('');
    },

    initHTML: function() {
      if ( ! this.$ ) return;
      this.SUPER();

      // Now is the time to inflate our fake carousel into the real thing.
      // For now we won't worry about re-rendering the current one.
      // TODO: Stop re-rendering if it's slow or causes flicker or whatever.

      this.slider = this.$.children[0];
      this.width  = this.$.clientWidth;

      var str = [];
      for ( var i = 0 ; i < this.views.length ; i++ ) {
        // Hide all views except the first one.  They'll be shown after they're resized.
        // This prevents all views from overlapping on startup.
        str.push('
');
        str.push(this.views[i].view().toHTML());
        str.push('
');
      }

      this.slider.innerHTML = str.join('');

      window.addEventListener('resize', this.resize, false);
      this.X.gestureManager.install(this.swipeGesture);

      // Wait for the new HTML to render first, then init it.
      var self = this;
      window.setTimeout(function() {
        self.resize();
        self.views.forEach(function(choice) {
          choice.view().initHTML();
        });
        var vs = self.slider.querySelectorAll('.swipeAltInner');
        for ( var i = 0 ; i < vs.length ; i++ ) vs[i].style.visibility = '';
      }, 0);
    },

    destroy: function() {
      this.SUPER();
      this.X.gestureManager.uninstall(this.swipeGesture);
      this.views.forEach(function(c) { c.view().destroy(); });
    },

    snapToCurrent: function(sizeOfMove) {
      var self = this;
      var time = 150 + sizeOfMove * 150;
      Movement.animate(time, function(evt) {
        self.x = self.index * self.width;
      }, Movement.ease(150/time, 150/time), function() {
        self.views[self.index].view().deepPublish(self.ON_SHOW);
      })();
    }
  },

  listeners: [
    {
      name: 'resize',
      isMerged: 100,
      code: function() {
        // When the orientation of the screen has changed, update the
        // left and width values of the inner elements and slider.
        if ( ! this.$ ) {
          window.removeEventListener('resize', this.resize, false);
          return;
        }

        this.width = this.$.clientWidth;
        var self = this;
        var frame = window.requestAnimationFrame(function() {
          self.x = self.index * self.width;

          for ( var i = 0 ; i < self.slider.children.length ; i++ ) {
            self.slider.children[i].style.left = (i * 100) + '%';
            self.slider.children[i].style.visibility = '';
          }

          window.cancelAnimationFrame(frame);
        });
      }
    },
    {
      name: 'horizontalScrollMove',
      code: function(dx, tx, x) {
        var x = this.index * this.width - tx;

        // Limit x to be within the scope of the slider: no dragging too far.
        if (x < 0) x = 0;
        var maxWidth = (this.views.length - 1) * this.width;
        if ( x > maxWidth ) x = maxWidth;

        this.x = x;
      }
    },
    {
      name: 'horizontalScrollEnd',
      code: function(dx, tx, x) {
        if ( Math.abs(tx) > this.width / 3 ) {
          // Consider that a move.
          if (tx < 0) {
            this.index++;
          } else {
            this.index--;
          }
        } else {
          this.snapToCurrent(1);
        }
      }
    }
  ],
  templates: [
    function CSS() {/*
      .swipeAltInner {
        position: absolute;
        top: 0px;
        height: 100%;
        width: 100%;
      }

      .swipeAltOuter {
        display: flex;
        overflow: hidden;
        min-width: 240px;
        width: 100%;
        height: 100%;
      }

      .swipeAltSlider {
        position: relative;
        width: 100%;
        top: 0px;
        -webkit-transform: translate3d(0,0,0);
      }

    */}
  ]
});
<commit_msg>MBug: Fixed issue 479 SwipeAltView not working properly after resize.<commit_after>CLASS({
  package: 'foam.ui',
  name: 'SwipeAltView',
  extendsModel: 'View',

  requires: [
    'foam.input.touch.GestureTarget'
  ],

  properties: [
    {
      name: 'views',
      type: 'Array',
      subType: 'ViewChoice',
      view: 'ArrayView',
      factory: function() { return []; },
      help: 'View Choices'
    },
    {
      name: 'index',
      help: 'The index of the currently selected view',
      defaultValue: 0,
      preSet: function(old, nu) {
        if (nu < 0) return 0;
        if (nu >= this.views.length) return this.views.length - 1;
        return nu;
      },
      postSet: function(oldValue, viewChoice) {
        this.views[oldValue].view().deepPublish(this.ON_HIDE);
        // ON_SHOW is called after the animation is done.
        this.snapToCurrent(Math.abs(oldValue - viewChoice));
      },
      hidden: true
    },
    {
      name: 'headerView',
      help: 'Optional View to be displayed in header.',
      factory: function() {
        return this.X.ChoiceListView.create({
          choices: this.views.map(function(x) {
            return x.label;
          }),
          index$: this.index$,
          className: 'swipeAltHeader foamChoiceListView horizontal'
        });
      }
    },
    {
      name: 'data',
      help: 'Generic data field for the views. Proxied to all the child views.',
      postSet: function(old, nu) {
        this.views.forEach(function(c) {
          c.view().data = nu;
        });
      }
    },
    {
      name: 'slider',
      help: 'Internal element which gets translated around',
      hidden: true
    },
    {
      name: 'width',
      help: 'Set when we know the width',
      getter: function() { return this.$.clientWidth; },
      hidden: true
    },
    {
      name: 'x',
      help: 'X coordinate of the translation',
      hidden: true,
      postSet: function(old, nu) {
        // TODO: Other browsers.
        this.slider.style['-webkit-transform'] = 'translate3d(-' +
            nu + 'px, 0, 0)';
      }
    },
    {
      name: 'swipeGesture',
      hidden: true,
      transient: true,
      factory: function() {
        return this.GestureTarget.create({
          containerID: this.id,
          handler: this,
          gesture: 'horizontalScroll'
        });
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.views.forEach(function(choice, index) {
        if ( index != self.index )
          choice.view().deepPublish(self.ON_HIDE);
      });
      this.views[this.index].view().deepPublish(this.ON_SHOW);
    },

    // The general structure of the carousel is:
    // - An outer div (this.$), with position: relative.
    // - A second div (this.slider) with position: relative.
    //   This is the div that gets translated to and fro.
    // - A set of internal divs (this.slider.children) for the child views.
    //   These are positioned inside the slider right next to each other,
    //   and they have the same width as the outer div.
    //   At most two of these can be visible at a time.
    //
    // If the width is not set yet, this renders a fake carousel. It has the
    // outer, slider and inner divs, but there's only one inner div and it
    // can't slide yet. Shortly thereafter, the slide is expanded and the
    // other views are added. This should be imperceptible to the user.
    toHTML: function() {
      var str  = [];
      var viewChoice = this.views[this.index];

      if ( this.headerView ) {
        str.push(this.headerView.toHTML());
        this.addChild(this.headerView);
      }

      str.push('
');
      str.push('
');
      str.push('
');

      str.push(viewChoice.view().toHTML());

      str.push('
');
      str.push('
');
      str.push('
');

      return str.join('');
    },

    initHTML: function() {
      if ( ! this.$ ) return;
      this.SUPER();

      // Now is the time to inflate our fake carousel into the real thing.
      // For now we won't worry about re-rendering the current one.
      // TODO: Stop re-rendering if it's slow or causes flicker or whatever.

      this.slider = this.$.children[0];

      var str = [];
      for ( var i = 0 ; i < this.views.length ; i++ ) {
        // Hide all views except the first one.  They'll be shown after they're resized.
        // This prevents all views from overlapping on startup.
        str.push('
');
        str.push(this.views[i].view().toHTML());
        str.push('
');
      }

      this.slider.innerHTML = str.join('');

      window.addEventListener('resize', this.resize, false);
      this.X.gestureManager.install(this.swipeGesture);

      // Wait for the new HTML to render first, then init it.
      var self = this;
      window.setTimeout(function() {
        self.resize();
        self.views.forEach(function(choice) {
          choice.view().initHTML();
        });
        var vs = self.slider.querySelectorAll('.swipeAltInner');
        for ( var i = 0 ; i < vs.length ; i++ ) vs[i].style.visibility = '';
      }, 0);
    },

    destroy: function() {
      this.SUPER();
      this.X.gestureManager.uninstall(this.swipeGesture);
      this.views.forEach(function(c) { c.view().destroy(); });
    },

    snapToCurrent: function(sizeOfMove) {
      var self = this;
      var time = 150 + sizeOfMove * 150;
      Movement.animate(time, function(evt) {
        self.x = self.index * self.width;
      }, Movement.ease(150/time, 150/time), function() {
        self.views[self.index].view().deepPublish(self.ON_SHOW);
      })();
    }
  },

  listeners: [
    {
      name: 'resize',
      isMerged: 100,
      code: function() {
        // When the orientation of the screen has changed, update the
        // left and width values of the inner elements and slider.
        if ( ! this.$ ) {
          window.removeEventListener('resize', this.resize, false);
          return;
        }

        var self = this;
        var frame = window.requestAnimationFrame(function() {
          self.x = self.index * self.width;

          for ( var i = 0 ; i < self.slider.children.length ; i++ ) {
            self.slider.children[i].style.left = (i * 100) + '%';
            self.slider.children[i].style.visibility = '';
          }

          window.cancelAnimationFrame(frame);
        });
      }
    },
    {
      name: 'horizontalScrollMove',
      code: function(dx, tx, x) {
        var x = this.index * this.width - tx;

        // Limit x to be within the scope of the slider: no dragging too far.
        if (x < 0) x = 0;
        var maxWidth = (this.views.length - 1) * this.width;
        if ( x > maxWidth ) x = maxWidth;

        this.x = x;
      }
    },
    {
      name: 'horizontalScrollEnd',
      code: function(dx, tx, x) {
        if ( Math.abs(tx) > this.width / 3 ) {
          // Consider that a move.
          if (tx < 0) {
            this.index++;
          } else {
            this.index--;
          }
        } else {
          this.snapToCurrent(1);
        }
      }
    }
  ],
  templates: [
    function CSS() {/*
      .swipeAltInner {
        position: absolute;
        top: 0px;
        height: 100%;
        width: 100%;
      }

      .swipeAltOuter {
        display: flex;
        overflow: hidden;
        min-width: 240px;
        width: 100%;
        height: 100%;
      }

      .swipeAltSlider {
        position: relative;
        width: 100%;
        top: 0px;
        -webkit-transform: translate3d(0,0,0);
      }

    */}
  ]
});
<|endoftext|>


<commit_before>import { Request } from 'react-axios'
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isReady: false,
      isLoading: false,
      debounce: 200,
      url: ''
    }
  }

  render() {
    return (

          <Request
            isReady={this.state.isReady}
            method="get"
            debounce={this.state.debounce}
            url={this.state.url}
            onSuccess={()=>this.setState({ isReady: false, isLoading: false })}
            onLoading={()=>this.setState({ isLoading: true })}
            onError={()=>this.setState({ isReady: false, isLoading: false })}
          >
            {(error, response, isLoading) => {
              if(error) {
                return (
Something bad happened: {error.message}
)
              } else if(isLoading) {
                return (

)
              } else if(response !== null) {
                return (
{response.data.message}
)
              }
              return
Click a button to test its action.

            }}
          </Request>

        <button className="info" disabled={this.state.isLoading} onClick={()=>this.setState({ isReady: true, url: '/api/advanced', debounce: 200 })}>
          Make API Request
        </button>
        <button className="warning" onClick={()=>this.setState({ isReady: true, url: '/api/debounce/?t='+new Date().getTime(), debounce: 250 })}>
          Click rapidly for debounce test
        </button>
        <button className="warning" onClick={()=>this.setState({ isReady: true, url: '/api/cancel/?t='+new Date().getTime(), debounce: 0 })}>
          Click rapidly for cancel test
        </button>
        <button className="danger" disabled={this.state.isLoading} onClick={()=>this.setState({ isReady: true, url: '/error', debounce: 200 })}>
          Force API Error
        </button>

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
<commit_msg>adding test for component unmount.<commit_after>import { Request } from 'react-axios'
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isReady: false,
      isLoading: false,
      debounce: 200,
      url: '',
      unmount: false
    }
  }

  testUnmount() {
    this.setState({ isReady: true, url: '/api/cancel/?t='+new Date().getTime(), debounce: 0, unmount: false })
    setTimeout(()=>{
      this.setState({ unmount: true, isLoading: false, isReady: true })
    }, 500)
  }

  render() {
    return (

          {!this.state.unmount && <Request
            isReady={this.state.isReady}
            method="get"
            debounce={this.state.debounce}
            url={this.state.url}
            onSuccess={()=>this.setState({ isReady: false, isLoading: false })}
            onLoading={()=>this.setState({ isLoading: true })}
            onError={()=>this.setState({ isReady: false, isLoading: false })}
          >
            {(error, response, isLoading) => {
              if(error) {
                return (
Something bad happened: {error.message}
)
              } else if(isLoading) {
                return (

)
              } else if(response !== null) {
                return (
{response.data.message}
)
              }
              return
Click a button to test its action.

            }}
          </Request>}
          {this.state.unmount && 'Component unmounted.'}

        <button className="info" disabled={this.state.isLoading} onClick={()=>this.setState({ isReady: true, url: '/api/advanced', debounce: 200, unmount: false })}>
          Make API Request
        </button>
        <button className="warning" onClick={()=>this.setState({ isReady: true, url: '/api/debounce/?t='+new Date().getTime(), debounce: 250, unmount: false })}>
          Click rapidly for debounce test
        </button>
        <button className="warning" onClick={()=>this.setState({ isReady: true, url: '/api/cancel/?t='+new Date().getTime(), debounce: 0, unmount: false })}>
          Click rapidly for cancel test
        </button>
        <button className="danger" disabled={this.state.isLoading} onClick={()=>this.setState({ isReady: true, url: '/error', debounce: 200, unmount: false })}>
          Force API Error
        </button>
        <button className="danger" disabled={this.state.isLoading} onClick={()=>this.testUnmount()}>
          Unmount Test
        </button>

    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
<|endoftext|>


<commit_before>const {job} = require('root/jobs/job')

const worker$ = ({tableId, columnName, columnValue, buffer, color = '#FFFFFF50', fillColor = '#FFFFFF08'}) => {
    const ee = require('ee')
    const {filterTable} = require('sepal/ee/table')
    const {forkJoin} = require('rx')
    const {map} = require('rx/operators')
    const _ = require('lodash')

    const log = require('sepal/log').getLogger('ee')
    log.fatal(fillColor)

    const bufferMeters = (buffer && _.toNumber(buffer)) * 1000
    const table = bufferMeters
        ? filterTable({tableId, columnName, columnValue})
            .map(feature => feature.buffer(ee.Number(bufferMeters), bufferMeters / 10))
        : filterTable({tableId, columnName, columnValue})
    const bounds = bufferMeters
        ? table.geometry().bounds(bufferMeters / 10).buffer(ee.Number(bufferMeters), bufferMeters / 10).bounds(bufferMeters / 10)
        : table.geometry().bounds()
    const boundsPolygon = ee.List(bounds.coordinates().get(0))
    return forkJoin({
        bounds: ee.getInfo$(ee.List([boundsPolygon.get(0), boundsPolygon.get(2)]), 'get bounds'),
        eeMap: ee.getMap$(table.style({color, fillColor}))
    }).pipe(
        map(({bounds, eeMap}) => ({bounds, ...eeMap}))
    )
}

module.exports = job({
    jobName: 'Request EE Table map',
    jobPath: __filename,
    args: ctx => [ctx.request.query],
    worker$
})
<commit_msg>Cleanup.<commit_after>const {job} = require('root/jobs/job')

const worker$ = ({tableId, columnName, columnValue, buffer, color = '#FFFFFF50', fillColor = '#FFFFFF08'}) => {
    const ee = require('ee')
    const {filterTable} = require('sepal/ee/table')
    const {forkJoin} = require('rx')
    const {map} = require('rx/operators')
    const _ = require('lodash')

    const bufferMeters = (buffer && _.toNumber(buffer)) * 1000
    const table = bufferMeters
        ? filterTable({tableId, columnName, columnValue})
            .map(feature => feature.buffer(ee.Number(bufferMeters), bufferMeters / 10))
        : filterTable({tableId, columnName, columnValue})
    const bounds = bufferMeters
        ? table.geometry().bounds(bufferMeters / 10).buffer(ee.Number(bufferMeters), bufferMeters / 10).bounds(bufferMeters / 10)
        : table.geometry().bounds()
    const boundsPolygon = ee.List(bounds.coordinates().get(0))
    return forkJoin({
        bounds: ee.getInfo$(ee.List([boundsPolygon.get(0), boundsPolygon.get(2)]), 'get bounds'),
        eeMap: ee.getMap$(table.style({color, fillColor}))
    }).pipe(
        map(({bounds, eeMap}) => ({bounds, ...eeMap}))
    )
}

module.exports = job({
    jobName: 'Request EE Table map',
    jobPath: __filename,
    args: ctx => [ctx.request.query],
    worker$
})
<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(console.log);
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 780,
    height: 500
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<commit_msg>set new default app sizes<commit_after>import { app, BrowserWindow, Menu, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(console.log);
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 340,
    height: 500
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<|endoftext|>


<commit_before>// Mozilla Firefox User Preferences

// -----------------------------------------------------------------------------
// Startup
// -----------------------------------------------------------------------------

// Show a blank page when Firefox starts.
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.startup.page", 0);
user_pref("startup.homepage_welcome_url", "");
user_pref("startup.homepage_welcome_url.additional", "");
user_pref("startup.homepage_override_url", "");
user_pref("browser.rights.3.shown", true);
user_pref("browser.laterrun.enabled", false);

// Show a blank page when opening new tab.
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.directory.source", "data:text/plain,");
user_pref("browser.newtabpage.activity-stream.enabled", false);
user_pref("browser.library.activity-stream.enabled", false);

// Disable Slow Startup notifications.
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.slowStartup.samples", 0);
user_pref("browser.slowStartup.maxSamples", 0);

// -----------------------------------------------------------------------------
// Localization
// -----------------------------------------------------------------------------

// Choose preferred languages for displaying pages.
user_pref("intl.accept_languages", "ja, zh-tw, zh, en-us, en");

// Disable GeoIP-based search results.
user_pref("browser.search.countryCode", "JP");
user_pref("browser.search.region", "JP");
user_pref("browser.search.geoip.url", "");

// Disable geographically specific results/search engines.
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");

// -----------------------------------------------------------------------------
// Content
// -----------------------------------------------------------------------------

// Set minimum font size.
user_pref("font.minimum-size.ja", 10);
user_pref("font.minimum-size.ko", 10);
user_pref("font.minimum-size.zh-CN", 10);
user_pref("font.minimum-size.zh-HK", 10);
user_pref("font.minimum-size.zh-TW", 10);

// Disable Beacon.
user_pref("beacon.enabled", false);

// Disable pings.
user_pref("browser.send_pings", false);
user_pref("browser.send_pings.require_same_host", true);

// Disable camera image capture.
user_pref("dom.imagecapture.enabled", false);

// Disable canvas capture stream.
user_pref("canvas.capturestream.enabled", false);

// Disallow JavaScript to move or resize window.
user_pref("dom.disable_window_move_resize", true);

// Limit events that can cause a popup.
user_pref("dom.popup_allowed_events", "click dblclick mouseup");

// Decrease the maximum number of popups from a single non-click event.
user_pref("dom.popup_maximum", 2);

// Disable links opening in a new window.
user_pref("browser.link.open_newwindow.restriction", 0);

// Disable Notifications API.
user_pref("dom.webnotifications.enabled", false);
user_pref("dom.webnotifications.serviceworker.enabled", false);
user_pref("permissions.default.desktop-notification", 2);

// Disable Push API.
user_pref("dom.push.enabled", false);
user_pref("dom.push.connection.enabled", false);
user_pref("dom.push.serverURL", "");
user_pref("dom.push.userAgentID", "");

// Disable Geolocation.
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "");
user_pref("geo.wifi.logging.enabled", false);
user_pref("permissions.default.geo", 2);

// Disable audio auto-play in non-active tabs.
user_pref("media.block-autoplay-until-in-foreground", true);

// Disable WebRTC.
user_pref("media.peerconnection.enabled", false);
user_pref("media.peerconnection.ice.tcp", false);
user_pref("media.peerconnection.identity.enabled", false);
user_pref("media.peerconnection.identity.timeout", 1);
user_pref("media.peerconnection.turn.disable", true);
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("media.peerconnection.video.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.navigator.video.enabled", false);

// Limit WebRTC IP leaks.
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true);

// Disable WebRTC screen sharing.
user_pref("media.getusermedia.screensharing.enabled", false);
user_pref("media.getusermedia.audiocapture.enabled", false);
user_pref("media.getusermedia.browser.enabled", false);

// Disable WebGL.
user_pref("webgl.disabled", true);
user_pref("webgl.disable-extensions", true);
user_pref("webgl.disable-fail-if-major-performance-caveat", true);
user_pref("webgl.enable-debug-renderer-info", false);
user_pref("webgl.enable-webgl2", false);
user_pref("webgl.min_capability_mode", true);
user_pref("webgl.dxgl.enabled", false);
user_pref("pdfjs.enableWebGL", false);

// Block camera and microphone permissions.
user_pref("permissions.default.camera", 2);
user_pref("permissions.default.microphone", 2);

// -----------------------------------------------------------------------------
// Privacy
// -----------------------------------------------------------------------------

// Enable DNT HTTP header.
user_pref("privacy.donottrackheader.enabled", true);

// Enable Tracking Protection.
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.trackingprotection.ui.enabled", true);
user_pref("privacy.trackingprotection.introCount", 20);

// Enable First Party Isolation.
user_pref("privacy.firstparty.isolate", true);
user_pref("privacy.firstparty.isolate.restrict_opener_access", true);

// Never accept third-party cookies.
user_pref("network.cookie.cookieBehavior", 1);

// Disable prefetching.
user_pref("network.prefetch-next", false);
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);
user_pref("network.predictor.enable-prefetch", false);

// Disable opening connection to links when mouseover.
user_pref("network.http.speculative-parallel-limit", 0);

// Disable Seer/Necko.
user_pref("network.predictor.enabled", false);
user_pref("network.captive-portal-service.enabled", false);
user_pref("captivedetect.canonicalURL", "");

// -----------------------------------------------------------------------------
// Security
// -----------------------------------------------------------------------------

// Enable Safe Browsing.
user_pref("browser.safebrowsing.phishing.enabled", true);
user_pref("browser.safebrowsing.malware.enabled", true);

// Disable saving passwords.
user_pref("signon.rememberSignons", false);

// Enable OCSP stapling.
user_pref("security.ssl.enable_ocsp_stapling", true);
user_pref("security.OCSP.enabled", 1);
user_pref("security.OCSP.require", true);

// -----------------------------------------------------------------------------
// Features and Components
// -----------------------------------------------------------------------------

// Disable Health Report.
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);

// Disable Crash Reporter.
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);

// Disable Telemetry.
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.hybridContent.enabled", false);

// Disable Telemetry Experiments.
user_pref("experiments.enabled", false);
user_pref("experiments.supported", false);
user_pref("experiments.activeExperiment", false);
user_pref("experiments.manifest.uri", "");
user_pref("network.allow-experiments", false);

// Disable Onboarding.
user_pref("browser.onboarding.enabled", false);

// Disable Ping-centre telemetry.
user_pref("browser.ping-centre.telemetry", false);

// Disable UITour backend.
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");

// Disable remote debugging.
user_pref("devtools.webide.enabled", false);
user_pref("devtools.webide.autoinstallADBHelper", false);
user_pref("devtools.debugger.force-local", true);
user_pref("devtools.debugger.remote-enabled", false);
user_pref("devtools.chrome.enabled", false);

// Disable Reader View.
user_pref("reader.parse-on-load.enabled", false);

// -----------------------------------------------------------------------------
// Add-ons and Plugins
// -----------------------------------------------------------------------------

// Disable extension metadata updating.
user_pref("extensions.getAddons.cache.enabled", false);

// Disable Personas (themes) updating.
user_pref("lightweightThemes.update.enabled", false);

// Disable "Get Add-ons" pane.
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.webservice.discoverURL", "");

// Lock down allowed extension directories.
user_pref("extensions.enabledScopes", 1);

// Clear localStorage and UUID when an extension is uninstalled.
user_pref("extensions.webextensions.keepStorageOnUninstall", false);
user_pref("extensions.webextensions.keepUuidOnUninstall", false);

// Disable Form Autofill.
user_pref("extensions.formautofill.available", "off");
user_pref("extensions.formautofill.addresses.enabled", false);
user_pref("extensions.formautofill.creditCards.enabled", false);
user_pref("extensions.formautofill.heuristics.enabled", false);

// Disable Pocket.
user_pref("extensions.pocket.enabled", false);

// Disable Shield and Normandy (telemetry system).
user_pref("extensions.shield-recipe-client.enabled", false);
user_pref("extensions.shield-recipe-client.api_url", "");
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
user_pref("app.shield.optoutstudies.enabled", false);

// Disable Web Compatibility Reporter.
user_pref("extensions.webcompat-reporter.enabled", false);

// Disable all plugins by default.
user_pref("plugin.default.state", 0);
user_pref("plugin.defaultXpi.state", 0);

// Enable click-to-play and set the session permission.
user_pref("plugins.click_to_play", true);
user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0);

// Disable scanning plugins on Windows.
user_pref("plugin.scan.plid.all", false);

// Disable all GMP (Gecko Media Plugins).
user_pref("media.gmp-provider.enabled", false);
user_pref("media.gmp-manager.url", "data:text/plain,");
user_pref("media.gmp-manager.url.override", "data:text/plain,");
user_pref("media.gmp-manager.updateEnabled", false);
user_pref("media.gmp.trial-create.enabled", false);

// Disable widevine CDM.
user_pref("media.gmp-widevinecdm.visible", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.gmp-widevinecdm.autoupdate", false);

// Disable all DRM content.
user_pref("media.eme.enabled", false);
user_pref("browser.eme.ui.enabled", false);

// Disable OpenH264 Video Codec by Cisco.
user_pref("media.gmp-gmpopenh264.enabled", false);
user_pref("media.gmp-gmpopenh264.autoupdate", false);

// Skip the installation delay.
user_pref("security.dialog_enable_delay", 0);

// -----------------------------------------------------------------------------
// Others
// -----------------------------------------------------------------------------

// Prevent accessibility services from accessing browser.
user_pref("accessibility.force_disabled", 1);

// Always ask me where to save download files.
user_pref("browser.download.useDownloadDir", false);

// Disable downloading on desktop.
user_pref("browser.download.folderList", 2);

// Always display download button on toolbar.
user_pref("browser.download.autohideButton", false);

// Disable URL bar domain guessing.
user_pref("browser.fixup.alternate.enabled", false);

// Strip password from URL.
user_pref("browser.fixup.hide_user_pass", true);

// Disable capturing page thumbnails.
user_pref("browser.pagethumbnails.capturing_disabled", false);

// Display search bar by default.
user_pref("browser.search.widget.inNavBar", true);

// Disable closing browser with last tab.
user_pref("browser.tabs.closeWindowWithLastTab", false);

// Disable Windows Taskbar Jump List.
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);

// Disable URL bar autofill.
user_pref("browser.urlbar.autoFill", false);
user_pref("browser.urlbar.autoFill.typed", false);

// Disable search suggestions in the URL bar.
user_pref("browser.urlbar.suggest.searches", false);
user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true);
user_pref("browser.urlbar.oneOffSearches", false);

// Disable URL bar making speculative connections.
user_pref("browser.urlbar.speculativeConnect.enabled", false);

// Display all parts of the URL in the URL bar.
user_pref("browser.urlbar.trimURLs", false);

// Disable preloading top websites in the URL bar.
user_pref("browser.urlbar.usepreloadedtopurls.enabled", false);

// Disable site specific zoom.
user_pref("browser.zoom.siteSpecific", false);

// Disable `about:config` warnings.
user_pref("general.warnOnAboutConfig", false);

// Display the raw Punycode in the URL bar.
user_pref("network.IDN_show_punycode", true);

// Disable links launching Windows Store.
user_pref("network.protocol-handler.external.ms-windows-store", false);

// Disable Windows Family Safety Mode.
user_pref("security.family_safety.mode", 0);

// Disable UI animation.
user_pref("toolkit.cosmeticAnimations.enabled", false);
user_pref("browser.stopReloadAnimation.enabled", false);
<commit_msg>Remove some config for better browsering experience<commit_after>// Mozilla Firefox User Preferences

// -----------------------------------------------------------------------------
// Startup
// -----------------------------------------------------------------------------

// Show a blank page when Firefox starts.
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.startup.page", 0);
user_pref("startup.homepage_welcome_url", "");
user_pref("startup.homepage_welcome_url.additional", "");
user_pref("startup.homepage_override_url", "");
user_pref("browser.rights.3.shown", true);
user_pref("browser.laterrun.enabled", false);

// Show a blank page when opening new tab.
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.newtabpage.directory.source", "data:text/plain,");
user_pref("browser.newtabpage.activity-stream.enabled", false);
user_pref("browser.library.activity-stream.enabled", false);

// Disable Slow Startup notifications.
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.slowStartup.samples", 0);
user_pref("browser.slowStartup.maxSamples", 0);

// -----------------------------------------------------------------------------
// Localization
// -----------------------------------------------------------------------------

// Choose preferred languages for displaying pages.
user_pref("intl.accept_languages", "ja, zh-tw, zh, en-us, en");

// Disable GeoIP-based search results.
user_pref("browser.search.countryCode", "JP");
user_pref("browser.search.region", "JP");
user_pref("browser.search.geoip.url", "");

// Disable geographically specific results/search engines.
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");

// -----------------------------------------------------------------------------
// Content
// -----------------------------------------------------------------------------

// Set minimum font size.
user_pref("font.minimum-size.ja", 10);
user_pref("font.minimum-size.ko", 10);
user_pref("font.minimum-size.zh-CN", 10);
user_pref("font.minimum-size.zh-HK", 10);
user_pref("font.minimum-size.zh-TW", 10);

// Disable Beacon.
user_pref("beacon.enabled", false);

// Disable pings.
user_pref("browser.send_pings", false);
user_pref("browser.send_pings.require_same_host", true);

// Disable camera image capture.
user_pref("dom.imagecapture.enabled", false);

// Disable canvas capture stream.
user_pref("canvas.capturestream.enabled", false);

// Disallow JavaScript to move or resize window.
user_pref("dom.disable_window_move_resize", true);

// Decrease the maximum number of popups from a single non-click event.
user_pref("dom.popup_maximum", 2);

// Disable links opening in a new window.
user_pref("browser.link.open_newwindow.restriction", 0);

// Disable Notifications API.
user_pref("dom.webnotifications.enabled", false);
user_pref("dom.webnotifications.serviceworker.enabled", false);
user_pref("permissions.default.desktop-notification", 2);

// Disable Push API.
user_pref("dom.push.enabled", false);
user_pref("dom.push.connection.enabled", false);
user_pref("dom.push.serverURL", "");
user_pref("dom.push.userAgentID", "");

// Disable Geolocation.
user_pref("geo.enabled", false);
user_pref("geo.wifi.uri", "");
user_pref("geo.wifi.logging.enabled", false);
user_pref("permissions.default.geo", 2);

// Disable audio auto-play in non-active tabs.
user_pref("media.block-autoplay-until-in-foreground", true);

// Disable WebRTC.
user_pref("media.peerconnection.enabled", false);
user_pref("media.peerconnection.ice.tcp", false);
user_pref("media.peerconnection.identity.enabled", false);
user_pref("media.peerconnection.identity.timeout", 1);
user_pref("media.peerconnection.turn.disable", true);
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("media.peerconnection.video.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.navigator.video.enabled", false);

// Limit WebRTC IP leaks.
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true);

// Disable WebRTC screen sharing.
user_pref("media.getusermedia.screensharing.enabled", false);
user_pref("media.getusermedia.audiocapture.enabled", false);
user_pref("media.getusermedia.browser.enabled", false);

// Block camera and microphone permissions.
user_pref("permissions.default.camera", 2);
user_pref("permissions.default.microphone", 2);

// -----------------------------------------------------------------------------
// Privacy
// -----------------------------------------------------------------------------

// Enable DNT HTTP header.
user_pref("privacy.donottrackheader.enabled", true);

// Enable Tracking Protection.
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.trackingprotection.ui.enabled", true);
user_pref("privacy.trackingprotection.introCount", 20);

// Enable First Party Isolation.
user_pref("privacy.firstparty.isolate", true);
user_pref("privacy.firstparty.isolate.restrict_opener_access", true);

// Never accept third-party cookies.
user_pref("network.cookie.cookieBehavior", 1);

// Disable opening connection to links when mouseover.
user_pref("network.http.speculative-parallel-limit", 0);

// -----------------------------------------------------------------------------
// Security
// -----------------------------------------------------------------------------

// Enable Safe Browsing.
user_pref("browser.safebrowsing.phishing.enabled", true);
user_pref("browser.safebrowsing.malware.enabled", true);

// Disable saving passwords.
user_pref("signon.rememberSignons", false);

// Enable OCSP stapling.
user_pref("security.ssl.enable_ocsp_stapling", true);
user_pref("security.OCSP.enabled", 1);
user_pref("security.OCSP.require", true);

// -----------------------------------------------------------------------------
// Features and Components
// -----------------------------------------------------------------------------

// Disable Health Report.
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);

// Disable Crash Reporter.
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);

// Disable Telemetry.
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.hybridContent.enabled", false);

// Disable Telemetry Experiments.
user_pref("experiments.enabled", false);
user_pref("experiments.supported", false);
user_pref("experiments.activeExperiment", false);
user_pref("experiments.manifest.uri", "");
user_pref("network.allow-experiments", false);

// Disable Onboarding.
user_pref("browser.onboarding.enabled", false);

// Disable Ping-centre telemetry.
user_pref("browser.ping-centre.telemetry", false);

// Disable UITour backend.
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");

// Disable remote debugging.
user_pref("devtools.webide.enabled", false);
user_pref("devtools.webide.autoinstallADBHelper", false);
user_pref("devtools.debugger.force-local", true);
user_pref("devtools.debugger.remote-enabled", false);
user_pref("devtools.chrome.enabled", false);

// Disable Reader View.
user_pref("reader.parse-on-load.enabled", false);

// -----------------------------------------------------------------------------
// Add-ons and Plugins
// -----------------------------------------------------------------------------

// Disable "Get Add-ons" pane.
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.webservice.discoverURL", "");

// Lock down allowed extension directories.
user_pref("extensions.enabledScopes", 1);

// Clear localStorage and UUID when an extension is uninstalled.
user_pref("extensions.webextensions.keepStorageOnUninstall", false);
user_pref("extensions.webextensions.keepUuidOnUninstall", false);

// Disable Form Autofill.
user_pref("extensions.formautofill.available", "off");
user_pref("extensions.formautofill.addresses.enabled", false);
user_pref("extensions.formautofill.creditCards.enabled", false);
user_pref("extensions.formautofill.heuristics.enabled", false);

// Disable Pocket.
user_pref("extensions.pocket.enabled", false);

// Disable Shield and Normandy (telemetry system).
user_pref("extensions.shield-recipe-client.enabled", false);
user_pref("extensions.shield-recipe-client.api_url", "");
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
user_pref("app.shield.optoutstudies.enabled", false);

// Disable Web Compatibility Reporter.
user_pref("extensions.webcompat-reporter.enabled", false);

// Disable all plugins by default.
user_pref("plugin.default.state", 0);
user_pref("plugin.defaultXpi.state", 0);

// Enable click-to-play and set the session permission.
user_pref("plugins.click_to_play", true);
user_pref("plugin.sessionPermissionNow.intervalInMinutes", 0);

// Disable scanning plugins on Windows.
user_pref("plugin.scan.plid.all", false);

// Disable all GMP (Gecko Media Plugins).
user_pref("media.gmp-provider.enabled", false);
user_pref("media.gmp-manager.url", "data:text/plain,");
user_pref("media.gmp-manager.url.override", "data:text/plain,");
user_pref("media.gmp-manager.updateEnabled", false);
user_pref("media.gmp.trial-create.enabled", false);

// Disable widevine CDM.
user_pref("media.gmp-widevinecdm.visible", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.gmp-widevinecdm.autoupdate", false);

// Disable all DRM content.
user_pref("media.eme.enabled", false);
user_pref("browser.eme.ui.enabled", false);

// Disable OpenH264 Video Codec by Cisco.
user_pref("media.gmp-gmpopenh264.enabled", false);
user_pref("media.gmp-gmpopenh264.autoupdate", false);

// Skip the installation delay.
user_pref("security.dialog_enable_delay", 0);

// -----------------------------------------------------------------------------
// Others
// -----------------------------------------------------------------------------

// Prevent accessibility services from accessing browser.
user_pref("accessibility.force_disabled", 1);

// Always ask me where to save download files.
user_pref("browser.download.useDownloadDir", false);

// Disable downloading on desktop.
user_pref("browser.download.folderList", 2);

// Always display download button on toolbar.
user_pref("browser.download.autohideButton", false);

// Disable URL bar domain guessing.
user_pref("browser.fixup.alternate.enabled", false);

// Strip password from URL.
user_pref("browser.fixup.hide_user_pass", true);

// Disable capturing page thumbnails.
user_pref("browser.pagethumbnails.capturing_disabled", false);

// Display search bar by default.
user_pref("browser.search.widget.inNavBar", true);

// Disable closing browser with last tab.
user_pref("browser.tabs.closeWindowWithLastTab", false);

// Disable Windows Taskbar Jump List.
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);

// Disable URL bar autofill.
user_pref("browser.urlbar.autoFill", false);
user_pref("browser.urlbar.autoFill.typed", false);

// Disable search suggestions in the URL bar.
user_pref("browser.urlbar.suggest.searches", false);
user_pref("browser.urlbar.userMadeSearchSuggestionsChoice", true);
user_pref("browser.urlbar.oneOffSearches", false);

// Display all parts of the URL in the URL bar.
user_pref("browser.urlbar.trimURLs", false);

// Disable site specific zoom.
user_pref("browser.zoom.siteSpecific", false);

// Disable `about:config` warnings.
user_pref("general.warnOnAboutConfig", false);

// Display the raw Punycode in the URL bar.
user_pref("network.IDN_show_punycode", true);

// Disable links launching Windows Store.
user_pref("network.protocol-handler.external.ms-windows-store", false);

// Disable Windows Family Safety Mode.
user_pref("security.family_safety.mode", 0);

// Disable UI animation.
user_pref("toolkit.cosmeticAnimations.enabled", false);
user_pref("browser.stopReloadAnimation.enabled", false);
<|endoftext|>


<commit_before>var util = require('util')
	, EventEmitter = require('events').EventEmitter
	, spawn = require('child_process').spawn
	, path = require('path')
	, cmdDir = process.env.ES_BIN || path.resolve(__dirname, 'EventStore')
	, cmd = path.resolve(cmdDir, 'clusternode')
	, opts = {
			cwd: cmdDir
		, env: {
				'LD_LIBRARY_PATH': cmdDir + ':$LD_LIBRARY_PATH'
			, 'MONO_GC_DEBUG': 'clear-at-gc'
			}
		}
	, currentPort = 5000

module.exports = MemoryStore

function LogDebug(msg) {
	//console.log(msg)
}

function MemoryStore(done) {
	if(!(this instanceof MemoryStore)) {
    return new MemoryStore(done)
	}
	EventEmitter.call(this)

	var me = this
	initializeGesProcess()

	function initializeGesProcess() {
		var settings = getSettings()
			, es = spawn(cmd, getArgsArray(settings), opts)
			, isIntialized = false

		me._es = es

		es.stdout.on('data', function(data) {
			LogDebug('[LOG] : ' + data.toString())
			var logLine = data.toString()
			if(logLine.indexOf("'$users' projection source has been written") !== -1) {
				isIntialized = true
				done(null, {
					host: settings.ip
				, port: settings.tcpPort
				})
			} else if(logLine.indexOf('Exit reason: Address already in use') !== -1) {
				me._removeHandlers()
				initializeGesProcess()
			}
		})

		es.stderr.on('data', function(data) {
			LogDebug('[ERR] : ' + data.toString())
			var err = data.toString()
			cb(data.toString())
			if(isIntialized) {
				me.emit('error', err)
				me._close()
			} else {
				done(err)
			}
		})

		es.on('close', function(signal) {
			LogDebug('passive close', arguments)
			me._removeHandlers()
		})

		es.on('exit', function(signal) {
			LogDebug('passive exit', arguments)
			me._removeHandlers()
		})

		es.on('error', function(err) {
			if(isIntialized) {
				me.emit('error', err)
				me._close()
			} else {
				done(err)
			}
		})
	}
}
util.inherits(MemoryStore, EventEmitter)

MemoryStore.prototype._close = function() {
	this._es.kill('SIGINT')
}

MemoryStore.prototype._removeHandlers = function() {
	this._es.removeAllListeners()
	this._es.stdin.removeAllListeners()
	this._es.stdout.removeAllListeners()
}

MemoryStore.prototype.addConnection = function(con) {
	this._con = con
}

MemoryStore.prototype.cleanup = function(cb) {
	var me = this
		, isClosed = false
	this._es.removeAllListeners('close')
	this._es.removeAllListeners('error')

	function completeClose(msg) {
		me._removeHandlers()
		if(!isClosed) {
			if(msg) {
				LogDebug('COMPLETE CLOSE ERROR: ' + msg)
			}
			isClosed = true
			cb()
		}
	}

	this._es.stdout.on('data', function(data) {
		LogDebug(data.toString())
	})

	this._es.on('close', function(signal) {
		LogDebug('in close handler',arguments)
		completeClose()
	}).on('exit', function(signal) {
		LogDebug('in exit handler',arguments)
		completeClose()
	}).on('error', function(err) {
		completeClose('Had error closing')
	})

	setTimeout(function() {
		completeClose('Close timeout')
	}, 5000)

	function closeGes() {
		me._close()
	}

	if(this._con) {
		LogDebug('closing connection')
		this._con.close(closeGes)
	} else {
		closeGes()
	}
}

function getSettings() {
	currentPort += 1
	return {
		ip: '127.0.0.1'
	, tcpPort: currentPort
	}
}

function getArgsArray(args) {
	var allArgs = ['--mem-db']
	if(args.ip) allArgs.push('--ext-ip=' + args.ip)
	if(args.tcpPort) {
		allArgs.push('--ext-tcp-port=' + args.tcpPort)
		allArgs.push('--ext-http-port=' + (args.tcpPort + 1000))
	}
	return allArgs
}<commit_msg>Memory Store now properly closes and cleans up provided connections<commit_after>var util = require('util')
	, EventEmitter = require('events').EventEmitter
	, spawn = require('child_process').spawn
	, path = require('path')
	, cmdDir = process.env.ES_BIN || path.resolve(__dirname, 'EventStore')
	, cmd = path.resolve(cmdDir, 'clusternode')
	, opts = {
			cwd: cmdDir
		, env: {
				'LD_LIBRARY_PATH': cmdDir + ':$LD_LIBRARY_PATH'
			, 'MONO_GC_DEBUG': 'clear-at-gc'
			}
		}
	, currentPort = 5000

module.exports = MemoryStore

function LogDebug(msg) {
	//console.log(msg)
}

function MemoryStore(done) {
	if(!(this instanceof MemoryStore)) {
    return new MemoryStore(done)
	}
	EventEmitter.call(this)

	var me = this
	initializeGesProcess()

	function initializeGesProcess() {
		var settings = getSettings()
			, es = spawn(cmd, getArgsArray(settings), opts)
			, isIntialized = false

		me._es = es

		es.stdout.on('data', function(data) {
			LogDebug('[LOG] : ' + data.toString())
			var logLine = data.toString()
			if(logLine.indexOf("'$users' projection source has been written") !== -1) {
				isIntialized = true
				done(null, {
					host: settings.ip
				, port: settings.tcpPort
				})
			} else if(logLine.indexOf('Exit reason: Address already in use') !== -1) {
				me._removeHandlers()
				initializeGesProcess()
			}
		})

		es.stderr.on('data', function(data) {
			LogDebug('[ERR] : ' + data.toString())
			var err = data.toString()
			cb(data.toString())
			if(isIntialized) {
				me.emit('error', err)
				me._close()
			} else {
				done(err)
			}
		})

		es.on('close', function(signal) {
			LogDebug('passive close', arguments)
			me._removeHandlers()
		})

		es.on('exit', function(signal) {
			LogDebug('passive exit', arguments)
			me._removeHandlers()
		})

		es.on('error', function(err) {
			if(isIntialized) {
				me.emit('error', err)
				me._close()
			} else {
				done(err)
			}
		})
	}
}
util.inherits(MemoryStore, EventEmitter)

MemoryStore.prototype._close = function() {
	this._es.kill('SIGINT')
}

MemoryStore.prototype._removeHandlers = function() {
	this._es.removeAllListeners()
	this._es.stdin.removeAllListeners()
	this._es.stdout.removeAllListeners()
}

MemoryStore.prototype.addConnection = function(con) {
	this._con = con
}

MemoryStore.prototype.cleanup = function(cb) {
	var me = this
		, isClosed = false
	this._es.removeAllListeners('close')
	this._es.removeAllListeners('error')

	function completeClose(msg) {
		me._removeHandlers()
		if(!isClosed) {
			if(msg) {
				LogDebug('COMPLETE CLOSE ERROR: ' + msg)
			}
			isClosed = true
			cb()
		}
	}

	this._es.stdout.on('data', function(data) {
		LogDebug(data.toString())
	})

	this._es.on('close', function(signal) {
		LogDebug('in close handler',arguments)
		completeClose()
	}).on('exit', function(signal) {
		LogDebug('in exit handler',arguments)
		completeClose()
	}).on('error', function(err) {
		completeClose('Had error closing')
	})

	setTimeout(function() {
		completeClose('Close timeout')
	}, 5000)

	function closeGes() {
		me._close()
		if(this._con) {
			this._con.removeAllListeners()
		}
	}

	if(this._con) {
		LogDebug('closing connection')
		this._con.on('close', closeGes)
		this._con.close()
	} else {
		closeGes()
	}
}

function getSettings() {
	currentPort += 1
	return {
		ip: '127.0.0.1'
	, tcpPort: currentPort
	}
}

function getArgsArray(args) {
	var allArgs = ['--mem-db']
	if(args.ip) allArgs.push('--ext-ip=' + args.ip)
	if(args.tcpPort) {
		allArgs.push('--ext-tcp-port=' + args.tcpPort)
		allArgs.push('--ext-http-port=' + (args.tcpPort + 1000))
	}
	return allArgs
}<|endoftext|>


<commit_before>var exampleType = module.exports;

/**
 * The type() hook.
 */
exampleType.type = function(types, callback) {
  var newTypes = {};

  // A basic article resource.
  newTypes['article'] = {
    title: 'Article',
    description: 'Articles are pieces of text with a title.',
    storage: 'database',
    keyProperty: 'id',
    fields: {
      id: {
        title: 'Id',
        type: 'id'
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      },
      body: {
        title: 'Body',
        type: 'text',
        element: {
          type: 'wysiwyg'
        }
      },
      image: {
        title: 'Image',
        type: 'file'
      },
      categories: {
        title: 'Categories',
        type: 'reference',
        reference: {
          type: 'category',
          multiple: true,
          titleField: 'title'
        },
        element: {
          type: 'tag',
          placeholder: 'Select categories...'
        }
      }
    },
    access: {
      'list': true,
      'load': true,
      'add': true,
      'edit': true,
      'delete': true
    }
  };

  callback(null, newTypes);
};

/**
 * The page() hook.
 */
exampleType.page = function(pages, callback) {
  var newPages = {};

  newPages['add-article'] = {
    path: '/add-article',
    type: 'form',
    title: 'Add article',
    formName: 'type-article'
  };

  callback(null, newPages);
};
<commit_msg>Improving type example.<commit_after>var exampleType = module.exports;

/**
 * The type() hook.
 */
exampleType.type = function(types, callback) {
  var newTypes = {};

  // A basic article resource.
  newTypes['article'] = {
    title: 'Article',
    description: 'Articles are pieces of text with a title.',
    storage: 'database',
    keyProperty: 'id',
    fields: {
      id: {
        title: 'Id',
        type: 'id'
      },
      title: {
        title: 'Title',
        type: 'text',
        required: true
      },
      body: {
        title: 'Body',
        type: 'text',
        element: {
          type: 'wysiwyg'
        }
      },
      image: {
        title: 'Image',
        type: 'file'
      },
      category: {
        title: 'Category',
        type: 'text',
        options: {
          'sports': 'Sports',
          'politics': 'Politics'
        },
        multiple: true,
        required: true
      }
    },
    access: {
      'list': true,
      'load': true,
      'add': true,
      'edit': true,
      'delete': true
    }
  };

  callback(null, newTypes);
};

/**
 * The page() hook.
 */
exampleType.page = function(pages, callback) {
  var newPages = {};

  newPages['add-article'] = {
    path: '/add-article',
    type: 'form',
    title: 'Add article',
    formName: 'type-article',
    itemType: 'article',
    redirect: '/edit-article/[id|item]'
  };
  newPages['edit-article'] = {
    path: '/edit-article/:id',
    type: 'form',
    title: 'Edit article',
    formName: 'type-article',
    itemType: 'article'
  };

  callback(null, newPages);
};
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * This file is used during string and audio plugin resolution in order to accomplish 2 goals:
 *
 * (a) determine that PhET Simulations are built using compatible resources.  Each resource (image or audio file) must
 * be annotated in a license.json file in the same directory.  Resource files without a compatible license will cause
 * the build to fail.
 *
 * (b) provide information from the 3rd party resource files to the build system, so that a report can be included in the
 * build HTML file
 *
 * The return value from this function is a javascript object literal of the form:
 *   {classification: <string>, isProblematic: <boolean>, entry: <object> }
 *
 * The classification is one of: missing-license.json, not-annotated, phet or third-party
 * isProblematic indicates whether the particular license is compatible with PhET's licensing
 * entry: the object that appears in the license.json file, see
 * https://github.com/phetsims/simula-rasa/blob/master/images/README.txt
 *
 * In order to simplify compatibility with requirejs and node versions, the return value is a javascript object literal
 * rather than a separate file/constructor function such as LicenseInfo.js
 *
 * @author Sam Reid
 */
(function() {
  'use strict';

  // During a build, store the 3rd party data for reporting in the HTML file.
  if ( typeof global !== 'undefined' ) {
    global.imageAndAudioLicenseInfo = global.imageAndAudioLicenseInfo || {};
  }

  /**
   * Returns a string indicating a problem with licensing for the image/audio file, or null if there is no problem found.
   * The license.json file is consulted.  This function has no side effects (compare to getLicenseInfo above)
   *
   * @param {string} abspath - the path for the file
   * @returns {*}
   *
   * @private
   */
  function _getLicenseInfo( abspath ) {
    var lastSlash = abspath.lastIndexOf( '/' );
    var prefix = abspath.substring( 0, lastSlash );
    var licenseFilename = prefix + '/license.json';
    var assetFilename = abspath.substring( lastSlash + 1 );

    var file = null;
    // look in the license.json file to see if there is an entry for that file
    try {
      file = global.fs.readFileSync( licenseFilename, 'utf8' );
    }
    catch( err ) {
      return { classification: 'missing-license.json', isProblematic: true, entry: null };
    }
    var json = JSON.parse( file );

    var entry = json[ assetFilename ];

    if ( !entry ) {
      return { classification: 'not-annotated', isProblematic: true, entry: entry };
    }
    else if ( entry.projectURL === 'http://phet.colorado.edu' ) {
      return { classification: 'phet', isProblematic: false, entry: entry };
    }
    else if ( entry.license === 'Public Domain' ) {
      // public domain OK, but should still be annotated
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.license === 'NASA' ) {
      // NASA OK, but should still be annotated
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.projectURL === 'http://www.americancinematheque.com/ball/1997MPBTravolta.htm' ) {
      // We decided to allow images for John Travoltage even though we were unable to contact American Cinematheque for
      // explicit permission
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.notes === 'from Snow Day Math' ) {
      // Permit Snow Day Match images to pass the build--they should be replaced in the near future
      // by PhET-created artwork, see https://github.com/phetsims/making-tens/issues/25
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else {
      return { classification: 'third-party', isProblematic: true, entry: entry };
    }
  }

  /**
   * Returns the classification from _getLicenseInfo but also has the side effect of adding it to a global variable
   * for providing licensing information for 3rd party resources in the built HTML file, looking for unused annotations,
   * etc.
   * @returns {Function}
   */
  var getLicenseInfo = function() {
    return function( name, abspath ) {
      var licenseInfo = _getLicenseInfo( abspath );

      // Make it available for adding a list of 3rd party resources to the HTML
      // and for checking whether there are unused images/audio
      global.imageAndAudioLicenseInfo[ name ] = licenseInfo;

      // Return it for further processing
      return licenseInfo;
    };
  };

  // browser require.js-compatible definition
  if ( typeof define !== 'undefined' ) {
    define( function() {
      return getLicenseInfo();
    } );
  }

  // Node.js-compatible definition
  if ( typeof module !== 'undefined' ) {
    module.exports = getLicenseInfo();
  }
})();<commit_msg>Cleaned up implementation for getLicenseInfo.js<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * This file is used during string and audio plugin resolution in order to accomplish 2 goals:
 *
 * (a) determine that PhET Simulations are built using compatible resources.  Each resource (image or audio file) must
 * be annotated in a license.json file in the same directory.  Resource files without a compatible license will cause
 * the build to fail.
 *
 * (b) provide information from the 3rd party resource files to the build system, so that a report can be included in the
 * build HTML file
 *
 * The return value from this function is a javascript object literal of the form:
 *   {classification: <string>, isProblematic: <boolean>, entry: <object> }
 *
 * The classification is one of: missing-license.json, not-annotated, phet or third-party
 * isProblematic indicates whether the particular license is compatible with PhET's licensing
 * entry: the object that appears in the license.json file, see
 * https://github.com/phetsims/simula-rasa/blob/master/images/README.txt
 *
 * In order to simplify compatibility with requirejs and node versions, the return value is a javascript object literal
 * rather than a separate file/constructor function such as LicenseInfo.js
 *
 * @author Sam Reid
 */
(function() {
  'use strict';

  // During a build, store the 3rd party data for reporting in the HTML file.
  if ( typeof global !== 'undefined' ) {
    global.imageAndAudioLicenseInfo = global.imageAndAudioLicenseInfo || {};
  }

  /**
   * Returns a string indicating a problem with licensing for the image/audio file, or null if there is no problem found.
   * The license.json file is consulted.  This function has no side effects (compare to getLicenseInfo above)
   *
   * @param {string} abspath - the path for the file
   * @returns {*}
   *
   * @private
   */
  function _getLicenseInfo( abspath ) {
    var lastSlash = abspath.lastIndexOf( '/' );
    var prefix = abspath.substring( 0, lastSlash );
    var licenseFilename = prefix + '/license.json';
    var assetFilename = abspath.substring( lastSlash + 1 );

    var file = null;
    // look in the license.json file to see if there is an entry for that file
    try {
      file = global.fs.readFileSync( licenseFilename, 'utf8' );
    }
    catch( err ) {
      return { classification: 'missing-license.json', isProblematic: true, entry: null };
    }
    var json = JSON.parse( file );

    var entry = json[ assetFilename ];

    if ( !entry ) {
      return { classification: 'not-annotated', isProblematic: true, entry: entry };
    }
    else if ( entry.projectURL === 'http://phet.colorado.edu' ) {
      return { classification: 'phet', isProblematic: false, entry: entry };
    }
    else if ( entry.license === 'Public Domain' ) {
      // public domain OK, but should still be annotated
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.license === 'NASA' ) {
      // NASA OK, but should still be annotated
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.projectURL === 'http://www.americancinematheque.com/ball/1997MPBTravolta.htm' ) {
      // We decided to allow images for John Travoltage even though we were unable to contact American Cinematheque for
      // explicit permission
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else if ( entry.notes === 'from Snow Day Math' ) {
      // Permit Snow Day Match images to pass the build--they should be replaced in the near future
      // by PhET-created artwork, see https://github.com/phetsims/making-tens/issues/25
      return { classification: 'third-party', isProblematic: false, entry: entry };
    }
    else {
      return { classification: 'third-party', isProblematic: true, entry: entry };
    }
  }

  /**
   * Returns the classification from _getLicenseInfo but also has the side effect of adding it to a global variable
   * for providing licensing information for 3rd party resources in the built HTML file, looking for unused annotations,
   * etc.
   * @returns {Function}
   */
  var getLicenseInfo = function( name, abspath ) {
    var licenseInfo = _getLicenseInfo( abspath );

    // Make it available for adding a list of 3rd party resources to the HTML
    // and for checking whether there are unused images/audio
    global.imageAndAudioLicenseInfo[ name ] = licenseInfo;

    // Return it for further processing
    return licenseInfo;
  };

  // browser require.js-compatible definition
  if ( typeof define !== 'undefined' ) {
    define( function() {
      return getLicenseInfo;
    } );
  }

  // Node.js-compatible definition
  if ( typeof module !== 'undefined' ) {
    module.exports = getLicenseInfo;
  }
})();<|endoftext|>


<commit_before>const dialog = require('electron').remote.require('dialog');
const fs = require('fs');

$(document).ready(function () {
    $('#submit-btn').click(function () {
        let text = $('#inputText').val();
        if (text == null || text.length === 0) {
            $("#algo-panel").prepend(createAlert("You have submitted an empty string. Please try again."));
        }
        else {
            constructVisTree(text);
            $("#customAlert").remove();
        }
    });

    $('#random-btn').click(function () {
        let numberOfChars = rangeSlider.noUiSlider.get();
        let randomString = generateRandomString(numberOfChars);
        $('#inputText').val(randomString);
        $('#inputFormGroup').removeClass('is-empty');
        $("#customAlert").remove();
        constructVisTree(randomString);
    });

    $('#upload-btn').bind('click', function () {
        dialog.showOpenDialog(function (fileNames) {
            if (fileNames === undefined) {
                console.log("No file selected");
            }
            else {
                readFile(fileNames[0]);
            }
        });
    });
});

function readFile(filepath) {
    let content;
    fs.readFile(filepath, 'utf-8', function (err, data) {
        if (err) {
            $("#algo-panel").prepend(createAlert("Error while trying to read the file. Please upload another one."));
            return;
        }
        content = data;
        processFile();
    });

    function processFile() {
        if (content == null || content.length === 0) {
            $("#algo-panel").prepend(createAlert("You have submitted an empty string. Please try again."));
        }
        else {
            $("#customAlert").remove();
            constructVisTree(content);
            $('#inputFormGroup').removeClass('is-empty');
            $('#inputText').val(content);
        }
    }
}

function constructVisTree(text) {
    addFrequencyTable(text);
    let huffmanTree = buildHuffmanTree(text);
    let nodes = huffmanTree.nodes;
    let edges = huffmanTree.edges;
    let network;

    // create a network
    const container = $('#tree-simple')[0];

    // provide the data in the vis format
    const data = {
        nodes: nodes,
        edges: edges
    };

    const options = {
        autoResize: true,
        layout: {
            hierarchical: {
                enabled: true,
                parentCentralization: true,
                sortMethod: "directed",
                edgeMinimization: true
            }
        },
        interaction: {
            navigationButtons: true
        },
        physics: {
            enabled: false
        }
    };

    network = new Vis.Network(container, data, options);
    const delay = text.length * 6000;

    constructLeafNodes(network, nodes, container, options, edges, text);
    runCodeLinesForLeafNodes(text);
    constructRestOfNodes(network, nodes, container, options, edges, text);
    setTimeout(function () {
        constructRestOfTree(nodes, text);
    }, delay);
    setTimeout(function() {
        nodes[nodes[nodes.length - 1].getEdges()[0].to].color = "red";
        nodes[nodes[nodes.length - 1].getEdges()[1].to].color = "red";
        network = rebuildNetwork(network, nodes, container, options, edges);
    }, 6000 * (nodes.length - 1));
}

function addFrequencyTable(text) {
    let freqTable = $("#freq-table");
    if (freqTable.length) {
        freqTable.remove();
    }
    const frequenciesSorted = getCharFrequency(text);
    const uniqueCharString = text.split('').filter(function (item, i, ar) {
        return ar.indexOf(item) === i;
    }).join('');
    let letters = "

";
    let frequencies = "
";
    for (let i = 0; i < uniqueCharString.length; i++) {
        letters += "" + uniqueCharString[i] + "	";
        frequencies += "" + frequenciesSorted[uniqueCharString[i]] + "	";
    }
    letters += "
 	";
    frequencies += "
";
    $("#algo-panel").prepend("
" + letters + frequencies + "
");
}

function rebuildNetwork (network, nodes, container, options, edges) {
    let data = {
        nodes: nodes,
        edges: edges
    };
    network.destroy();
    network = new Vis.Network(container, data, options);
    return network;
}

function constructLeafNodes(network, nodes, container, options, edges, text) {
    for (let index = 0; index < text.length; index++) {
        (function (ind) {
            setTimeout(function () {
                nodes[ind].hidden = false;
                network = rebuildNetwork(network, nodes, container, options, edges);
            }, 6000 * ind);
        })(index);
    }
}

function runCodeLinesForLeafNodes(text) {
    for (let index1 = 0; index1 < 6 * text.length; index1++) {
        (function (ind1) {
            setTimeout(function () {
                const tempVal = ind1 % 6;
                if (tempVal == 0) {
                    $("#first-line-5").css('color', '#3f51b5');
                    $("#first-line-0").css('color', 'red');
                }
                else {
                    $("#first-line-" + (tempVal - 1)).css('color', '#3f51b5');
                    $("#first-line-" + (tempVal)).css('color', 'red');
                }
            }, (1000 * ind1));
        })(index1);
    }
}

function constructRestOfTree(nodes, text) {
    $("#first-line-5").css('color', '#3f51b5');
    for (let index1 = 0; index1 < 6 * (nodes.length - text.length); index1++) {
        (function (ind1) {
            setTimeout(function () {
                const tempVal = ind1 % 6;
                if (tempVal == 0) {
                    $("#second-line-5").css('color', '#3f51b5');
                    $("#second-line-0").css('color', 'red');
                }
                else {
                    $("#second-line-" + (tempVal - 1)).css('color', '#3f51b5');
                    $("#second-line-" + (tempVal)).css('color', 'red');
                }
            }, (1000 * ind1));
        })(index1);
    }
}

function constructRestOfNodes(network, nodes,container, options, edges, text) {
    for (let indexRestNodes = text.length; indexRestNodes < nodes.length; indexRestNodes++) {
        (function(indd){
            setTimeout(function() {
                nodes[indd].hidden = false;
                nodes[indd].getEdges()[0].hidden = false;
                nodes[indd].getEdges()[1].hidden = false;
                nodes[indd].color = "red";
                nodes[nodes[indd].getEdges()[0].to].color = "red";
                nodes[nodes[indd].getEdges()[1].to].color = "red";
                if (indd > text.length) {
                    nodes[indd-1].color = "#009688";
                    nodes[nodes[indd-1].getEdges()[0].to].color = "#009688";
                    nodes[nodes[indd-1].getEdges()[1].to].color = "#009688";
                    nodes[indd-1].getEdges()[0].color = "#009688";
                    nodes[indd-1].getEdges()[1].color = "#009688";
                }
                network = rebuildNetwork (network, nodes, container, options, edges);
            }, 6000 * indd);
        })(indexRestNodes);
    }
}

function generateRandomString(len) {
    let text = "";
    const charset = "abcdefghijklmnopqrstuvwxyz";
    for (let i=0; i < len; i++ ) {
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    return text;
}
<commit_msg>solved bug in Huffman<commit_after>const dialog = require('electron').remote.dialog;
const fs = require('fs');

$(document).ready(function () {
    $('#submit-btn').click(function () {
        let text = $('#inputText').val();
        if (text === null || text.length === 0) {
            $("#algo-panel").prepend(createAlert("You have submitted an empty string. Please try again."));
        }
        else {
            constructVisTree(text);
            $("#customAlert").remove();
        }
    });

    $('#random-btn').click(function () {
        let numberOfChars = rangeSlider.noUiSlider.get();
        let randomString = generateRandomString(numberOfChars);
        $('#inputText').val(randomString);
        $('#inputFormGroup').removeClass('is-empty');
        $("#customAlert").remove();
        constructVisTree(randomString);
    });

    $('#upload-btn').bind('click', function () {
        dialog.showOpenDialog(function (fileNames) {
            if (fileNames === undefined) {
                console.log("No file selected");
            }
            else {
                readFile(fileNames[0]);
            }
        });
    });
});

function readFile(filepath) {
    let content;
    fs.readFile(filepath, 'utf-8', function (err, data) {
        if (err) {
            $("#algo-panel").prepend(createAlert("Error while trying to read the file. Please upload another one."));
            return;
        }
        content = data;
        processFile();
    });

    function processFile() {
        if (content === null || content.length === 0) {
            $("#algo-panel").prepend(createAlert("You have submitted an empty string. Please try again."));
        }
        else {
            $("#customAlert").remove();
            constructVisTree(content);
            $('#inputFormGroup').removeClass('is-empty');
            $('#inputText').val(content);
        }
    }
}

function constructVisTree(text) {
    addFrequencyTable(text);
    let huffmanTree = buildHuffmanTree(text);
    let nodes = huffmanTree.nodes;
    let edges = huffmanTree.edges;
    let network;

    // create a network
    const container = $('#tree-simple')[0];

    // provide the data in the vis format
    const data = {
        nodes: nodes,
        edges: edges
    };

    const options = {
        autoResize: true,
        layout: {
            hierarchical: {
                enabled: true,
                parentCentralization: true,
                sortMethod: "directed",
                edgeMinimization: true
            }
        },
        interaction: {
            navigationButtons: true
        },
        physics: {
            enabled: false
        }
    };

    network = new Vis.Network(container, data, options);
    const delay = text.length * 6000;

    constructLeafNodes(network, nodes, container, options, edges, text);
    runCodeLinesForLeafNodes(text);
    constructRestOfNodes(network, nodes, container, options, edges, text);
    setTimeout(function () {
        constructRestOfTree(nodes, text);
    }, delay);
    setTimeout(function() {
        nodes[nodes[nodes.length - 1].getEdges()[0].to].color = "red";
        nodes[nodes[nodes.length - 1].getEdges()[1].to].color = "red";
        network = rebuildNetwork(network, nodes, container, options, edges);
    }, 6000 * (nodes.length - 1));
}

function addFrequencyTable(text) {
    let freqTable = $("#freq-table");
    if (freqTable.length) {
        freqTable.remove();
    }
    const frequenciesSorted = getCharFrequency(text);
    const uniqueCharString = text.split('').filter(function (item, i, ar) {
        return ar.indexOf(item) === i;
    }).join('');
    let letters = "

";
    let frequencies = "
";
    for (let i = 0; i < uniqueCharString.length; i++) {
        letters += "" + uniqueCharString[i] + "	";
        frequencies += "" + frequenciesSorted[uniqueCharString[i]] + "	";
    }
    letters += "
 	";
    frequencies += "
";
    $("#algo-panel").prepend("
" + letters + frequencies + "
");
}

function rebuildNetwork (network, nodes, container, options, edges) {
    let data = {
        nodes: nodes,
        edges: edges
    };
    network.destroy();
    network = new Vis.Network(container, data, options);
    return network;
}

function constructLeafNodes(network, nodes, container, options, edges, text) {
    for (let index = 0; index < text.length; index++) {
        (function (ind) {
            setTimeout(function () {
                nodes[ind].hidden = false;
                network = rebuildNetwork(network, nodes, container, options, edges);
            }, 6000 * ind);
        })(index);
    }
}

function runCodeLinesForLeafNodes(text) {
    for (let index1 = 0; index1 < 6 * text.length; index1++) {
        (function (ind1) {
            setTimeout(function () {
                const tempVal = ind1 % 6;
                if (tempVal === 0) {
                    $("#first-line-5").css('color', '#3f51b5');
                    $("#first-line-0").css('color', 'red');
                }
                else {
                    $("#first-line-" + (tempVal - 1)).css('color', '#3f51b5');
                    $("#first-line-" + (tempVal)).css('color', 'red');
                }
            }, (1000 * ind1));
        })(index1);
    }
}

function constructRestOfTree(nodes, text) {
    $("#first-line-5").css('color', '#3f51b5');
    for (let index1 = 0; index1 < 6 * (nodes.length - text.length); index1++) {
        (function (ind1) {
            setTimeout(function () {
                const tempVal = ind1 % 6;
                if (tempVal === 0) {
                    $("#second-line-5").css('color', '#3f51b5');
                    $("#second-line-0").css('color', 'red');
                }
                else {
                    $("#second-line-" + (tempVal - 1)).css('color', '#3f51b5');
                    $("#second-line-" + (tempVal)).css('color', 'red');
                }
            }, (1000 * ind1));
        })(index1);
    }
}

function constructRestOfNodes(network, nodes,container, options, edges, text) {
    for (let indexRestNodes = text.length; indexRestNodes < nodes.length; indexRestNodes++) {
        (function(indd){
            setTimeout(function() {
                nodes[indd].hidden = false;
                nodes[indd].getEdges()[0].hidden = false;
                nodes[indd].getEdges()[1].hidden = false;
                nodes[indd].color = "red";
                nodes[nodes[indd].getEdges()[0].to].color = "red";
                nodes[nodes[indd].getEdges()[1].to].color = "red";
                if (indd > text.length) {
                    nodes[indd-1].color = "#009688";
                    nodes[nodes[indd-1].getEdges()[0].to].color = "#009688";
                    nodes[nodes[indd-1].getEdges()[1].to].color = "#009688";
                    nodes[indd-1].getEdges()[0].color = "#009688";
                    nodes[indd-1].getEdges()[1].color = "#009688";
                }
                network = rebuildNetwork (network, nodes, container, options, edges);
            }, 6000 * indd);
        })(indexRestNodes);
    }
}

function generateRandomString(len) {
    let text = "";
    const charset = "abcdefghijklmnopqrstuvwxyz";
    for (let i=0; i < len; i++ ) {
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    return text;
}
<|endoftext|>