<commit_before>//
// Copyright (c) Telefonica I+D. All rights reserved.
//
//

exports.C = {
    'STATE_COMPLETED':'completed',
    'STATE_PENDING':'pending',
    'STATE_PROCESSING':'processing',
    'STATE_ERROR':'error',
    'STATE_RETRY_FAIL':'retry_fail',
    'STATE_CALLBACK':'callback_state',
    'STATE_ONERR_CALLBACK': 'on_err_callback_state',
    'STATE_PERSISTENCE':'persistence_state',
    'STATUS_OK':'200',
    'STATUS_ERROR':'404',
    'STATUS_WEIRD':'500',
    'HEAD_RELAYER_HOST':'x-relayer-host',
    'HEAD_RELAYER_RETRY':'x-relayer-retry',
    'HEAD_RELAYER_HTTPCALLBACK':'x-relayer-httpcallback',
    'HEAD_RELAYER_HTTPCALLBACK_ERROR':'x-relayer-httpcallback-error',
    'HEAD_RELAYER_PERSISTENCE' : 'x-relayer-persistence', //STATUS, HEAD, CONTENT
    'HEAD_RELAYER_TOPIC': 'x-relayer-topic',
    'PARAM_DBHOST':'dbhost',
    'PARAM_DBPORT':'dbport',
    'PARAM_SPAWN':'spawn',
    'PARAM_DEBUG':'debug',
    'PARAM_HELP':'help',
    'RD_STATE':'State',
    'RD_HEADER':'Header',
    'RD_STATUSCODE':'StatusCode',
    'RD_DATA':'Data',
    'RD_METHOD':'Method',
    'RD_POSTDATA':'Postdata',
    'RD_RELAYED_REQUEST':'RelayedRequest',
    'EVENT_NEWSTATE': 'newstate',
    'EVENT_ERR' : 'error'
};

<commit_msg>EVENT_ERR renamed<commit_after>//
// Copyright (c) Telefonica I+D. All rights reserved.
//
//

exports.C = {
    'STATE_COMPLETED':'completed',
    'STATE_PENDING':'pending',
    'STATE_PROCESSING':'processing',
    'STATE_ERROR':'error',
    'STATE_RETRY_FAIL':'retry_fail',
    'STATE_CALLBACK':'callback_state',
    'STATE_ONERR_CALLBACK': 'on_err_callback_state',
    'STATE_PERSISTENCE':'persistence_state',
    'STATUS_OK':'200',
    'STATUS_ERROR':'404',
    'STATUS_WEIRD':'500',
    'HEAD_RELAYER_HOST':'x-relayer-host',
    'HEAD_RELAYER_RETRY':'x-relayer-retry',
    'HEAD_RELAYER_HTTPCALLBACK':'x-relayer-httpcallback',
    'HEAD_RELAYER_HTTPCALLBACK_ERROR':'x-relayer-httpcallback-error',
    'HEAD_RELAYER_PERSISTENCE' : 'x-relayer-persistence', //STATUS, HEAD, CONTENT
    'HEAD_RELAYER_TOPIC': 'x-relayer-topic',
    'PARAM_DBHOST':'dbhost',
    'PARAM_DBPORT':'dbport',
    'PARAM_SPAWN':'spawn',
    'PARAM_DEBUG':'debug',
    'PARAM_HELP':'help',
    'RD_STATE':'State',
    'RD_HEADER':'Header',
    'RD_STATUSCODE':'StatusCode',
    'RD_DATA':'Data',
    'RD_METHOD':'Method',
    'RD_POSTDATA':'Postdata',
    'RD_RELAYED_REQUEST':'RelayedRequest',
    'EVENT_NEWSTATE': 'newstate',
    'EVENT_ERR' : 'failure'
};

<|endoftext|>


<commit_before>jQuery(function($) {
  if (typeof BUCKET_URL != 'undefined') {
    var url = BUCKET_URL;
  } else {
    var url = location.protocol + '//' + location.hostname;
  }
  $.get(url)
    .done(function(data) {
      var xml = $(data);
      var files = $.map(xml.find('Contents'), function(item) {
        item = $(item);
        return {
          Key: item.find('Key').text(),
          LastModified: item.find('LastModified').text(),
          Size: item.find('Size').text(),
        }
      });
      renderTable(files);
    })
    .fail(function(error) {
      alert('There was an error');
      console.log(error);
    });
});

function renderTable(files) {
  var cols = [ 45, 30, 15 ];
  var content = padRight('Key', cols[0]) + '  ' + padRight('Last Modified', cols[1]) + '  ' + padRight('Size', cols[2]) + '\n';
  content += new Array(cols[0] + cols[1] + cols[2] + 4).join('-') + '\n';
  $.each(files, function(idx, item) {
    var key = item.Key;
    var row = '' + padRight(item.Key, cols[0]) + '  ';
    row += padRight(item.LastModified, cols[1]) + '  ';
    row += padRight(item.Size, cols[2]);
    content += row + '\n';
  });

  document.getElementById('listing').innerHTML = '
' + content + '
';
}

function padRight(padString, length) {
  var str = padString.slice(0, length-3);
  if (padString.length > str.length) {
    str += '...';
  }
  while (str.length < length) {
    str = str + ' ';
  }
  return str;
}

<commit_msg>[refactor][s]: move key / filename list to far right column so we have unlimited space for file names.<commit_after>jQuery(function($) {
  if (typeof BUCKET_URL != 'undefined') {
    var url = BUCKET_URL;
  } else {
    var url = location.protocol + '//' + location.hostname;
  }
  $.get(url)
    .done(function(data) {
      var xml = $(data);
      var files = $.map(xml.find('Contents'), function(item) {
        item = $(item);
        return {
          Key: item.find('Key').text(),
          LastModified: item.find('LastModified').text(),
          Size: item.find('Size').text(),
        }
      });
      renderTable(files);
    })
    .fail(function(error) {
      alert('There was an error');
      console.log(error);
    });
});

function renderTable(files) {
  var cols = [ 45, 30, 15 ];
  var content = padRight('Last Modified', cols[1]) + '  ' + padRight('Size', cols[2]) + 'Key \n';
  content += new Array(cols[0] + cols[1] + cols[2] + 4).join('-') + '\n';
  $.each(files, function(idx, item) {
    var key = item.Key;
    var row = '';
    row += padRight(item.LastModified, cols[1]) + '  ';
    row += padRight(item.Size, cols[2]);
    row += '' + item.Key + '';
    content += row + '\n';
  });

  document.getElementById('listing').innerHTML = '
' + content + '
';
}

function padRight(padString, length) {
  var str = padString.slice(0, length-3);
  if (padString.length > str.length) {
    str += '...';
  }
  while (str.length < length) {
    str = str + ' ';
  }
  return str;
}

<|endoftext|>


<commit_before>// @flow

import debug from 'debug'
import { highlight, getLanguage } from 'highlight.js'
import React from 'react'
import { Link } from 'react-router'
import { extname } from 'path'

import styles from './FileContent.css'
import btnStyles from '../../styles/btn.css'
import panelStyles from '../../styles/panel.css'

const d = debug('keik:gh:components:repository:file-content')

export default class RepoFileContent extends React.Component<{
  params: {
    branch: string,
    owner: string,
    repo: string,
    splat: string
  },
  content: string,
  contributors: Array<string>,
  size: number
}> {
  static defaultProps = {
    contributors: ['a', 'b', 'c']
  }

  render() {
    d('render')
    const {
      params: { branch, owner, repo, splat: path = '' },
      content,
      size,
      contributors
    } = this.props
    const lines = [].concat(content.match(/\n/g)).length
    const ext = extname(path).substr(1)
    return (

commit tease

            <button>{contributors.length} contributors</button>
            {contributors.map(c => (
              <Link key={c} to={`/${c}`}>

              </Link>
            ))}

            {lines} line | {size} bytes

                <Link
                  className={btnStyles.defaultSmBtn}
                  to={`/${owner}/${repo}/raw/${branch}/${path}`}
                >
                  Raw
                </Link>
                <Link
                  className={btnStyles.defaultSmBtn}
                  to={`/${owner}/${repo}/blame/${branch}/${path}`}
                >
                  Blame
                </Link>
                <Link
                  className={btnStyles.defaultSmBtn}
                  to={`/${owner}/${repo}/commits/${branch}/${path}`}
                >
                  History
                </Link>

              <form>
                <button>

                </button>
              </form>
              <form>
                <button>

                </button>
              </form>

              {(() => {
                const e = []
                for (let i = 0; i < lines; i++) {
                  e.push(
{i + 1}
)
                }
                return e
              })()}

    )
  }
}
<commit_msg>Use styled-components instead of CSS modules<commit_after>// @flow

import debug from 'debug'
import { highlight, getLanguage } from 'highlight.js'
import React from 'react'
import { Link } from 'react-router'
import { extname } from 'path'

import Button from '../common/atoms/Button'
import SegmentedButtonsContainer from '../common/layouts/SegmentedButtonsContainer'
import styles from './FileContent.css'
import panelStyles from '../../styles/panel.css'

const d = debug('keik:gh:components:repository:file-content')

export default class RepoFileContent extends React.Component<{
  params: {
    branch: string,
    owner: string,
    repo: string,
    splat: string
  },
  content: string,
  contributors: Array<string>,
  size: number
}> {
  static defaultProps = {
    contributors: ['a', 'b', 'c']
  }

  render() {
    d('render')
    const {
      params: { branch, owner, repo, splat: path = '' },
      content,
      size,
      contributors
    } = this.props
    const lines = [].concat(content.match(/\n/g)).length
    const ext = extname(path).substr(1)
    return (

commit tease

            <button>{contributors.length} contributors</button>
            {contributors.map(c => (
              <Link key={c} to={`/${c}`}>

              </Link>
            ))}

            {lines} line | {size} bytes

              <SegmentedButtonsContainer>
                <Button
                  as={Link}
                  // $FlowFixMe
                  small="true"
                  to={`/${owner}/${repo}/raw/${branch}/${path}`}
                >
                  Raw
                </Button>
                <Button
                  as={Link}
                  // $FlowFixMe
                  small="true"
                  to={`/${owner}/${repo}/blame/${branch}/${path}`}
                >
                  Blame
                </Button>
                <Button
                  as={Link}
                  // $FlowFixMe
                  small="true"
                  to={`/${owner}/${repo}/commits/${branch}/${path}`}
                >
                  History
                </Button>
              </SegmentedButtonsContainer>
              <form>
                <button>

                </button>
              </form>
              <form>
                <button>

                </button>
              </form>

              {(() => {
                const e = []
                for (let i = 0; i < lines; i++) {
                  e.push(
{i + 1}
)
                }
                return e
              })()}

    )
  }
}
<|endoftext|>


<commit_before>var Visualization = (function() {
	'use strict';

	var _nodes;

	var _links;

	var _s;

	function start(s, nodes, links) {
		_s = s;
		_nodes = nodes;
		_links = links;

		_nodes.forEach(function(node) {
			if ('frequency' === node.type) {
				circle(node);
			} else if ('attribute' === node.type) {
				rect(node);
			}

			draggable(node);
		});

		_links.forEach(function(link) {
			link._ui = _s.line(link.source.x, link.source.y, link.target.x, link.target.y);
			link._ui.attr({
				stroke: '#333'
			});

			link.source._link = link;
			link.target._link = link;
		});
	}

	function rect(node) {
		node._ui = _s.rect(node.x, node.y, 120, 45);
		node._ui.attr({
			'fill': 'deeppink'
		});
	}

	function circle(node) {
		var r = Math.pow(node.intervals[0].percentage, 4) / 30;
		node._ui = _s.circle(node.x, node.y, r);
		node._ui.attr({
			'fill': 'deepskyblue'
		});
	}

	function draggable(node) {
		node._ui.drag(function(dx, dy, x, y) {
			this.attr({
				transform: this.data('transform') + (this.data('transform') ? 'T' : 't') + [dx, dy]
			});

			node.x = x;
			node.y = y;

			if (node._link.source === node) {
				node._link._ui.attr({
					x1: node.x,
					y1: node.y
				});
			} else if (node._link.target === node) {
				node._link._ui.attr({
					x2: node.x,
					y2: node.y
				});
			}

		}, function() {
			this.data('transform', this.transform().local);
		});
	}

	return {
		start: start
	};
})();<commit_msg>Bind links to node center<commit_after>var Visualization = (function() {
	'use strict';

	var _nodes;

	var _links;

	var _s;

	function start(s, nodes, links) {
		_s = s;
		_nodes = nodes;
		_links = links;

		_nodes.forEach(function(node) {
			if ('frequency' === node.type) {
				circle(node);
			} else if ('attribute' === node.type) {
				rect(node);
			}

			draggable(node);
		});

		_links.forEach(function(link) {
			link._ui = _s.line(
				link.source._ui.getBBox().cx,
				link.source._ui.getBBox().cy,
				link.target._ui.getBBox().cx,
				link.target._ui.getBBox().cy
			);

			link._ui.attr({
				stroke: '#333'
			});

			link.source._link = link;
			link.target._link = link;
		});
	}

	function rect(node) {
		node._ui = _s.rect(node.x, node.y, 120, 45);
		node._ui.attr({
			'fill': 'deeppink'
		});
	}

	function circle(node) {
		var r = Math.pow(node.intervals[0].percentage, 4) / 30;
		node._ui = _s.circle(node.x, node.y, r);
		node._ui.attr({
			'fill': 'deepskyblue'
		});
	}

	function draggable(node) {
		node._ui.drag(function(dx, dy, x, y) {
			this.attr({
				transform: this.data('transform') + (this.data('transform') ? 'T' : 't') + [dx, dy]
			});

			node.x = x;
			node.y = y;

			var boundingBox = node._ui.getBBox();

			if (node._link.source === node) {
				node._link._ui.attr({
					x1: boundingBox.cx,
					y1: boundingBox.cy
				});
			} else {
				node._link._ui.attr({
					x2: boundingBox.cx,
					y2: boundingBox.cy
				});
			}

		}, function() {
			this.data('transform', this.transform().local);
		});
	}

	return {
		start: start
	};
})();<|endoftext|>


<commit_before>const React = require('react');
const h = require('react-hyperscript');
const classNames = require('classnames');
const _ = require('lodash');

class InteractionsFilterMenu extends React.Component {
  constructor(props) {
    super(props);
    this.sliderUpdate = _.debounce(this.sliderUpdate,150);
  }

  /**
   *
   * @param {*} degreeValues array returned by getUniqueDegreeValues
   * @description Hides nodes based on their betweenness centrality, determined by on-screen slider
   */
  sliderUpdate(){
    const cy = this.props.cy;

    //get the value from the slider
    let sliderVal = document.getElementById('selection-slider').value;

    //compare to pre-calculated centrality & hide if necessary
    cy.nodes().forEach(node => {
      if(node.data('bcVal') < sliderVal)
        node.addClass('hidden');
      else
        node.removeClass('hidden');
    });
  }

  /**
   *
   * @param {*} nodesToShow Number of nodes that should be visible to user on first load of network
   * @description Hides all nodes based on betweenness centrality, keeping only `nodesToShow` visible.
   * Also sets the default value for the slider, based on this number.
   */
  findDefaultAndUpdate(nodesToShow){
    //setting up variables
    const cy = this.props.cy;
    let i = 0;
    let returnValue = 0;
    let maxVal = 0;

    //sort nodes based on betweenness centrality
    let sortedNodes = cy.nodes().sort(function( a, b ){
      return b.data('bcVal') - a.data('bcVal');
    });

    //get the first nodesToShow nodes
    //also get the node with second-highest bcVal
    sortedNodes.forEach(node => {
      if(i<nodesToShow){
        returnValue =  node.data('bcVal');
        if(i === 1)
          maxVal = node.data('bcVal');
      }
      i++;
    });

    //hide all nodes other than the ones with top `nodesToShow`th bcVal
    cy.nodes().forEach(node => {
      if(node.data('bcVal') < returnValue)
        node.addClass('hidden');
    });

    //return the bcVal of the `nodesToShow`th highest bcVal
    //return the bcVal of the second highest bcVal
    return [returnValue,maxVal];
  }

  render(){
    const props= this.props;

    //Networks end up with all nodes next to 0 bcVal other than search term
    //slider becomes a toggle since noone has the dexterity to distinguish values at the low end
    //instead use the second highest bcVal as the maximum for slider, so its actually useful
    const [defaultSliderVal,maxSliderVal] = this.findDefaultAndUpdate(20);
    const buttons= _.map(props.filters,(active,type)=>
    h('div',{
        key:type,
        className:classNames ('interaction-filter-button', active ? 'interaction-filter-active':'interaction-filter-not-active'),
        onClick: () => props.filterUpdate(type)
      },
      [
        h('div',{className:classNames('interaction-filter-legend',{[type]:active})}),
        h('h3.button-label',type),
      ]
    ));

    //Slider listed under 'Visible Nodes' in the interaction viewer
    const slider = [
      h("input",{type:"range",id:'selection-slider',min:0,max:maxSliderVal,step:0.0001,defaultValue:defaultSliderVal,
      onInput:() => this.sliderUpdate() }),
    ];

    return h('div',[
      h('h2', 'Interaction Filters'),
      buttons,
      h('h2.slider-heading','Visible Nodes'),
      h('div.slider-wrapper',slider),
      h('div.slider-bottom',[
        h('span.most','Most'),
        h('span.least','Least')
      ])
    ]);
  }
}
module.exports = InteractionsFilterMenu; <commit_msg>Slider Kind of woking now<commit_after>const React = require('react');
const h = require('react-hyperscript');
const classNames = require('classnames');
const _ = require('lodash');

class InteractionsFilterMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = _.merge({defaultSliderVal:0,maxSliderVal:0},props);
    this.sliderUpdate = _.debounce(this.sliderUpdate,150);

    this.state.cySrv.loadPromise().then( cy => {
      let defaultResult = this.findDefaultAndUpdate(cy,20);
      this.state.defaultSliderVal = defaultResult[0];
      this.state.maxSliderVal = defaultResult[1];
    });
  }

  /**
   *
   * @param {*} degreeValues array returned by getUniqueDegreeValues
   * @description Hides nodes based on their betweenness centrality, determined by on-screen slider
   */
  sliderUpdate(){
    const cy = this.props.cySrv.get();

    console.log("HERE");

    //get the value from the slider
    let sliderVal = document.getElementById('selection-slider').value;

    //compare to pre-calculated centrality & hide if necessary
    cy.nodes().forEach(node => {
      if(node.data('bcVal') < sliderVal)
        node.addClass('hidden');
      else
        node.removeClass('hidden');
    });
  }

  /**
   *
   * @param {*} nodesToShow Number of nodes that should be visible to user on first load of network
   * @description Hides all nodes based on betweenness centrality, keeping only `nodesToShow` visible.
   * Also sets the default value for the slider, based on this number.
   */
  findDefaultAndUpdate(cy,nodesToShow){

    let i = 0;
    let returnValue = 0;
    let maxVal = 0;

    //sort nodes based on betweenness centrality
    let sortedNodes = cy.nodes().sort(function( a, b ){
      return b.data('bcVal') - a.data('bcVal');
    });

    //get the first nodesToShow nodes
    //also get the node with second-highest bcVal
    sortedNodes.forEach(node => {
      if(i<nodesToShow){
        returnValue =  node.data('bcVal');
        if(i === 1)
          maxVal = node.data('bcVal');
      }
      i++;
    });

    //hide all nodes other than the ones with top `nodesToShow`th bcVal
    cy.nodes().forEach(node => {
      if(node.data('bcVal') < returnValue)
        node.addClass('hidden');
    });

    //return the bcVal of the `nodesToShow`th highest bcVal
    //return the bcVal of the second highest bcVal
    return [returnValue,maxVal];
  }

  render(){
    const props= this.props;

    //Networks end up with all nodes next to 0 bcVal other than search term
    //slider becomes a toggle since noone has the dexterity to distinguish values at the low end
    //instead use the second highest bcVal as the maximum for slider, so its actually useful
    const buttons= _.map(props.filters,(active,type)=>
    h('div',{
        key:type,
        className:classNames ('interaction-filter-button', active ? 'interaction-filter-active':'interaction-filter-not-active'),
        onClick: () => props.filterUpdate(type)
      },
      [
        h('div',{className:classNames('interaction-filter-legend',{[type]:active})}),
        h('h3.button-label',type),
      ]
    ));

    //Slider listed under 'Visible Nodes' in the interaction viewer
    const slider = [
      h("input",{type:"range",id:'selection-slider',min:0,max:1,step:0.0001,defaultValue:0.9,
      onInput:() => this.sliderUpdate() }),
    ];

    return h('div',[
      h('h2', 'Interaction Filters'),
      buttons,
      h('h2.slider-heading','Visible Nodes'),
      h('div.slider-wrapper',slider),
      h('div.slider-bottom',[
        h('span.most','Most'),
        h('span.least','Least')
      ])
    ]);
  }
}
module.exports = InteractionsFilterMenu; <|endoftext|>


<commit_before>/*
    Dial.js
*/

var DialFactory = new function() {
    this.moduleName = 'Dial.js';
    this.selectorAttribute = 'data-dial-js';
    this.next_id = 0;
    this.allDials = {};

    this.makeDial = function(dialName = 'Unnamed Dial', historic = false, selectorAttribute = null) {
        if (selectorAttribute == null)
            ret = new Dial(dialName, historic, this.selectorAttribute);
        else
            ret = new Dial(dialName, historic, selectorAttribute);
        ret.id = this.next_id++;
        this.allDials[ret.id] = ret;
        return ret;
    }
    this.setSelectorAttribute = function(name) {
        this.selectorAttribute = name;
    }
}

var Dial = function(dialName, historic, selectorAttribute) {
    this.moduleName = 'Dial.js';
    this.dialName = dialName;
    this.historic = historic;
    this.selectorAttribute = selectorAttribute;
    this.dial = this;
    this.states = {};
    this.stateHandlers = {};
	this.hashEffectors = {};

    this.trigger = function(data, stateName, historic = this.historic) {
        if(this.historic)
            this.stateHandlers[stateName].callback(data);
        else
            this.states[stateName](data);
    }

    this.addState = function(stateName, fn, hashEffector = null) {
        //actual toggle function
        this.states[stateName] = fn;

		//hashEffector
		this.hashEffectors[stateName] = hashEffector;

        //object that wraps toggle function
        this.stateHandlers[stateName] = {};
        this.stateHandlers[stateName].dial = this.dial;
        this.stateHandlers[stateName].stateName = stateName;
		if(hashEffector != null) {
			this.stateHandlers[stateName].hasHashEffector = true;
		} else {
			this.stateHandlers[stateName].hasHashEffector = false;
		}

        this.stateHandlers[stateName].callback = function(data) {
            //push history object if needed
            if (this.dial.historic) {
                History.pushState({
                    moduleName: this.dial.moduleName,
                    dial: this.dial.dialName,
                    state: stateName,
                    data: data,
                    id: this.dial.id,
					he: this.hasHashEffector
                }, null, 	(this.hasHashEffector)?this.dial.hashEffectors[stateName](
								data, window.location.href.substring(window.location.href.indexOf('?'))):null
							);
            }
            else {
				if(this.hasHashEffector)
					//History.pushState(this.hashEffectors[stateName](data, window.location.hash));
                this.dial.states[stateName](data);
            }
        }
    }

    this.associateElements = function(a_selector, event, state) {
        var obj = {
            dial: this.dial,
            state: state,
            selectorAttribute: this.selectorAttribute
        };
        $(a_selector).each(function(i, elem) {

            $(elem).on(event, obj, function(event) {
                event.preventDefault();
                event.data.dial.stateHandlers[event.data.state].callback($(this).attr(event.data.selectorAttribute));
            });
        });
    }

}

History.Adapter.bind(window, 'statechange', function() {
    try {
        hsdata = History.getState().data;
        if (hsdata.moduleName == DialFactory.moduleName) {

            _dial = DialFactory.allDials[hsdata.id];
			if(hsdata.he) {
				//History.pushState(null,null,_dial.hashEffectors[hsdata.state](hsdata.data, window.location.hash));
			}
            _dial.states[hsdata.state](hsdata.data);

        }
		else if (hsdata.moduleName == 'Dial.js Loading') {
			history.back();
		}
        else {
            //history.go(0); //not a perfect solution
        }
    }
    catch (err) {
        //not our problem
    }
});

History.pushState({
    moduleName: "Dial.js Loading",
    dial: "None",
    state: "Page load",
    data: "No data",
    id: -1
}, null, null);<commit_msg>Fixed history forward bug coming from external pages<commit_after>/*
    Dial.js
*/

var DialFactory = new function() {
    this.moduleName = 'Dial.js';
    this.selectorAttribute = 'data-dial-js';
    this.next_id = 0;
    this.allDials = {};

    this.makeDial = function(dialName = 'Unnamed Dial', historic = false, selectorAttribute = null) {
        if (selectorAttribute == null)
            ret = new Dial(dialName, historic, this.selectorAttribute);
        else
            ret = new Dial(dialName, historic, selectorAttribute);
        ret.id = this.next_id++;
        this.allDials[ret.id] = ret;
        return ret;
    }
    this.setSelectorAttribute = function(name) {
        this.selectorAttribute = name;
    }
}

var Dial = function(dialName, historic, selectorAttribute) {
    this.moduleName = 'Dial.js';
    this.dialName = dialName;
    this.historic = historic;
    this.selectorAttribute = selectorAttribute;
    this.dial = this;
    this.states = {};
    this.stateHandlers = {};
	this.hashEffectors = {};

    this.trigger = function(data, stateName, historic = this.historic) {
        if(this.historic)
            this.stateHandlers[stateName].callback(data);
        else
            this.states[stateName](data);
    }

    this.addState = function(stateName, fn, hashEffector = null) {
        //actual toggle function
        this.states[stateName] = fn;

		//hashEffector
		this.hashEffectors[stateName] = hashEffector;

        //object that wraps toggle function
        this.stateHandlers[stateName] = {};
        this.stateHandlers[stateName].dial = this.dial;
        this.stateHandlers[stateName].stateName = stateName;
		if(hashEffector != null) {
			this.stateHandlers[stateName].hasHashEffector = true;
		} else {
			this.stateHandlers[stateName].hasHashEffector = false;
		}

        this.stateHandlers[stateName].callback = function(data) {
            //push history object if needed
            if (this.dial.historic) {
                History.pushState({
                    moduleName: this.dial.moduleName,
                    dial: this.dial.dialName,
                    state: stateName,
                    data: data,
                    id: this.dial.id,
					he: this.hasHashEffector
                }, null, 	(this.hasHashEffector)?this.dial.hashEffectors[stateName](
								data, window.location.href.substring(window.location.href.indexOf('?'))):null
							);
            }
            else {
				if(this.hasHashEffector)
					//History.pushState(this.hashEffectors[stateName](data, window.location.hash));
                this.dial.states[stateName](data);
            }
        }
    }

    this.associateElements = function(a_selector, event, state) {
        var obj = {
            dial: this.dial,
            state: state,
            selectorAttribute: this.selectorAttribute
        };
        $(a_selector).each(function(i, elem) {

            $(elem).on(event, obj, function(event) {
                event.preventDefault();
                event.data.dial.stateHandlers[event.data.state].callback($(this).attr(event.data.selectorAttribute));
            });
        });
    }

}

var _dial_loaded = false;
History.Adapter.bind(window, 'statechange', function() {
    try {
        hsdata = History.getState().data;
        if (hsdata.moduleName == DialFactory.moduleName) {

            _dial = DialFactory.allDials[hsdata.id];
			if(hsdata.he) {
				//History.pushState(null,null,_dial.hashEffectors[hsdata.state](hsdata.data, window.location.hash));
			}
            _dial.states[hsdata.state](hsdata.data);

        }
		else if(_dial_loaded) {
			history.go(0); //not a perfect solution
			//reloads the page if user backtracks to before the first Dial state
		}
    }
    catch (err) {
        //not our problem
    }
});

History.pushState({
    moduleName: "Dial.js Reload Please",
    dial: "None",
    state: "Page load",
    data: "No data",
    id: -1
}, null, null);

_dial_loaded = true;<|endoftext|>


<commit_before>M.TemplateManager = M.Object.extend({

    "M.View": {
        defaultTemplate: '
<%= _value_ %>
'
    },

    "M.ButtonView": {
        defaultTemplate: '
Button: <div data-binding="_value_"<% if(_value_) {  } %>><%= _value_ %>

',
        topcoat: '<button class="topcoat-button--large" data-binding="_value_"><%= _value_ %></button>',
        bootstrap: '<button type="button" class="btn btn-lg"><%= _value_ %></button>',
        jqm: '<%= _value_ %>'
    },

    "M.ToolbarView": {
        defaultTemplate: '
AAA

<%= _value_ %>

',
        bootstrap: '

<%= _value_ %>

',
        topcoat: '

<%= _value_ %>

',
        jqm: '

<%= _value_ %>

'
    },

    //TODO implement label for=""
    "M.TextfieldView": {
        defaultTemplate: '
<% if(label) {  %><%= label %><% } %><input type="text" value="<%= _value_ %>"><% if(label) {  %><% } %>
',
        bootstrap: '
<% if(label) {  %><%= label %><% } %><input type="text" class="form-control" value="<%= _value_ %>">
',
        topcoat: '<input value="<%= _value_ %>"/>',
        jqm: '<input value="<%= _value_ %>" />'
    },

    "M.ListView": {
        defaultTemplate: '

',
        bootstrap: '

',
        topcoat: '

',
        jqm: '

'
    },

    "M.ListItemView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

<%= _value_ %>

'
    },

    "M.ModelView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<%= _value_ %>
'
    },

    "M.LabelView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<%= _value_ %>
'
    },

    "M.SearchfieldView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<input type="text" data-type="search" name="password" id="search" _value_="" placeholder="<%= placeholder %>" class="ui-input-text ui-body-c"><%= _value_ %>clear text
'
    },

    "M.AccordionView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

'
    },

    "M.AccordionItemView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

'
    },

    "M.SliderView": {
        defaultTemplate: '<input type="range">',
        bootstrap: '<input type="range">',
        topcoat: '<input type="range">',
        jqm: '
<input type="number" data-type="range" name="slider-1" id="slider-1" min="0" max="100" value="50" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset ui-slider-input">

'
    },

    "M.ToggleView": {
        defaultTemplate: '

',
        bootstrap: '

first

second

',
        topcoat: '

',
        jqm: '

'
    },

    "M.LoaderView": {
        defaultTemplate: '

loading

',
        bootstrap: '

loading

',
        topcoat: '

loading

',
        jqm: '

loading

'
    },

    _currentUI: 'jqm',

    get: function( template ) {

        if( this[template] ) {
            //use TMP.TemplateManager._currentUI because this function is called in another this context
            var tpl = this[template][M.TemplateManager._currentUI];
            if( !tpl ) {
                return this[template]['defaultTemplate'];
            } else {
                return tpl;
            }
        }
    }
});<commit_msg>restored M.ImageView template<commit_after>M.TemplateManager = M.Object.extend({

    "M.View": {
        defaultTemplate: '
<%= _value_ %>
'
    },

    "M.ButtonView": {
        defaultTemplate: '
Button: <div data-binding="_value_"<% if(_value_) {  } %>><%= _value_ %>

',
        topcoat: '<button class="topcoat-button--large" data-binding="_value_"><%= _value_ %></button>',
        bootstrap: '<button type="button" class="btn btn-lg"><%= _value_ %></button>',
        jqm: '<%= _value_ %>'
    },

    "M.ToolbarView": {
        defaultTemplate: '
AAA

<%= _value_ %>

',
        bootstrap: '

<%= _value_ %>

',
        topcoat: '

<%= _value_ %>

',
        jqm: '

<%= _value_ %>

'
    },

    //TODO implement label for=""
    "M.TextfieldView": {
        defaultTemplate: '
<% if(label) {  %><%= label %><% } %><input type="text" value="<%= _value_ %>"><% if(label) {  %><% } %>
',
        bootstrap: '
<% if(label) {  %><%= label %><% } %><input type="text" class="form-control" value="<%= _value_ %>">
',
        topcoat: '<input value="<%= _value_ %>"/>',
        jqm: '<input value="<%= _value_ %>" />'
    },

    "M.ListView": {
        defaultTemplate: '

',
        bootstrap: '

',
        topcoat: '

',
        jqm: '

'
    },

    "M.ListItemView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

<%= _value_ %>

'
    },

    "M.ModelView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<%= _value_ %>
'
    },

    "M.LabelView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<%= _value_ %>
'
    },

    "M.SearchfieldView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '
<input type="text" data-type="search" name="password" id="search" _value_="" placeholder="<%= placeholder %>" class="ui-input-text ui-body-c"><%= _value_ %>clear text
'
    },

    "M.AccordionView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

'
    },

    "M.AccordionItemView": {
        defaultTemplate: '
<%= _value_ %>
',
        bootstrap: '
<%= _value_ %>
',
        topcoat: '
<%= _value_ %>
',
        jqm: '

'
    },

    "M.SliderView": {
        defaultTemplate: '<input type="range">',
        bootstrap: '<input type="range">',
        topcoat: '<input type="range">',
        jqm: '
<input type="number" data-type="range" name="slider-1" id="slider-1" min="0" max="100" value="50" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset ui-slider-input">

'
    },

    "M.ToggleView": {
        defaultTemplate: '

',
        bootstrap: '

first

second

',
        topcoat: '

',
        jqm: '

'
    },

    "M.ImageView": {
        defaultTemplate: '<img src="<%= _value_ %>" alt="<%= alt %>" />',
        bootstrap: '<img src="<%= _value_ %>" alt="<%= alt %>" />',
        topcoat: '<img src="<%= _value_ %>" alt="<%= alt %>" />',
        jqm: '<img src="<%= _value_ %>" alt="<%= alt %>" />'
    },

    "M.LoaderView": {
        defaultTemplate: '

loading

',
        bootstrap: '

loading

',
        topcoat: '

loading

',
        jqm: '

loading

'
    },

    _currentUI: 'jqm',

    get: function( template ) {

        if( this[template] ) {
            //use TMP.TemplateManager._currentUI because this function is called in another this context
            var tpl = this[template][M.TemplateManager._currentUI];
            if( !tpl ) {
                return this[template]['defaultTemplate'];
            } else {
                return tpl;
            }
        }
    }
});<|endoftext|>


<commit_before>var start_time = new Date().getTime();

$('a.vote').each(function(){
  $(this).attr('start_time', start_time);
});

$('a.vote').find('i').on({
  mouseenter: function(){
    var star = $(this).parent().attr('id').replace('star','');
    highlight_stars(star);
  },
  mouseleave: function(){
    unhighlight_stars();
  }
});

/**
 * Highlight all the stars up to a certain one
 */
function highlight_stars(amount)
{
  unhighlight_stars();

  if(!isNaN(amount)) {
    for(i = 1; i <= amount; i++) {
      $('#star'+i).children().addClass('fa-star');
      $('#star'+i).children().removeClass('fa-star-o');
    }
  }
}

/**
 * Makes all voting stars on the page become unhighlighted
 */
function unhighlight_stars()
{
  $('a.vote').find('i').addClass('fa-star-o');
  $('a.vote').find('i').removeClass('fa-star');
}

function insert_time(anchor, time)
{
  anchor = $(anchor);

  var start_time = anchor.attr('start_time');
  var end_time = new Date().getTime();
  var deliberation_time = end_time - start_time;

  var new_href = anchor.attr('href') + '&delib_time=' + deliberation_time;

  anchor.attr('href', new_href);
}
<commit_msg>add click event for touch interaction<commit_after>var start_time = new Date().getTime();

$('a.vote').each(function(){
  $(this).attr('start_time', start_time);
});

$('a.vote').find('i').on({
  mouseenter: function(){
    var star = $(this).parent().attr('id').replace('star','');
    highlight_stars(star);
  },
  click: function(){
    var star = $(this).parent().attr('id').replace('star','');
    highlight_stars(star);
  },
  mouseleave: function(){
    unhighlight_stars();
  }
});

/**
 * Highlight all the stars up to a certain one
 */
function highlight_stars(amount)
{
  unhighlight_stars();

  if(!isNaN(amount)) {
    for(i = 1; i <= amount; i++) {
      $('#star'+i).children().addClass('fa-star');
      $('#star'+i).children().removeClass('fa-star-o');
    }
  }
}

/**
 * Makes all voting stars on the page become unhighlighted
 */
function unhighlight_stars()
{
  $('a.vote').find('i').addClass('fa-star-o');
  $('a.vote').find('i').removeClass('fa-star');
}

function insert_time(anchor, time)
{
  anchor = $(anchor);

  var start_time = anchor.attr('start_time');
  var end_time = new Date().getTime();
  var deliberation_time = end_time - start_time;

  var new_href = anchor.attr('href') + '&delib_time=' + deliberation_time;

  anchor.attr('href', new_href);
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  v<|endoftext|>


<commit_before>/* eslint-disable no-var */
var rimraf = require('rimraf');
var chalk = require('chalk');
var replace = require("replace");
var prompt = require("prompt");
var prompts = require('./setupPrompts');

var chalkSuccess = chalk.green;
var chalkProcessing = chalk.blue;
var chalkWarn = chalk.red;

/* eslint-disable no-console */

console.log(chalkSuccess('Dependencies installed.'));

prompt.start();

console.log(chalkWarn("WARNING:  Preparing to delete local git repository..."));
prompt.get([{name: 'deleteGit', description: "Delete the git repository?  YES to continue or NO to skip."}], function(err, result) {
  var deleteGit;

  if (err) {
    process.exit(1);
  }

  deleteGit = result.deleteGit.toUpperCase();
  if (deleteGit === 'Y' || deleteGit === "YES") {
    // remove the original git repository
    rimraf('.git', error => {
      if (error) throw new Error(error);
      console.log(chalkSuccess('Original Git repository removed.\n'));

      console.log(chalkProcessing('Updating package.json settings:'));

      prompt.get(prompts, function(err, result) {
        // parse user responses
        // default values provided for fields that will cause npm to complain if left empty
        const responses = [
          {
            key: 'name',
            value: result.projectName || 'new-project'
          },
          {
            key: 'version',
            value: result.version || '0.1.0'
          },
          {
            key: 'author',
            value: result.author
          },
          {
            key: 'license',
            value: result.license || 'MIT'
          },
          {
            key: 'description',
            value: result.description
          },
          // simply use an empty URL here to clear the existing repo URL
          {
            key: 'url',
            value: ''
          }
        ];

        // update package.json with the user's values
        responses.forEach(res => {
          replace({
            regex: `("${res.key}"): "(.*?)"`,
            replacement: `$1: "${res.value}"`,
            paths: ['package.json'],
            recursive: false,
            silent: true
          });
        });

        // reset package.json 'keywords' field to empty state
        replace({
          regex: /"keywords": \[[\s\S]+?\]/,
          replacement: `"keywords": []`,
          paths: ['package.json'],
          recursive: false,
          silent: true
        });

        // remove all setup scripts from the 'tools' folder
        console.log(chalkSuccess('\nSetup complete! Cleaning up...\n'));
        rimraf('./tools/setup', error => {
          if (error) throw new Error(error);
        });
      });
    });
  }
});
<commit_msg>update setup script (#416)<commit_after>/* eslint-disable no-var */
var rimraf = require('rimraf');
var chalk = require('chalk');
var replace = require("replace");
var prompt = require("prompt");
var prompts = require('./setupPrompts');

var chalkSuccess = chalk.green;
var chalkProcessing = chalk.blue;
var chalkWarn = chalk.red;

/* eslint-disable no-console */

console.log(chalkSuccess('Dependencies installed.'));

prompt.start();

console.log(chalkWarn("WARNING:  Preparing to delete local git repository..."));
prompt.get([{name: 'deleteGit', description: "Delete the git repository?  [Y/n]"}], function(err, result) {
  var deleteGit = result.deleteGit.toUpperCase();

  if (err) {
    process.exit(1);
  }

  function updatePackage() {
    console.log(chalkProcessing('Updating package.json settings:'));

    prompt.get(prompts, function(err, result) {
      // parse user responses
      // default values provided for fields that will cause npm to complain if left empty
      const responses = [
        {
          key: 'name',
          value: result.projectName || 'new-project'
        },
        {
          key: 'version',
          value: result.version || '0.1.0'
        },
        {
          key: 'author',
          value: result.author
        },
        {
          key: 'license',
          value: result.license || 'MIT'
        },
        {
          key: 'description',
          value: result.description
        },
        // simply use an empty URL here to clear the existing repo URL
        {
          key: 'url',
          value: ''
        }
      ];

      // update package.json with the user's values
      responses.forEach(res => {
        replace({
          regex: `("${res.key}"): "(.*?)"`,
          replacement: `$1: "${res.value}"`,
          paths: ['package.json'],
          recursive: false,
          silent: true
        });
      });

      // reset package.json 'keywords' field to empty state
      replace({
        regex: /"keywords": \[[\s\S]+?\]/,
        replacement: `"keywords": []`,
        paths: ['package.json'],
        recursive: false,
        silent: true
      });

      // remove setup script from package.json
      replace({
        regex: /\s*"setup":.*,/,
        replacement: "",
        paths: ['package.json'],
        recursive: false,
        silent: true
      });

      // remove all setup scripts from the 'tools' folder
      console.log(chalkSuccess('\nSetup complete! Cleaning up...\n'));
      rimraf('./tools/setup', error => {
        if (error) throw new Error(error);
      });
    });

  }

  if (deleteGit.match(/^N.*/)) {
    updatePackage();
  }
  else {
    // remove the original git repository
    rimraf('.git', error => {
      if (error) throw new Error(error);
      console.log(chalkSuccess('Original Git repository removed.\n'));
      updatePackage();
    });
  }
});
<|endoftext|>


<commit_before>M.wrap('github/jillix/bind-filter/dev/list.js', function (require, module, exports) {
// TODO use bind for dom interaction/manipulation
function get(s,c){
    try{return (c||document).querySelector(s);}
    catch (err) {}
}

var getFieldLabel = require('./validate').getFieldLabel;

function createFilterItem (hash) {
    var self = this;
    var item = self.domRefs.listItem.cloneNode(true);
    var checkbox = get(self.config.ui.item.onoff, item);
    var field = get(self.config.ui.item.field, item);
    var operator = get(self.config.ui.item.operator, item);
    var value = get(self.config.ui.item.value, item);
    var edit = get(self.config.ui.item.edit, item);
    var rm = get(self.config.ui.item.remove, item);

    // enable/disable filter
    if (self.filters[hash].disabled) {
        item.setAttribute('class', 'disabled');
        checkbox.removeAttribute('checked');
    }

    // hide filter item
    if (self.filters[hash].hidden) {
        item.style.display = 'none';
    }

    // set content
    if (field) {
        field.innerHTML = getFieldLabel.call(self, self.filters[hash].field);
    }
    if (operator) {
        operator.innerHTML = self.filters[hash].operator;
    }
    if (value) {
        value.innerHTML = self.filters[hash].value === undefined ? '' : self.filters[hash].value;
    }

    // hide edit if it's a core field
    if (edit && self.filters[hash].field[0] === '_') {
        edit.style.display = 'none';
    }

    if (!self.filters[hash].fixed) {

        if (checkbox) {
            checkbox.addEventListener('change', function (event) {
                if (checkbox.checked) {
                    self.emit('enableFilter', hash);
                } else {
                    self.emit('disableFilter', hash);
                }
            }, false);
        }

        // edit filter
        if (edit) {
            edit.addEventListener(self.config.ui.events.itemEdit || 'click', function () {
                self.emit('editFilter', hash);
            }, false);
            delete edit.style.display;
        }

        // remove filter
        if (rm) {
            rm.addEventListener(self.config.ui.events.itemRemove || 'click', function () {
                self.emit('removeFilter', hash);
            }, false);
        }
    } else {
        // TODO handle attributes with bind
        item.setAttribute('class', 'fixed' + (self.filters[hash].disabled ? ' disabled' : ''));
        if (checkbox) {
            checkbox.setAttribute('disabled', true);
        }
        if (edit) {
            edit.style.display = 'none';
        }
    }

    return item;
}

function save (hash) {
    var self = this;

    // create filter item
    var item = createFilterItem.call(self, hash);
    if (self.filters[hash].item) {
        // replace filter
        self.domRefs.list.replaceChild(item, self.filters[hash].item);
        //self.domRefs.list.appendChild(item);
    } else {
        // add new filter
        if (self.domRefs.list) {
            self.domRefs.list.appendChild(item);
        }
    }

    // update cache
    self.filters[hash].item = item;
}

function remove (hash) {
    var self = this;

    if (self.filters[hash]) {
        // remove dom element
        self.domRefs.list.removeChild(self.filters[hash].item);

        // remove from cache
        delete self.filters[hash];
    }
}

exports.save = save;
exports.remove = remove;

return module; });
<commit_msg>added stop propagation and prevent default to edit and remove buttons<commit_after>M.wrap('github/jillix/bind-filter/dev/list.js', function (require, module, exports) {
// TODO use bind for dom interaction/manipulation
function get(s,c){
    try{return (c||document).querySelector(s);}
    catch (err) {}
}

var getFieldLabel = require('./validate').getFieldLabel;

function createFilterItem (hash) {
    var self = this;
    var item = self.domRefs.listItem.cloneNode(true);
    var checkbox = get(self.config.ui.item.onoff, item);
    var field = get(self.config.ui.item.field, item);
    var operator = get(self.config.ui.item.operator, item);
    var value = get(self.config.ui.item.value, item);
    var edit = get(self.config.ui.item.edit, item);
    var rm = get(self.config.ui.item.remove, item);

    // enable/disable filter
    if (self.filters[hash].disabled) {
        item.setAttribute('class', 'disabled');
        checkbox.removeAttribute('checked');
    }

    // hide filter item
    if (self.filters[hash].hidden) {
        item.style.display = 'none';
    }

    // set content
    if (field) {
        field.innerHTML = getFieldLabel.call(self, self.filters[hash].field);
    }
    if (operator) {
        operator.innerHTML = self.filters[hash].operator;
    }
    if (value) {
        value.innerHTML = self.filters[hash].value === undefined ? '' : self.filters[hash].value;
    }

    // hide edit if it's a core field
    if (edit && self.filters[hash].field[0] === '_') {
        edit.style.display = 'none';
    }

    if (!self.filters[hash].fixed) {

        if (checkbox) {
            checkbox.addEventListener('change', function (event) {
                if (checkbox.checked) {
                    self.emit('enableFilter', hash);
                } else {
                    self.emit('disableFilter', hash);
                }
            }, false);
        }

        // edit filter
        if (edit) {
            edit.addEventListener(self.config.ui.events.itemEdit || 'click', function (event) {
                event.stopPropagation();
                event.preventDefault();
                self.emit('editFilter', hash);
            }, false);
            delete edit.style.display;
        }

        // remove filter
        if (rm) {
            rm.addEventListener(self.config.ui.events.itemRemove || 'click', function (event) {
                event.stopPropagation();
                event.preventDefault();
                self.emit('removeFilter', hash);
            }, false);
        }
    } else {
        // TODO handle attributes with bind
        item.setAttribute('class', 'fixed' + (self.filters[hash].disabled ? ' disabled' : ''));
        if (checkbox) {
            checkbox.setAttribute('disabled', true);
        }
        if (edit) {
            edit.style.display = 'none';
        }
    }

    return item;
}

function save (hash) {
    var self = this;

    // create filter item
    var item = createFilterItem.call(self, hash);
    if (self.filters[hash].item) {
        // replace filter
        self.domRefs.list.replaceChild(item, self.filters[hash].item);
        //self.domRefs.list.appendChild(item);
    } else {
        // add new filter
        if (self.domRefs.list) {
            self.domRefs.list.appendChild(item);
        }
    }

    // update cache
    self.filters[hash].item = item;
}

function remove (hash) {
    var self = this;

    if (self.filters[hash]) {
        // remove dom element
        self.domRefs.list.removeChild(self.filters[hash].item);

        // remove from cache
        delete self.filters[hash];
    }
}

exports.save = save;
exports.remove = remove;

return module; });
<|endoftext|>


<commit_before>import { createTranslator } from 'kolibri.utils.i18n';

const coachStrings = createTranslator('CommonCoachStrings', {
  // actions
  copyAction: 'Copy',
  editDetailsAction: 'Edit details',
  finishAction: 'Finish',
  goBackAction: 'Go back',
  manageResourcesAction: 'Manage resources',
  newLessonAction: 'New lesson',
  newQuizAction: 'New quiz',
  previewAction: 'Preview',
  saveAction: 'Save',
  saveChangesAction: 'Save changes',
  renameAction: 'Rename',
  showAction: 'Show',
  showMoreAction: 'Show more',
  sortedAscendingAction: 'Sort in ascending order',
  sortedDescendingAction: 'Sort in descending order',
  viewAllAction: 'View all',

  // labels, phrases, titles, headers...
  activeQuizzesLabel: 'Active quizzes',
  activityLabel: 'Activity',
  allQuizzesLabel: 'All quizzes',
  avgScoreLabel: 'Average score',
  avgTimeSpentLabel: 'Average time spent',
  avgQuizScoreLabel: 'Average quiz score',
  descriptionLabel: 'Description',
  descriptionMissingLabel: 'No description',
  detailsLabel: 'Details',
  difficultQuestionsLabel: 'Difficult questions',
  entireClassLabel: 'Entire class',
  exercisesCompletedLabel: 'Exercises completed',
  groupNameLabel: 'Group name',
  groupsLabel: 'Groups',
  helpNeededLabel: 'Help needed',
  inactiveQuizzesLabel: 'Inactive quizzes',
  lastActivityLabel: 'Last activity',
  lessonActiveLabel: 'Active',
  inactiveLabel: 'Inactive',
  lessonsLabel: 'Lessons',
  lessonsAssignedLabel: 'Lessons assigned',
  masteryModelLabel: 'Completion requirement',
  membersLabel: 'Members',
  nameLabel: 'Name',
  orderFixedLabel: 'Fixed',
  orderFixedDescription: 'Each learner sees the same question order',
  orderRandomLabel: 'Randomized',
  orderRandomDescription: 'Each learner sees a different question order',
  overallLabel: 'Overall',
  previewLabel: 'Preview',
  questionLabel: 'Question',
  questionOrderLabel: 'Question order',
  quizLabel: 'Quiz',
  quizActiveLabel: 'Active',
  quizScoreLabel: 'Quiz score',
  quizzesLabel: 'Quizzes',
  quizzesAssignedLabel: 'Quizzes assigned',
  quizzesCompletedLabel: 'Quizzes completed',
  recipientLabel: 'Recipient',
  recipientsLabel: 'Recipients',
  reportLabel: 'Report',
  reportsLabel: 'Reports',
  resourceTitleLabel: 'Resource title',
  resourcesViewedLabel: 'Resources viewed',
  scoreLabel: 'Score',
  sortedAscendingLabel: '(sorted ascending)',
  sortedDescendingLabel: '(sorted descending)',
  startedLabel: 'Started',
  statusLabel: 'Status',
  titleLabel: 'Title',
  timeLabel: 'Time',
  timeSpentLabel: 'Time spent',
  ungroupedLearnersLabel: 'Ungrouped learners',
  usernameLabel: 'Username',
  viewsLabel: 'Views',

  // notifications
  updatedNotification: 'Updated',
  createdNotification: 'Created',
  deletedNotification: 'Deleted',
  savedNotification: 'Saved',

  // empty states
  activityListEmptyState: 'There is no activity',
  groupListEmptyState: 'There are no groups',
  learnerListEmptyState: 'There are no learners',
  lessonListEmptyState: 'There are no lessons',
  recentActivityListEmptyState: 'There is no recent activity',
  questionListEmptyState: 'There are no questions',
  quizListEmptyState: 'There are no quizzes',

  // toggles
  showCorrectAnswerLabel: 'Show correct answer',
  viewByGroupsLabel: 'View by groups',

  // formatted values
  integer: '{value, number, integer}',
  nthExerciseName: '{name} ({number, number, integer})',
  number: '{value, number}',
  numberOfClasses: '{value, number, integer} {value, plural, one {class} other {classes}}',
  numberOfCoaches: '{value, number, integer} {value, plural, one {coach} other {coaches}}',
  numberOfGroups: '{value, number, integer} {value, plural, one {group} other {groups}}',
  numberOfLearners: '{value, number, integer} {value, plural, one {learner} other {learners}}',
  numberOfQuestions: '{value, number, integer} {value, plural, one {question} other {questions}}',
  numberOfResources: '{value, number, integer} {value, plural, one {resource} other {resources}}',
  numberOfViews: '{value, number, integer} {value, plural, one {view} other {views}}',
  percentage: '{value, number, percent}',
  ratio: '{value, number, integer} out of {total, number, integer}',
  ratioShort: '{value, number, integer} of {total, number, integer}',

  // Errors
  quizDuplicateTitleError: 'A quiz with that name already exists',
  lessonDuplicateTitleError: 'A lesson with this name already exists',
});

const coachStringsMixin = {
  methods: {
    coachCommon$tr(key, args) {
      return coachStrings.$tr(key, args);
    },
  },
};

export { coachStrings, coachStringsMixin };
<commit_msg>Remove unused strings<commit_after>import { createTranslator } from 'kolibri.utils.i18n';

const coachStrings = createTranslator('CommonCoachStrings', {
  // actions
  copyAction: 'Copy',
  editDetailsAction: 'Edit details',
  finishAction: 'Finish',
  goBackAction: 'Go back',
  manageResourcesAction: 'Manage resources',
  newLessonAction: 'New lesson',
  newQuizAction: 'New quiz',
  previewAction: 'Preview',
  saveAction: 'Save',
  saveChangesAction: 'Save changes',
  renameAction: 'Rename',
  showAction: 'Show',
  showMoreAction: 'Show more',
  sortedAscendingAction: 'Sort in ascending order',
  sortedDescendingAction: 'Sort in descending order',
  viewAllAction: 'View all',

  // labels, phrases, titles, headers...
  activeQuizzesLabel: 'Active quizzes',
  activityLabel: 'Activity',
  allQuizzesLabel: 'All quizzes',
  avgScoreLabel: 'Average score',
  avgTimeSpentLabel: 'Average time spent',
  avgQuizScoreLabel: 'Average quiz score',
  descriptionLabel: 'Description',
  descriptionMissingLabel: 'No description',
  detailsLabel: 'Details',
  difficultQuestionsLabel: 'Difficult questions',
  entireClassLabel: 'Entire class',
  exercisesCompletedLabel: 'Exercises completed',
  groupNameLabel: 'Group name',
  groupsLabel: 'Groups',
  helpNeededLabel: 'Help needed',
  inactiveQuizzesLabel: 'Inactive quizzes',
  lastActivityLabel: 'Last activity',
  lessonActiveLabel: 'Active',
  inactiveLabel: 'Inactive',
  lessonsLabel: 'Lessons',
  lessonsAssignedLabel: 'Lessons assigned',
  masteryModelLabel: 'Completion requirement',
  membersLabel: 'Members',
  nameLabel: 'Name',
  orderFixedLabel: 'Fixed',
  orderFixedDescription: 'Each learner sees the same question order',
  orderRandomLabel: 'Randomized',
  orderRandomDescription: 'Each learner sees a different question order',
  overallLabel: 'Overall',
  previewLabel: 'Preview',
  questionLabel: 'Question',
  questionOrderLabel: 'Question order',
  quizActiveLabel: 'Active',
  quizzesLabel: 'Quizzes',
  quizzesAssignedLabel: 'Quizzes assigned',
  recipientsLabel: 'Recipients',
  reportLabel: 'Report',
  reportsLabel: 'Reports',
  resourcesViewedLabel: 'Resources viewed',
  scoreLabel: 'Score',
  sortedAscendingLabel: '(sorted ascending)',
  sortedDescendingLabel: '(sorted descending)',
  startedLabel: 'Started',
  statusLabel: 'Status',
  titleLabel: 'Title',
  timeLabel: 'Time',
  timeSpentLabel: 'Time spent',
  ungroupedLearnersLabel: 'Ungrouped learners',
  usernameLabel: 'Username',
  viewsLabel: 'Views',

  // notifications
  updatedNotification: 'Updated',
  createdNotification: 'Created',
  deletedNotification: 'Deleted',
  savedNotification: 'Saved',

  // empty states
  activityListEmptyState: 'There is no activity',
  groupListEmptyState: 'There are no groups',
  learnerListEmptyState: 'There are no learners',
  lessonListEmptyState: 'There are no lessons',
  questionListEmptyState: 'There are no questions',
  quizListEmptyState: 'There are no quizzes',

  // toggles
  showCorrectAnswerLabel: 'Show correct answer',
  viewByGroupsLabel: 'View by groups',

  // formatted values
  integer: '{value, number, integer}',
  nthExerciseName: '{name} ({number, number, integer})',
  number: '{value, number}',
  numberOfClasses: '{value, number, integer} {value, plural, one {class} other {classes}}',
  numberOfCoaches: '{value, number, integer} {value, plural, one {coach} other {coaches}}',
  numberOfGroups: '{value, number, integer} {value, plural, one {group} other {groups}}',
  numberOfLearners: '{value, number, integer} {value, plural, one {learner} other {learners}}',
  numberOfQuestions: '{value, number, integer} {value, plural, one {question} other {questions}}',
  numberOfResources: '{value, number, integer} {value, plural, one {resource} other {resources}}',
  numberOfViews: '{value, number, integer} {value, plural, one {view} other {views}}',
  percentage: '{value, number, percent}',
  ratio: '{value, number, integer} out of {total, number, integer}',
  ratioShort: '{value, number, integer} of {total, number, integer}',

  // Errors
  quizDuplicateTitleError: 'A quiz with that name already exists',
  lessonDuplicateTitleError: 'A lesson with this name already exists',
});

const coachStringsMixin = {
  methods: {
    coachCommon$tr(key, args) {
      return coachStrings.$tr(key, args);
    },
  },
};

export { coachStrings, coachStringsMixin };
<|endoftext|>


<commit_before>let path = require('path');
let Entry = require('./Entry');
let { Chunks } = require('../Chunks');
let webpackRules = require('./webpack-rules');
let webpackPlugins = require('./webpack-plugins');
let webpackDefaultConfig = require('./webpack-default');

process.noDeprecation = true;

class WebpackConfig {
    /**
     * Create a new instance.
     */
    constructor() {
        this.webpackConfig = webpackDefaultConfig();
        this.chunks = Chunks.instance();
    }

    /**
     * Build the Webpack configuration object.
     */
    build() {
        this.buildEntry()
            .buildOutput()
            .buildRules()
            .buildPlugins()
            .buildChunks()
            .mergeCustomConfig();

        // We'll announce that the core config object has been
        // generated by Mix. At this point, any plugins may
        // hook in and modify the config as necessary.
        Mix.dispatch('configReady', this.webpackConfig);

        // Rebuild the chunks as plugins may have added new ones
        this.buildChunks();

        // Finally, we'll make one last announcement for the user
        // to hook into - using mix.override().
        Mix.dispatch('configReadyForUser', this.webpackConfig);

        // Rebuild the chunks as the user may have changed things
        this.buildChunks();

        return this.webpackConfig;
    }

    /**
     * Build the entry object.
     */
    buildEntry() {
        let entry = new Entry();

        if (!Mix.bundlingJavaScript) {
            entry.addDefault();
        }

        Mix.dispatch('loading-entry', entry);

        this.webpackConfig.entry = entry.get();

        return this;
    }

    /**
     * Build the output object.
     */
    buildOutput() {
        let http = process.argv.includes('--https') ? 'https' : 'http';

        if (Mix.isUsing('hmr')) {
            this.webpackConfig.devServer.host = Config.hmrOptions.host;
            this.webpackConfig.devServer.port = Config.hmrOptions.port;
        }

        this.webpackConfig.output = {
            path: Mix.isUsing('hmr') ? '/' : path.resolve(Config.publicPath),
            filename: '[name].js',

            chunkFilename: pathData => {
                let hasAbsolutePathChunkName =
                    pathData.chunk.name && pathData.chunk.name.startsWith('/');

                if (Mix.components.get('js') && !hasAbsolutePathChunkName) {
                    let output = Mix.components.get('js').toCompile[0].output;

                    return `${output.filePath}/[name].js`;
                }

                return '[name].js';
            },

            publicPath: Mix.isUsing('hmr')
                ? `${http}://${Config.hmrOptions.host}:${
                      Config.hmrOptions.port
                  }/`
                : '/'
        };

        return this;
    }

    /**
     * Build the rules array.
     */
    buildRules() {
        this.webpackConfig.module.rules = this.webpackConfig.module.rules.concat(
            webpackRules()
        );

        Mix.dispatch('loading-rules', this.webpackConfig.module.rules);

        return this;
    }

    /**
     * Build the plugins array.
     */
    buildPlugins() {
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(
            webpackPlugins()
        );

        Mix.dispatch('loading-plugins', this.webpackConfig.plugins);

        return this;
    }

    /**
     * Build the resolve object.
     */
    buildChunks() {
        this.webpackConfig = require('./MergeWebpackConfig')(
            this.webpackConfig,
            this.chunks.config()
        );

        return this;
    }

    /**
     * Merge the user's custom Webpack configuration.
     */
    mergeCustomConfig() {
        if (Config.webpackConfig) {
            this.webpackConfig = require('./MergeWebpackConfig')(
                this.webpackConfig,
                Config.webpackConfig
            );
        }
    }
}

module.exports = WebpackConfig;
<commit_msg>Don't immediately build default webpack config<commit_after>let path = require('path');
let Entry = require('./Entry');
let { Chunks } = require('../Chunks');
let webpackRules = require('./webpack-rules');
let webpackPlugins = require('./webpack-plugins');
let webpackDefaultConfig = require('./webpack-default');

process.noDeprecation = true;

class WebpackConfig {
    /**
     * Create a new instance.
     */
    constructor() {
        this.chunks = Chunks.instance();
    }

    /**
     * Build the Webpack configuration object.
     */
    build() {
        this.webpackConfig = webpackDefaultConfig();

        this.buildEntry()
            .buildOutput()
            .buildRules()
            .buildPlugins()
            .buildChunks()
            .mergeCustomConfig();

        // We'll announce that the core config object has been
        // generated by Mix. At this point, any plugins may
        // hook in and modify the config as necessary.
        Mix.dispatch('configReady', this.webpackConfig);

        // Rebuild the chunks as plugins may have added new ones
        this.buildChunks();

        // Finally, we'll make one last announcement for the user
        // to hook into - using mix.override().
        Mix.dispatch('configReadyForUser', this.webpackConfig);

        // Rebuild the chunks as the user may have changed things
        this.buildChunks();

        return this.webpackConfig;
    }

    /**
     * Build the entry object.
     */
    buildEntry() {
        let entry = new Entry();

        if (!Mix.bundlingJavaScript) {
            entry.addDefault();
        }

        Mix.dispatch('loading-entry', entry);

        this.webpackConfig.entry = entry.get();

        return this;
    }

    /**
     * Build the output object.
     */
    buildOutput() {
        let http = process.argv.includes('--https') ? 'https' : 'http';

        if (Mix.isUsing('hmr')) {
            this.webpackConfig.devServer.host = Config.hmrOptions.host;
            this.webpackConfig.devServer.port = Config.hmrOptions.port;
        }

        this.webpackConfig.output = {
            path: Mix.isUsing('hmr') ? '/' : path.resolve(Config.publicPath),
            filename: '[name].js',

            chunkFilename: pathData => {
                let hasAbsolutePathChunkName =
                    pathData.chunk.name && pathData.chunk.name.startsWith('/');

                if (Mix.components.get('js') && !hasAbsolutePathChunkName) {
                    let output = Mix.components.get('js').toCompile[0].output;

                    return `${output.filePath}/[name].js`;
                }

                return '[name].js';
            },

            publicPath: Mix.isUsing('hmr')
                ? `${http}://${Config.hmrOptions.host}:${
                      Config.hmrOptions.port
                  }/`
                : '/'
        };

        return this;
    }

    /**
     * Build the rules array.
     */
    buildRules() {
        this.webpackConfig.module.rules = this.webpackConfig.module.rules.concat(
            webpackRules()
        );

        Mix.dispatch('loading-rules', this.webpackConfig.module.rules);

        return this;
    }

    /**
     * Build the plugins array.
     */
    buildPlugins() {
        this.webpackConfig.plugins = this.webpackConfig.plugins.concat(
            webpackPlugins()
        );

        Mix.dispatch('loading-plugins', this.webpackConfig.plugins);

        return this;
    }

    /**
     * Build the resolve object.
     */
    buildChunks() {
        this.webpackConfig = require('./MergeWebpackConfig')(
            this.webpackConfig,
            this.chunks.config()
        );

        return this;
    }

    /**
     * Merge the user's custom Webpack configuration.
     */
    mergeCustomConfig() {
        if (Config.webpackConfig) {
            this.webpackConfig = require('./MergeWebpackConfig')(
                this.webpackConfig,
                Config.webpackConfig
            );
        }
    }
}

module.exports = WebpackConfig;
<|endoftext|>


<commit_before>if (process.env.NODE_ENV !== 'production') {
    const cb = window.webpackHotUpdate;

    window.webpackHotUpdate = (...args) => {
        const links = document.querySelectorAll('link[rel=stylesheet]');

        for (let link of links) {
            let { href } = link;
            link.href = 'about:blank';
            link.href = href;
        }

        return cb(...args);
    }
}

import './main.scss';

const canvas = document.getElementById('js-canvas');
const ctx = canvas.getContext('2d');

function onResize(/*event*/) {
    const {
        innerHeight: height,
        innerWidth: width,
    } = window;

    canvas.height = height;
    canvas.width = width;
}

window.addEventListener('resize', onResize);
onResize();

<commit_msg>chore: remove extra line<commit_after>if (process.env.NODE_ENV !== 'production') {
    const cb = window.webpackHotUpdate;

    window.webpackHotUpdate = (...args) => {
        const links = document.querySelectorAll('link[rel=stylesheet]');

        for (let link of links) {
            let { href } = link;
            link.href = 'about:blank';
            link.href = href;
        }

        return cb(...args);
    }
}

import './main.scss';

const canvas = document.getElementById('js-canvas');
const ctx = canvas.getContext('2d');

function onResize(/*event*/) {
    const {
        innerHeight: height,
        innerWidth: width,
    } = window;

    canvas.height = height;
    canvas.width = width;
}

window.addEventListener('resize', onResize);
onResize();
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

(function() {
    // special patch to correctly work on Ripple emulator (CB-9760)
    if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
        module.exports = window.open.bind(window); // fallback to default window.open behaviour
        return;
    }

    var exec = require('cordova/exec');
    var channel = require('cordova/channel');
    var modulemapper = require('cordova/modulemapper');
    var urlutil = require('cordova/urlutil');

    var InAppBrowser = function(url, windowName, windowFeatures, callbacks) {
        var me = this,
            hidden = false,
            backChannels = {
                preventexitonhide : channel.create('preventexitonhide')
            }
            polling = false,
            lastUrl = url,
            lastWindowName = windowName,
            lastWindowFeatures = windowFeatures
            lastPollIntervalToRestore = null,
            lastPollFunctionToRestore = null;

        function clearPolling () {
            lastPollIntervalToRestore = null;
            lastPollFunctionToRestore = null;
        }

        function releaseListeners(){
            for(var eventname in me.channels)
            {
                for(var listenerObserverId in me.channels[eventname].handlers)
                {
                    me.removeEventListener(eventname, me.channels[eventname].handlers[listenerObserverId]);
                }
            }
        }

        function eventCallback (event) {
            if (event && (event.type in backChannels)) {
                backChannels[event.type].fire(event);
            }
            if (event && (event.type in me.channels)) {
                me.channels[event.type].fire(event);
            }
        }

        backChannels['preventexitonhide'].subscribe(function(){
                var exitHandlersToRestore = {},
                exitChannel = me.channels['exit'],
                exitRestoreCallBack = function(){
                    // This cleans up the current handler
                    if(exitRestoreCallBack.observer_guid){
                        me.removeEventListener('exit', exitChannel.handlers[exitRestoreCallBack.observer_guid]);
                    }

                    for(var exitCallbackObserverId in exitHandlersToRestore) {
                        var eventHandler = exitHandlersToRestore[exitCallbackObserverId];
                        me.addEventListener('exit', eventHandler);
                    }
                };

                // Need to set this here as it is possible to hide via native code "directly" by calling hide via the
                // command infrastructure and not the hide method
                hidden = true;
                if(exitChannel.numHandlers >0){
                    for(var exitCallbackObserverId in exitChannel.handlers) {
                        var eventHandler = exitChannel.handlers[exitCallbackObserverId];
                        exitHandlersToRestore[exitCallbackObserverId] = exitChannel.handlers[exitCallbackObserverId];
                        me.removeEventListener('exit', eventHandler);
                    }
                    me.addEventListener('exit', exitRestoreCallBack);
                }
        });

        me.channels = {
            'loadstart': channel.create('loadstart'),
            'loadstop' : channel.create('loadstop'),
            'loaderror' : channel.create('loaderror'),
            'hidden' : channel.create('hidden'),
            'unhidden' : channel.create('unhidden'),
            'pollresult' : channel.create('pollresult'),
            'exit' : channel.create('exit')
        }

        me.isHidden = function(){
            return hidden;
        }

        me.isPolling = function(){
            return polling;
        }

        me.close = function(eventname) {
            exec(null, null, "InAppBrowser", "close", []);
            me.stopPoll();
            if(hidden){
                me.channels['exit'].fire();
            }
            hidden = false;
        }

        me.show = function(eventname) {
            exec(null, null, "InAppBrowser", "show", []);
            hidden = false;
        }

        me.startPoll = function(pollFunction, pollInterval){
           lastPollIntervalToRestore = pollInterval;
           lastPollFunctionToRestore = pollFunction;
           exec(null, null, "InAppBrowser", "startPoll", [pollFunction, pollInterval])
           polling = true;
        }

        me.stopPoll = function() {
           exec(null, null, "InAppBrowser", "stopPoll", []);
           clearPolling();
           polling = false;
        }

        me.hide = function(releaseResources, blankPage){
            //blankPage has no effect in iOS - the view is destroyed
            if(hidden){
                return;
            }

            if(releaseResources){
                me.stopPoll();
                releaseListeners();
            }

            // Release resources has no effect in native iOS - the IAB
            // Is fully closed & the JS pretends it isn't
            exec(null,null,"InAppBrowser", "hide", [releaseResources]);
            hidden = true;
        }

        me.unHide = function(strUrl, eventname){
            if(!hidden){
                return;
            }

            if(strUrl){
                lastUrl = urlutil.makeAbsolute(strUrl) || lastUrl;
            }

            me.startPoll(lastPollFunctionToRestore, lastPollIntervalToRestore);
            exec(eventCallback, eventCallback, "InAppBrowser", "unHide", [lastUrl, lastWindowName, lastWindowFeatures]);
            hidden = false;
        }

        me.addEventListener = function (eventname,f) {
            if (eventname in me.channels) {
                me.channels[eventname].subscribe(f);
            }
        }

        me.removeEventListener = function (eventname, f) {
            if (eventname in me.channels) {
                me.channels[eventname].unsubscribe(f);
            }
        }

        me.executeScript = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('executeScript requires exactly one of code or file to be specified');
            }
        }

        me.insertCSS = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('insertCSS requires exactly one of code or file to be specified');
            }
        }

        for (var callbackName in callbacks) {
            me.addEventListener(callbackName, callbacks[callbackName]);
        }

        exec(eventCallback, eventCallback, "InAppBrowser", "open", [lastUrl, lastWindowName, lastWindowFeatures]);
    }

    module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
        // Don't catch calls that write to existing frames (e.g. named iframes).
        if (window.frames && window.frames[strWindowName]) {
            var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
            return origOpenFunc.apply(window, arguments);
        }

        strUrl = urlutil.makeAbsolute(strUrl);
        strWindowFeatures = strWindowFeatures || "";

        if(strWindowName === '_system') {
            //TODO: open system browser
            exec(null, null, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);

        } else {
            var instance = new InAppBrowser(strUrl, strWindowName, strWindowFeatures, callbacks || {});
            return instance
        }
    };
})();
<commit_msg>tracing why this has suddenly stopped working<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

(function() {
    // special patch to correctly work on Ripple emulator (CB-9760)
    if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
        module.exports = window.open.bind(window); // fallback to default window.open behaviour
        return;
    }

    var exec = require('cordova/exec');
    var channel = require('cordova/channel');
    var modulemapper = require('cordova/modulemapper');
    var urlutil = require('cordova/urlutil');

    var InAppBrowser = function(url, windowName, windowFeatures, callbacks) {
        var me = this,
            hidden = false,
            backChannels = {
                preventexitonhide : channel.create('preventexitonhide')
            }
            polling = false,
            lastUrl = url,
            lastWindowName = windowName,
            lastWindowFeatures = windowFeatures
            lastPollIntervalToRestore = null,
            lastPollFunctionToRestore = null;

        function clearPolling () {
            lastPollIntervalToRestore = null;
            lastPollFunctionToRestore = null;
        }

        function releaseListeners(){
            for(var eventname in me.channels)
            {
                for(var listenerObserverId in me.channels[eventname].handlers)
                {
                    me.removeEventListener(eventname, me.channels[eventname].handlers[listenerObserverId]);
                }
            }
        }

        function eventCallback (event) {
            if (event && (event.type in backChannels)) {
                backChannels[event.type].fire(event);
            }
            if (event && (event.type in me.channels)) {
                me.channels[event.type].fire(event);
            }
        }

        backChannels['preventexitonhide'].subscribe(function(){
                var exitHandlersToRestore = {},
                exitChannel = me.channels['exit'],
                exitRestoreCallBack = function(){
                    // This cleans up the current handler
                    if(exitRestoreCallBack.observer_guid){
                        me.removeEventListener('exit', exitChannel.handlers[exitRestoreCallBack.observer_guid]);
                    }

                    for(var exitCallbackObserverId in exitHandlersToRestore) {
                        var eventHandler = exitHandlersToRestore[exitCallbackObserverId];
                        me.addEventListener('exit', eventHandler);
                    }
                };

                // Need to set this here as it is possible to hide via native code "directly" by calling hide via the
                // command infrastructure and not the hide method
                hidden = true;
                if(exitChannel.numHandlers >0){
                    for(var exitCallbackObserverId in exitChannel.handlers) {
                        var eventHandler = exitChannel.handlers[exitCallbackObserverId];
                        exitHandlersToRestore[exitCallbackObserverId] = exitChannel.handlers[exitCallbackObserverId];
                        me.removeEventListener('exit', eventHandler);
                    }
                    me.addEventListener('exit', exitRestoreCallBack);
                }
        });

        me.channels = {
            'loadstart': channel.create('loadstart'),
            'loadstop' : channel.create('loadstop'),
            'loaderror' : channel.create('loaderror'),
            'hidden' : channel.create('hidden'),
            'unhidden' : channel.create('unhidden'),
            'pollresult' : channel.create('pollresult'),
            'exit' : channel.create('exit')
        }

        me.isHidden = function(){
            return hidden;
        }

        me.isPolling = function(){
            return polling;
        }

        me.close = function(eventname) {
            exec(null, null, "InAppBrowser", "close", []);
            me.stopPoll();
            if(hidden){
                me.channels['exit'].fire();
            }
            hidden = false;
        }

        me.show = function(eventname) {
            exec(null, null, "InAppBrowser", "show", []);
            hidden = false;
        }

        me.startPoll = function(pollFunction, pollInterval){
           lastPollIntervalToRestore = pollInterval;
           lastPollFunctionToRestore = pollFunction;
           exec(null, null, "InAppBrowser", "startPoll", [pollFunction, pollInterval])
           polling = true;
        }

        me.stopPoll = function() {
           exec(null, null, "InAppBrowser", "stopPoll", []);
           clearPolling();
           polling = false;
        }

        me.hide = function(releaseResources, blankPage){
            //blankPage has no effect in iOS - the view is destroyed
            if(hidden){
                return;
            }

            if(releaseResources){
                me.stopPoll();
                releaseListeners();
            }

            // Release resources has no effect in native iOS - the IAB
            // Is fully closed & the JS pretends it isn't
            exec(null,null,"InAppBrowser", "hide", [releaseResources]);
            hidden = true;
        }

        me.unHide = function(strUrl, eventname){
            if(!hidden){
                return;
            }

            if(strUrl){
                lastUrl = urlutil.makeAbsolute(strUrl) || lastUrl;
            }

            console.log(lastUrl);
            console.log(lastWindowName);
            console.log(lastWindowFeatures);

            me.startPoll(lastPollFunctionToRestore, lastPollIntervalToRestore);
            exec(eventCallback, eventCallback, "InAppBrowser", "unHide", [lastUrl, lastWindowName, lastWindowFeatures]);
            hidden = false;
        }

        me.addEventListener = function (eventname,f) {
            if (eventname in me.channels) {
                me.channels[eventname].subscribe(f);
            }
        }

        me.removeEventListener = function (eventname, f) {
            if (eventname in me.channels) {
                me.channels[eventname].unsubscribe(f);
            }
        }

        me.executeScript = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('executeScript requires exactly one of code or file to be specified');
            }
        }

        me.insertCSS = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('insertCSS requires exactly one of code or file to be specified');
            }
        }

        for (var callbackName in callbacks) {
            me.addEventListener(callbackName, callbacks[callbackName]);
        }

        exec(eventCallback, eventCallback, "InAppBrowser", "open", [lastUrl, lastWindowName, lastWindowFeatures]);
    }

    module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
        // Don't catch calls that write to existing frames (e.g. named iframes).
        if (window.frames && window.frames[strWindowName]) {
            var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
            return origOpenFunc.apply(window, arguments);
        }

        strUrl = urlutil.makeAbsolute(strUrl);
        strWindowFeatures = strWindowFeatures || "";

        if(strWindowName === '_system') {
            //TODO: open system browser
            exec(null, null, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);

        } else {
            var instance = new InAppBrowser(strUrl, strWindowName, strWindowFeatures, callbacks || {});
            return instance
        }
    };
})();
<|endoftext|>


<commit_before>import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';

const githubSearchQuery = `cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc`;

function githubApiSearch (query) {
  return `https://api.github.com/search/repositories?q=${query}`;
}

function githubSearch (query) {
  return `https://github.com/search?q=${query}`;
}

const requestOptions = {
  url: githubApiSearch(githubSearchQuery),
  headers: {
    'User-Agent': 'cycle-ecosystem'
  }
};

Observable.bindCallback(request)(requestOptions)
  .map(([error, response]) => JSON.parse(response.body).items)
  .map(toMarkdown)
  .forEach(updateReadme);

function toMarkdown (searchResults) {
  return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?

| Name     | Description       | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}

Auto generated by update.js by [searching Github](${githubSearch(githubSearchQuery)}).

Last updated at ${new Date().toString()}.
`;
}

function toMarkdownEntry (result) {
  return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}

function updateReadme (markdown) {
  fs.writeFile('./README.md', markdown);
}
<commit_msg>Remove timestamp (so that commits only get made if list changes)<commit_after>import request from 'request';
import {Observable} from 'rxjs';
import fs from 'fs';

const githubSearchQuery = `cycle+OR+cyclejs+language%3AJavaScript+created%3A>2014-11-01+stars%3A>3&type=Repositories&sort=stars&order=desc`;

function githubApiSearch (query) {
  return `https://api.github.com/search/repositories?q=${query}`;
}

function githubSearch (query) {
  return `https://github.com/search?q=${query}`;
}

const requestOptions = {
  url: githubApiSearch(githubSearchQuery),
  headers: {
    'User-Agent': 'cycle-ecosystem'
  }
};

Observable.bindCallback(request)(requestOptions)
  .map(([error, response]) => JSON.parse(response.body).items)
  .map(toMarkdown)
  .forEach(updateReadme);

function toMarkdown (searchResults) {
  return `
# cycle-ecosystem
What are the most popular libraries for Cycle.js?

| Name     | Description       | Stars |
| -------- | ----------------- | ------|
${searchResults.map(toMarkdownEntry).join('\n')}

Auto generated by update.js by [searching Github](${githubSearch(githubSearchQuery)}).
`;
}

function toMarkdownEntry (result) {
  return `| [${result.full_name}](${result.html_url}) | ${result.description} | ${result.stargazers_count} |`;
}

function updateReadme (markdown) {
  fs.writeFile('./README.md', markdown);
}
<|endoftext|>


<commit_before>'use strict';

var node_path = require('path');
var comfort = require('comfort');

var context = {
    profile     : require('./profile'),
    neuropil    : require('./neuropil'),
    locale      : require('./i18n')
};

// Commander for CLI
// cli entrance
// cache commander instance
var commander = module.exports = comfort({
    command_root: node_path.join( __dirname, '..', '..', 'lib', 'command'),
    option_root : node_path.join( __dirname, '..', '..', 'lib', 'option'),
    name: 'cortex',

    logger: require('./logger'),
    context: context

}).on('complete', function(e) {
    if(e.error){
        this.logger.error(e.error);
        this.logger.debug(e.data);

    }else{
        this.logger.end();
    }

}).on('commandNotFound', function(e) {
    this.logger.error(
        this.logger.template( '{{name}}: "{{command}}" is not a {{name}} command. See "{{name}} --help".', {
            name: e.name,
            command: e.command
        })
    );
});

context.commander = commander;
<commit_msg>related to #90: update complete event<commit_after>'use strict';

var node_path = require('path');
var comfort = require('comfort');

var context = {
    profile     : require('./profile'),
    neuropil    : require('./neuropil'),
    locale      : require('./i18n')
};

// Commander for CLI
// cli entrance
// cache commander instance
var commander = module.exports = comfort({
    command_root: node_path.join( __dirname, '..', '..', 'lib', 'command'),
    option_root : node_path.join( __dirname, '..', '..', 'lib', 'option'),
    name: 'cortex',

    logger: require('./logger'),
    context: context

}).on('complete', function(e) {
    var err = e.error;

    if(err){
        if ( err instanceof Error ) {
            // loggie will deal with `Error` instances
            this.logger.error(err);

        // error code
        } else if (typeof err === 'number') {
            this.logger.error('Not ok, exit code: ' + err);

        } else {
            this.logger.error( err.message || err );
        }

    }else if(e.command !== 'help'){
        this.logger.info('{{green OK!}}');
    }
});

context.commander = commander;
<|endoftext|>