<commit_before>import React, { Component } from 'react';
import Panel from './internal/Panel.js';
import PanelRow from './internal/PanelRow.js';
import PanelCell from './internal/PanelCell.js';
import {Slider, Divider, TextField} from 'material-ui';

class Page extends Component {
    render() {
        return (

                <Panel header="Overview">
                    <PanelRow>
                        <PanelCell colClass="s4">

                            <TextField
                                floatingLabelText="Number of unique visitors"
                                value="100"
                                />
                            <TextField
                                floatingLabelText="Number of visits generated (approx.)"
                                value="500"
                                />
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s12">
                                    Bounce rate
                                </PanelCell>
                                <PanelCell colClass="s12">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s12">
                                    Percentage identified visitors
                                </PanelCell>
                                <PanelCell colClass="s12">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                             <TextField
                                floatingLabelText="Pageviews per visit (avg)"
                                value="4"
                                />
                            <TextField
                                floatingLabelText="Time spent per page (avg)"
                                value="00:30"
                                />

                        </PanelCell>

                        <PanelCell colClass="s4">

Traffic distribution

                        <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    micro
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    website
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>
                        <PanelCell colClass="s4">

Location

                        <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Europe, Middle East, Africa
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Asia Pacific
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Americas
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>
                    </PanelRow>
                </Panel>

        );
    }
}

export default Page;<commit_msg>Overview tab the rest of the content<commit_after>import React, { Component } from 'react';
import Panel from './internal/Panel.js';
import PanelRow from './internal/PanelRow.js';
import PanelCell from './internal/PanelCell.js';
import {Slider, Divider, TextField, DatePicker} from 'material-ui';

class Page extends Component {
    render() {
        return (

                <Panel header="Overview">
                    <PanelRow>
                        <PanelCell colClass="s4">

                            <TextField
                                floatingLabelText="Number of unique visitors"
                                value="100"
                                />
                            <TextField
                                floatingLabelText="Number of visits generated (approx.)"
                                value="500"
                                />
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s12">
                                    Bounce rate
                                </PanelCell>
                                <PanelCell colClass="s12">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s12">
                                    Percentage identified visitors
                                </PanelCell>
                                <PanelCell colClass="s12">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <TextField
                                floatingLabelText="Pageviews per visit (avg)"
                                value="4"
                                />
                            <TextField
                                floatingLabelText="Time spent per page (avg)"
                                value="00:30"
                                />

                        </PanelCell>

                        <PanelCell colClass="s4">

Traffic distribution

                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    micro
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    website
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>

                        <PanelCell colClass="s4">

Location

                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Europe, Middle East, Africa
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Asia Pacific
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Americas
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>
                    </PanelRow>

                    <PanelRow>
                        <PanelCell colClass="s4">

Start Date

                            <DatePicker container="inline" />

End Date

                            <DatePicker container="inline" />
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s12">
                                    Annual increase in traffic
                                </PanelCell>
                                <PanelCell colClass="s12">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>
                        <PanelCell colClass="s4">

Daily distribution

                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Monday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Tuesday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Wednesday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Thursday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Friday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Saturday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    Sunday
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>

                        <PanelCell colClass="s4">

Daily distribution

                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    January
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    February
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    March
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    April
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    May
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    June
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    July
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    August
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    September
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    October
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    November
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                            <PanelRow style={{ padding: '15px 0' }}>
                                <PanelCell colClass="s3">
                                    December
                                </PanelCell>
                                <PanelCell colClass="s9">
                                    <Slider value={0}> </Slider>
                                </PanelCell>
                            </PanelRow>
                        </PanelCell>

                    </PanelRow>

                </Panel>

        );
    }
}

export default Page;<|endoftext|>


<commit_before>(function () {
	var editorModule = angular.module('baddEditor');

	var baddDroppableDirective = function ($compile) {
		var dir = this;

		dir.objectEntering = function(event, object) {
			var position = $(this).offset();
			var width = $(this).outerWidth();
			var height = $(this).outerHeight();

			var body = $(this).parents('body');
			body.append('
');

			dir.objectPreview = $(object.draggable.data('raw'));
			$(this).append(dir.objectPreview);
		};

		dir.objectLeaving = function(event) {
			var body = $(event.target).parents('body');
			body.find('.badd-highlighter').remove();
			if (dir.objectPreview) {
				dir.objectPreview.remove();
			}
		};

		dir.objectDropped = function(scope) {
			return function (event, ui) {
				var rawHtml = angular.element(ui.draggable).data('raw');
				var draggedEl = angular.element(ui.draggable);
				var droppedEl = angular.element(this);
				if (rawHtml == undefined) {
					rawHtml = $(draggedEl)[0].outerHTML;
				}
				$compile(rawHtml)(scope).appendTo(droppedEl);

				dir.objectLeaving(event);
			}
		};

		return {
			restrict: 'A',
			link: function (scope, element, attrs) {
				var greedy = attrs.greedy;
				if (greedy == undefined) {
					greedy = true;
				}
				element.droppable({
					activeClass: 'drop-active',
					greedy: greedy,
					hoverClass: 'drop-hover',
					iframeFix: true,
					tolerance: 'intersect',
					over: dir.objectEntering,
					out: dir.objectLeaving,
					drop: dir.objectDropped(scope)
				});
			}
		}
	};
	baddDroppableDirective.$inject = ['$compile'];

	editorModule.directive('baddDroppable', baddDroppableDirective);
}());<commit_msg>fixing highlight border dimension after adding preview<commit_after>(function () {
	var editorModule = angular.module('baddEditor');

	var baddDroppableDirective = function ($compile) {
		var dir = this;

		dir.objectEntering = function(event, object) {
			// add preview
			dir.objectPreview = $(object.draggable.data('raw'));
			$(this).append(dir.objectPreview);

			// draw highlight border
			var position = $(this).offset();
			var width = $(this).outerWidth();
			var height = $(this).outerHeight();

			var body = $(this).parents('body');
			body.append('
');
		};

		dir.objectLeaving = function(event) {
			var body = $(event.target).parents('body');
			body.find('.badd-highlighter').remove();
			if (dir.objectPreview) {
				dir.objectPreview.remove();
			}
		};

		dir.objectDropped = function(scope) {
			return function (event, ui) {
				var rawHtml = angular.element(ui.draggable).data('raw');
				var draggedEl = angular.element(ui.draggable);
				var droppedEl = angular.element(this);
				if (rawHtml == undefined) {
					rawHtml = $(draggedEl)[0].outerHTML;
				}
				$compile(rawHtml)(scope).appendTo(droppedEl);

				dir.objectLeaving(event);
			}
		};

		return {
			restrict: 'A',
			link: function (scope, element, attrs) {
				var greedy = attrs.greedy;
				if (greedy == undefined) {
					greedy = true;
				}
				element.droppable({
					activeClass: 'drop-active',
					greedy: greedy,
					hoverClass: 'drop-hover',
					iframeFix: true,
					tolerance: 'intersect',
					over: dir.objectEntering,
					out: dir.objectLeaving,
					drop: dir.objectDropped(scope)
				});
			}
		}
	};
	baddDroppableDirective.$inject = ['$compile'];

	editorModule.directive('baddDroppable', baddDroppableDirective);
}());<|endoftext|>


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

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secondsElapsed: 1,
      message: 'Click the start button to begin!'
    }
  };

  getMinutes() {
    return Math.floor(this.state.secondsElapsed / 60);
  }

  getSeconds() {
    return (this.state.secondsElapsed % 60);
  }

  startTimer() {
    this.setState({
      message: 'Starting timer now! Let\'s code!'
    });

    this.props.startTimer();

    this.incrementer = setInterval(function() {
      this.setState({
        secondsElapsed: (this.state.secondsElapsed + 1),
        message: 'Time Elapsed: ' + this.getMinutes() + ' Minutes & ' + this.getSeconds() + ' Seconds!'
      });
    }.bind(this), 1000);
  }

  resetTimer() {
    this.setState({
      secondsElapsed: 0
    });

    if (this.state.secondsElapsed <= 60) {
      this.setState({
        message: 'You took ' + ((this.state.secondsElapsed-1) % 60) + ' Seconds!'
      });
    } else {
      this.setState({
        message: 'You took ' + Math.floor((this.state.secondsElapsed-1) / 60) + ' Minutes and ' + ((this.state.secondsElapsed-1) % 60) + ' Seconds!'
      });
    }
  }

  render() {
    return (

{this.state.message}

        <button type="button" onClick={this.startTimer.bind(this)} className="btn btn-success pull-right">START</button>

        <button type="button" onClick={this.resetTimer.bind(this)} className="btn btn-primary pull-left">FINISH</button>

    );
  }
};

export default Timer;
<commit_msg>[fix] clearInterval added to stop timer<commit_after>import React, { Component } from 'react';

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      secondsElapsed: 1,
      message: 'Click the start button to begin!'
    }
  };

  getMinutes() {
    return Math.floor(this.state.secondsElapsed / 60);
  }

  getSeconds() {
    return (this.state.secondsElapsed % 60);
  }

  startTimer() {
    this.setState({
      message: 'Starting timer now! Let\'s code!'
    });

    this.props.startTimer();

    this.incrementer = setInterval(function() {
      this.setState({
        secondsElapsed: (this.state.secondsElapsed + 1),
        message: 'Time Elapsed: ' + this.getMinutes() + ' Minutes & ' + this.getSeconds() + ' Seconds!'
      });
    }.bind(this), 1000);
  }

  resetTimer() {
    this.setState({
      secondsElapsed: 0
    });

    if (this.state.secondsElapsed <= 60) {
      this.setState({
        message: 'You took ' + ((this.state.secondsElapsed-1) % 60) + ' Seconds!'
      });
    } else {
      this.setState({
        message: 'You took ' + Math.floor((this.state.secondsElapsed-1) / 60) + ' Minutes and ' + ((this.state.secondsElapsed-1) % 60) + ' Seconds!'
      });
    }

    clearInterval(this.incrementer);
  }

  render() {
    return (

{this.state.message}

        <button type="button" onClick={this.startTimer.bind(this)} className="btn btn-success pull-right">START</button>

        <button type="button" onClick={this.resetTimer.bind(this)} className="btn btn-primary pull-left">FINISH</button>

    );
  }
};

export default Timer;
<|endoftext|>


<commit_before>var KillKat =
{
	init: 	function(){
        //if (confirm("Ready to kill Katz ??"))
        //{
            KillKat.staticFiles.load(function(){
                KillKat.initImagesHandler();
                KillKat.setSoundPlayer();
            });
        //}
	},
    currentImg: null,
    currentImgIndex: -1,
    currentOverlay: null,
    sound: null,
    domImgs : [],
    listImgs : [],
    icons: {
       iconKillable: {
            width: '20px',
            height: '20px',
            marginRight: '5px'
       }
    },
    rules : {
        IMG_MIN_WIDTH : '100px',
        IMG_MIN_HEIGHT : '100px'
    },
    styles :{
        OVERLAY_CLASS: 'killkat-overlay',
        KILLABLE_CLASS : 'killkat-icon-killable',
        KILLED_CLASS : 'killkat-overlay-splatter',
        TARGET_CLASS : 'killkat-overlay-target'
    },
    //GITHUB : 'https://cdn.rawgit.com/jorisgrouillet/killkat/master',
    GITHUB : 'http://sandbox.local/killkat/',

    requirements: {
        'min-dimensions' : function(domImg){ return ((domImg.width * domImg.height) > (parseInt(KillKat.rules.IMG_MIN_WIDTH) * parseInt(KillKat.rules.IMG_MIN_HEIGHT))); }
    },

    staticFiles: {
        load : function(callback){
            KillKat.staticFiles.loadStyles();
            KillKat.staticFiles.loadJS(callback);
        },
        loadStyles: function()
        {
            var stylesheet = document.createElement('link');
            stylesheet.href = KillKat.GITHUB+'/css/killkat.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

            var stylesheet = document.createElement('link');
            stylesheet.href = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

        },
        loadJS : function(callback){

            KillKat.loadJavascriptFile('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js', function()
            {
                require(
                    {   paths: {
                        'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
                        'jquery-ui' : '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min',
                        'jquery-transform': '//rawgit.com/louisremi/jquery.transform.js/master/jquery.transform2d',
                        'jquery-viewport' : KillKat.GITHUB+'/js/jquery.viewport.min',

                    }
                    }, ['jquery', 'jquery-ui', 'jquery-transform', 'jquery-viewport'], function(){ callback.call(this); });
              });
        }
    },
	initImagesHandler : function()
	{
        KillKat.domImgs = jQuery('img');
        KillKat.domImgs.each(
			function(idx, domImg){
				KillKat.filterImg(domImg);
            }
		);
        KillKat.razCurrentImg();
	},
    razCurrentImg: function()
    {
        KillKat.currentImg = null;
        KillKat.currentImgIndex = -1;
        KillKat.currentOverlay = null;
    },
    setCurrentImg: function(domImg)
    {
        if (domImg.tagName.toLowerCase() =='div'){
            domImg = jQuery(domImg).parent().find('img:eq(0)').get(0);
        }
        KillKat.currentImg = jQuery(domImg);
        KillKat.currentImgIndex = KillKat.getImgIndex();
        if (KillKat.currentImgIndex > -1){
            KillKat.currentOverlay = jQuery('#killkat-overlay-'+KillKat.currentImgIndex);
        }

    },

	filterImg : function(domImg)
	{
        if (KillKat.meetRequirements(domImg))
        {
            KillKat.currentImg = null;
            KillKat.setCurrentImg(domImg);
            KillKat.setImageBehaviour();
		}
	},

	meetRequirements : function(domImg)
	{
		var reqs = KillKat.requirements || [];
		var validateReqs = true;
		for (var rIdx in reqs){
			if (typeof(reqs[rIdx]) == 'function'){
				validateReqs &= reqs[rIdx].call(this, domImg);
			}
		}
		return (validateReqs===1);
	},

    setImageId: function(){
        if (typeof(KillKat.currentImg.get(0).id) =='undefined'){
            KillKat.currentImg.attr('id', 'killable-img-'+KillKat.currentImgIndex);
        }
    },
	setImageBehaviour: function()
	{
        KillKat.setImageId();
        var overlay = KillKat.setOverlay();
        KillKat.overrideClickEvent(overlay);
	},
    setOverlay: function()
    {
        var domOverlay = KillKat.currentOverlay;

        if (! domOverlay.length)
        {
            domOverlay = jQuery('

')
                .css({  'width' : KillKat.currentImg.innerWidth()+'px',
                    'height' : KillKat.currentImg.innerHeight()+'px',
                    'left' : (KillKat.currentImg.outerWidth()/4)+'px',
                    'z-index' : 1
                })
                //.insertAfter(KillKat.currentImg.parent());
                .insertBefore(KillKat.currentImg);
                   KillKat.currentImg.closest('a').css({ position : 'relative'});

            return domOverlay;
        }
    },
    overrideClickEvent: function(target)
	{
		var fct = KillKat.getClickEventFunction();
		//KillKat.currentImg.unbind('click').click(fct);
        target.click(fct);
        KillKat.setIconKillable();
	},
	getClickEventFunction: function()
	{
		return function(e){
            e.preventDefault();
            KillKat.razCurrentImg();
            KillKat.setCurrentImg(this);
            KillKat.handleTarget();

			return false;
		};
	},
	handleTarget: function()
	{
        KillKat.toggleSplatter();
    },

    toggleSplatter: function(pos)
    {
        if (! KillKat.currentOverlay.hasClass(KillKat.styles.KILLED_CLASS)){
            KillKat.removeSprite('target');
            KillKat.playSound();
            KillKat.applyVisualEffect();
        }
    },
    removeSprite : function(type)
    {
        KillKat.currentOverlay.addClass(KillKat.styles.KILLED_CLASS)
                             .removeClass(KillKat.styles.TARGET_CLASS);
    },
    applyVisualEffect : function()
    {
        // on efface le splatter
        KillKat.currentOverlay.fadeOut(1200);
        // on applique l'effet d'image : flip et collapse
        KillKat.currentImg
            .css({position :'relative'})
            .slideToggle(
            {    easing: 'easeOutExpo',
                duration: 300,
                complete: function()
                {
                    jQuery(this).slideToggle(
                        {
                            easing: 'easeOutExpo',
                            duration: 300,
                            complete : function(){
                                jQuery(this).animate({
                                    top: '+=800px'
                                }, 2000, 'swing').fadeOut(function(){ jQuery(this).remove();});
                            }
                        });
                }
            });

    },
    setIconKillable: function()
    {
        var domIconKillable = jQuery('#'+KillKat.styles.KILLABLE_CLASS+'-'+KillKat.currentImgIndex);
        if (! domIconKillable.length)
        {
            jQuery('

')
                .css({
                    'top' : 0,
                    'left' : (KillKat.currentImg.outerWidth() +
                             (parseInt(KillKat.icons.iconKillable.width)*1.5) +
                             (parseInt(KillKat.icons.iconKillable.marginRight))) +'px'
                })
                .appendTo(KillKat.currentImg.parent());
        }
    },
    highlightKillables: function(){
        jQuery('.'+KillKat.styles.KILLABLE_CLASS+':in-viewport')
            .animate({ 'transform' : 'scale(2)'}, 700)
            .animate({ 'transform' : 'scale(1)'}, 700);
    },

	isKatKilled: function(jqImg)
	{
		return (jqImg.parent().hasClass(KillKat.styles.KILLED_CLASS));
	},

    getImgIndex : function()
    {
        return KillKat.domImgs.index(KillKat.currentImg);
    },
    playSound : function()
    {
        if (! jQuery('#killkat-sound').length){
            KillKat.setSoundPlayer();
        }
        KillKat.sound.play();
    },
    setSoundPlayer: function()
    {
        if (! jQuery('#killkat-sound').length)
        {
            var sound = jQuery('<audio id="killkat-sound" preload="auto">'+
                '<source src="'+KillKat.GITHUB+'/audio/splatter-sound.mp3" type="audio/mp3" />'+
                            //'<source src="http://www.freesfx.co.uk/rx2/mp3s/2/1871_1272479313.mp3" type="audio/mp3" />'+
                            'Votre navigateur n\'est pas compatible'+
                            '</audio>');

            jQuery('body').append(sound);
            KillKat.sound = sound.get(0);
        }
    },
	convertImgToBase64 : function(url, callback, outputFormat)
	{
	    var canvas = document.createElement('canvas'),
	    ctx = canvas.getContext('2d'),
	    img = new Image();
	    img.crossOrigin = 'Anonymous';
	    img.onload = function(){
	        canvas.height = img.height;
	        canvas.width = img.width;
	        ctx.drawImage(img,0,0);
	        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
	        callback.call(this, dataURL);
	        canvas = null;
	    };
	    img.src = url;
	},
    loadJavascriptFile: function(url, callback)
    {
        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    if (callback) callback();
                }
            };
        } else { //Others
            script.onload = function () {
                if (callback) callback();

            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

};

KillKat.init();

<commit_msg>switcing du chemin Github version prod<commit_after>var KillKat =
{
	init: 	function(){
        //if (confirm("Ready to kill Katz ??"))
        //{
            KillKat.staticFiles.load(function(){
                KillKat.initImagesHandler();
                KillKat.setSoundPlayer();
            });
        //}
	},
    currentImg: null,
    currentImgIndex: -1,
    currentOverlay: null,
    sound: null,
    domImgs : [],
    listImgs : [],
    icons: {
       iconKillable: {
            width: '20px',
            height: '20px',
            marginRight: '5px'
       }
    },
    rules : {
        IMG_MIN_WIDTH : '100px',
        IMG_MIN_HEIGHT : '100px'
    },
    styles :{
        OVERLAY_CLASS: 'killkat-overlay',
        KILLABLE_CLASS : 'killkat-icon-killable',
        KILLED_CLASS : 'killkat-overlay-splatter',
        TARGET_CLASS : 'killkat-overlay-target'
    },
    GITHUB : 'https://cdn.rawgit.com/jorisgrouillet/killkat/master',
    //GITHUB : 'http://sandbox.local/killkat/',

    requirements: {
        'min-dimensions' : function(domImg){ return ((domImg.width * domImg.height) > (parseInt(KillKat.rules.IMG_MIN_WIDTH) * parseInt(KillKat.rules.IMG_MIN_HEIGHT))); }
    },

    staticFiles: {
        load : function(callback){
            KillKat.staticFiles.loadStyles();
            KillKat.staticFiles.loadJS(callback);
        },
        loadStyles: function()
        {
            var stylesheet = document.createElement('link');
            stylesheet.href = KillKat.GITHUB+'/css/killkat.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

            var stylesheet = document.createElement('link');
            stylesheet.href = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css';
            stylesheet.rel = 'stylesheet';
            stylesheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(stylesheet);

        },
        loadJS : function(callback){

            KillKat.loadJavascriptFile('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/require.min.js', function()
            {
                require(
                    {   paths: {
                        'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
                        'jquery-ui' : '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min',
                        'jquery-transform': '//rawgit.com/louisremi/jquery.transform.js/master/jquery.transform2d',
                        'jquery-viewport' : KillKat.GITHUB+'/js/jquery.viewport.min',

                    }
                    }, ['jquery', 'jquery-ui', 'jquery-transform', 'jquery-viewport'], function(){ callback.call(this); });
              });
        }
    },
	initImagesHandler : function()
	{
        KillKat.domImgs = jQuery('img');
        KillKat.domImgs.each(
			function(idx, domImg){
				KillKat.filterImg(domImg);
            }
		);
        KillKat.razCurrentImg();
	},
    razCurrentImg: function()
    {
        KillKat.currentImg = null;
        KillKat.currentImgIndex = -1;
        KillKat.currentOverlay = null;
    },
    setCurrentImg: function(domImg)
    {
        if (domImg.tagName.toLowerCase() =='div'){
            domImg = jQuery(domImg).parent().find('img:eq(0)').get(0);
        }
        KillKat.currentImg = jQuery(domImg);
        KillKat.currentImgIndex = KillKat.getImgIndex();
        if (KillKat.currentImgIndex > -1){
            KillKat.currentOverlay = jQuery('#killkat-overlay-'+KillKat.currentImgIndex);
        }

    },

	filterImg : function(domImg)
	{
        if (KillKat.meetRequirements(domImg))
        {
            KillKat.currentImg = null;
            KillKat.setCurrentImg(domImg);
            KillKat.setImageBehaviour();
		}
	},

	meetRequirements : function(domImg)
	{
		var reqs = KillKat.requirements || [];
		var validateReqs = true;
		for (var rIdx in reqs){
			if (typeof(reqs[rIdx]) == 'function'){
				validateReqs &= reqs[rIdx].call(this, domImg);
			}
		}
		return (validateReqs===1);
	},

    setImageId: function(){
        if (typeof(KillKat.currentImg.get(0).id) =='undefined'){
            KillKat.currentImg.attr('id', 'killable-img-'+KillKat.currentImgIndex);
        }
    },
	setImageBehaviour: function()
	{
        KillKat.setImageId();
        var overlay = KillKat.setOverlay();
        KillKat.overrideClickEvent(overlay);
	},
    setOverlay: function()
    {
        var domOverlay = KillKat.currentOverlay;

        if (! domOverlay.length)
        {
            domOverlay = jQuery('

')
                .css({  'width' : KillKat.currentImg.innerWidth()+'px',
                    'height' : KillKat.currentImg.innerHeight()+'px',
                    'left' : (KillKat.currentImg.outerWidth()/4)+'px',
                    'z-index' : 1
                })
                //.insertAfter(KillKat.currentImg.parent());
                .insertBefore(KillKat.currentImg);
                   KillKat.currentImg.closest('a').css({ position : 'relative'});

            return domOverlay;
        }
    },
    overrideClickEvent: function(target)
	{
		var fct = KillKat.getClickEventFunction();
		//KillKat.currentImg.unbind('click').click(fct);
        target.click(fct);
        KillKat.setIconKillable();
	},
	getClickEventFunction: function()
	{
		return function(e){
            e.preventDefault();
            KillKat.razCurrentImg();
            KillKat.setCurrentImg(this);
            KillKat.handleTarget();

			return false;
		};
	},
	handleTarget: function()
	{
        KillKat.toggleSplatter();
    },

    toggleSplatter: function(pos)
    {
        if (! KillKat.currentOverlay.hasClass(KillKat.styles.KILLED_CLASS)){
            KillKat.removeSprite('target');
            KillKat.playSound();
            KillKat.applyVisualEffect();
        }
    },
    removeSprite : function(type)
    {
        KillKat.currentOverlay.addClass(KillKat.styles.KILLED_CLASS)
                             .removeClass(KillKat.styles.TARGET_CLASS);
    },
    applyVisualEffect : function()
    {
        // on efface le splatter
        KillKat.currentOverlay.fadeOut(1200);
        // on applique l'effet d'image : flip et collapse
        KillKat.currentImg
            .css({position :'relative'})
            .slideToggle(
            {    easing: 'easeOutExpo',
                duration: 300,
                complete: function()
                {
                    jQuery(this).slideToggle(
                        {
                            easing: 'easeOutExpo',
                            duration: 300,
                            complete : function(){
                                jQuery(this).animate({
                                    top: '+=800px'
                                }, 2000, 'swing').fadeOut(function(){ jQuery(this).remove();});
                            }
                        });
                }
            });

    },
    setIconKillable: function()
    {
        var domIconKillable = jQuery('#'+KillKat.styles.KILLABLE_CLASS+'-'+KillKat.currentImgIndex);
        if (! domIconKillable.length)
        {
            jQuery('

')
                .css({
                    'top' : 0,
                    'left' : (KillKat.currentImg.outerWidth() +
                             (parseInt(KillKat.icons.iconKillable.width)*1.5) +
                             (parseInt(KillKat.icons.iconKillable.marginRight))) +'px'
                })
                .appendTo(KillKat.currentImg.parent());
        }
    },
    highlightKillables: function(){
        jQuery('.'+KillKat.styles.KILLABLE_CLASS+':in-viewport')
            .animate({ 'transform' : 'scale(2)'}, 700)
            .animate({ 'transform' : 'scale(1)'}, 700);
    },

	isKatKilled: function(jqImg)
	{
		return (jqImg.parent().hasClass(KillKat.styles.KILLED_CLASS));
	},

    getImgIndex : function()
    {
        return KillKat.domImgs.index(KillKat.currentImg);
    },
    playSound : function()
    {
        if (! jQuery('#killkat-sound').length){
            KillKat.setSoundPlayer();
        }
        KillKat.sound.play();
    },
    setSoundPlayer: function()
    {
        if (! jQuery('#killkat-sound').length)
        {
            var sound = jQuery('<audio id="killkat-sound" preload="auto">'+
                '<source src="'+KillKat.GITHUB+'/audio/splatter-sound.mp3" type="audio/mp3" />'+
                            //'<source src="http://www.freesfx.co.uk/rx2/mp3s/2/1871_1272479313.mp3" type="audio/mp3" />'+
                            'Votre navigateur n\'est pas compatible'+
                            '</audio>');

            jQuery('body').append(sound);
            KillKat.sound = sound.get(0);
        }
    },
	convertImgToBase64 : function(url, callback, outputFormat)
	{
	    var canvas = document.createElement('canvas'),
	    ctx = canvas.getContext('2d'),
	    img = new Image();
	    img.crossOrigin = 'Anonymous';
	    img.onload = function(){
	        canvas.height = img.height;
	        canvas.width = img.width;
	        ctx.drawImage(img,0,0);
	        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
	        callback.call(this, dataURL);
	        canvas = null;
	    };
	    img.src = url;
	},
    loadJavascriptFile: function(url, callback)
    {
        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    if (callback) callback();
                }
            };
        } else { //Others
            script.onload = function () {
                if (callback) callback();

            };
        }
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

};

KillKat.init();

<|endoftext|>


<commit_before>"use strict";

let React = require("react/addons");
let ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
let SearchField = require("./common/searchField");
let DrugList = require("./drugList");
let DrugStore = require("../stores/drugStore");

let store = new DrugStore();

let Drugs = React.createClass({

    propTypes: {
        params: React.PropTypes.object,
        children: React.PropTypes.node
    },

    getInitialState: function() {
        return {
            value: "",
            data: []
        };
    },

    _performQuery: function (query) {
        let qs = `openfda.brand_name:${query}+OR+openfda.substance_name:${query}+OR+openfda.manufacturer_name:${query}`;
        store.list({search: qs, limit: 10}).then((res) => {
            this.setState({data: res.body.data, loading: false});
        }, () => {
            this.setState({data: [], loading: false});
        });
    },

    _handleSearch: function (query) {
        this.setState({
            value: query
        });
        if (query.length) {
            this.setState({loading: true});
            this._performQuery(query);
        } else {
            this.setState({data: [], loading: false});
        }
    },

    render: function() {
        let list = null,
            classNames = ["drugs"];

        if (this.props.params && this.props.params.drugId) {
            classNames.push("drugs--populated");
        }

        if (this.state.data.length && !this.state.loading) {
            list = (
                <DrugList key={this.state.value} data={this.state.data}/>
            );
        }
        return (

                    <SearchField onSearch={this._handleSearch} loading={this.state.loading} placeholder={"Search for drugs and medication"}/>
                    <ReactCSSTransitionGroup transitionName="transition" transitionAppear={true}>
                        {list}
                    </ReactCSSTransitionGroup>

                    {this.props.children}

        );
    }
});

module.exports = Drugs;
<commit_msg>#110 - Cancel pending requests<commit_after>"use strict";

let React = require("react/addons");
let ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
let SearchField = require("./common/searchField");
let DrugList = require("./drugList");
let DrugStore = require("../stores/drugStore");

let store = new DrugStore();

let Drugs = React.createClass({

    propTypes: {
        params: React.PropTypes.object,
        children: React.PropTypes.node
    },

    getInitialState: function() {
        return {
            value: "",
            data: [],
            currentRequest: null
        };
    },

    _performQuery: function (query) {

        // cancel exesting request
        if (this.state.currentRequest) {
            this.state.currentRequest.cancel();
        }

        // perform query
        let qs = `openfda.brand_name:${query}+OR+openfda.substance_name:${query}+OR+openfda.manufacturer_name:${query}`;
        let req = store.list({search: qs, limit: 10}).then((res) => {
            this.setState({data: res.body.data, loading: false, currentRequest: null});
        }, (err) => {
            if (err && err.name !== "CancellationError") {
                this.setState({data: [], loading: false, currentRequest: null});
            }
        });

        // track this request
        this.setState({currentRequest: req});
    },

    _handleSearch: function (query) {
        this.setState({ value: query });
        if (query) {
            this.setState({loading: true});
            this._performQuery(query);
        } else {
            this.setState({data: [], loading: false});
        }
    },

    _getClassNames: function () {
        return this.props.params.drugId ? "drugs drugs--populated" : "drugs";
    },

    render: function() {
        let list = null;

        if (this.state.data.length && !this.state.loading) {
            list = <DrugList key={this.state.value} data={this.state.data}/>;
        }
        return (

                    <SearchField onSearch={this._handleSearch} loading={this.state.loading} placeholder={"Search for drugs and medication"}/>
                    <ReactCSSTransitionGroup transitionName="transition" transitionAppear={true}>
                        {list}
                    </ReactCSSTransitionGroup>

                    {this.props.children}

        );
    }
});

module.exports = Drugs;
<|endoftext|>


<commit_before>
/* Contains basic tiles like corridors and small rooms. */

const RG = require('../src/rg');
RG.Template = require('../src/template');

const Basic = {};
Basic.tiles = {};

Basic.tiles.corner = [
`
dir:NE
name:corner
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
#??....
#?????#
Y?????#
#######`,

`
dir:NEW
name:tcorner
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
.......
#?????#
Y?????#
#######`,

`
dir:NSEW
name:cross
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
.......
#??.??#
Y??.??#
###.###`

];

Basic.tiles.corridor = [
`
dir:NS
name:corridor
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
#??.??#
#??.??#
Y??.??#
###.###`

];

Basic.tiles.room = [
`
dir:N
name:room
X=#
Y=#

#X#.#X#
Y.....#
#.....#
#.....#
#.....#
Y.....#
#######`

];

// Contains names of the tiles to transform
const transforms = {
    all: ['corner', 'room'],
    flipVer: [],
    rotateR90: ['tcorner', 'corridor'],
    rotateR180: ['tcorner'],
    rotateR270: ['tcorner']
};

// All tiles concat together
Basic.tiles.all = []
    .concat(Basic.tiles.corner)
    .concat(Basic.tiles.corridor)
    .concat(Basic.tiles.room);

// Templates created from tiles strings
Basic.templates = Basic.tiles.all.map(tile => (
    RG.Template.createTemplate(tile)
));

// Transformation of each template added
Object.keys(transforms).forEach(func => {
    if (func !== 'all') {
        const created = [];
        let names = transforms[func];
        names = names.concat(transforms.all);
        names.forEach(name => {
            const templ = Basic.templates.find(t => (
                t.getProp('name') === name
            ));
            if (templ) {
                const newTempl = RG.Template[func](templ);
                created.push(newTempl);
            }

        });
        Basic.templates = Basic.templates.concat(created);
    }
});

const weighted = [];
Basic.templates.forEach(templ => {
    const weight = templ.getProp('weight');
    if (weight) {
        const nClones = weight - 1;
        for (let i = 0; i < nClones; i++) {
            weighted.push(templ.clone());
        }
    }
});
Basic.templates = Basic.templates.concat(weighted);

module.exports = Basic;
<commit_msg>Added getRotations().<commit_after>
/* Contains basic tiles like corridors and small rooms. */

const RG = require('../src/rg');
RG.Template = require('../src/template');

const Basic = {};
Basic.tiles = {};

Basic.tiles.corner = [
`
dir:NE
name:corner
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
#??....
#?????#
Y?????#
#######`,

`
dir:NEW
name:tcorner
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
.......
#?????#
Y?????#
#######`,

`
dir:NSEW
name:cross
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
.......
#??.??#
Y??.??#
###.###`

];

Basic.tiles.corridor = [
`
dir:NS
name:corridor
X=#
Y=#

#X#.#X#
Y??.??#
#??.??#
#??.??#
#??.??#
Y??.??#
###.###`

];

Basic.tiles.room = [
`
dir:N
name:room
X=#
Y=#

#X#.#X#
Y.....#
#.....#
#.....#
#.....#
Y.....#
#######`

];

// Contains names of the tiles to transform
const transforms = {
    all: ['corner'],
    flipVer: [],
    rotateR90: ['tcorner', 'corridor', 'room'],
    rotateR180: ['tcorner', 'room'],
    rotateR270: ['tcorner', 'room']
};

// All tiles concat together
Basic.tiles.all = []
    .concat(Basic.tiles.corner)
    .concat(Basic.tiles.corridor)
    .concat(Basic.tiles.room);

// Templates created from tiles strings
Basic.templates = Basic.tiles.all.map(tile => (
    RG.Template.createTemplate(tile)
));

// Transformation of each template added
Object.keys(transforms).forEach(func => {
    if (func !== 'all') {
        const created = [];
        let names = transforms[func];
        names = names.concat(transforms.all);
        names.forEach(name => {
            const templ = Basic.templates.find(t => (
                t.getProp('name') === name
            ));

            if (templ) {
                const newTempl = RG.Template[func](templ);
                created.push(newTempl);
                if (func === 'flipVer') {
                    const rotations = getRotations(name);
                    rotations.forEach(rot => {
                        const rotatedTempl = RG.Template[rot](newTempl);

                        created.push(rotatedTempl);
                    });
                }
            }

        });
        Basic.templates = Basic.templates.concat(created);
    }
});

const weighted = [];
Basic.templates.forEach(templ => {
    const weight = templ.getProp('weight');
    if (weight) {
        const nClones = weight - 1;
        for (let i = 0; i < nClones; i++) {
            weighted.push(templ.clone());
        }
    }
});
Basic.templates = Basic.templates.concat(weighted);

/* Finds which rotations need to be applied to given template by name. This is
 * mainly used when flipping vertical to find which rotations must be done. */
function getRotations(name) {
    const found = [];
    const rotations = ['rotateR90', 'rotateR180', 'rotateR270'];
    rotations.forEach(rot => {
        if (transforms[rot].indexOf(name) >= 0) {
            found.push(rot);
        }
    });
    return found;
}

module.exports = Basic;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/events",
    "firebug/lib/trace"
],
function factoryOptions(Events, FBTrace) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const nsIPrefBranch = Ci.nsIPrefBranch;
const PrefService = Cc["@mozilla.org/preferences-service;1"];

const nsIPrefService = Ci.nsIPrefService;
const prefService = PrefService.getService(nsIPrefService);
const prefs = PrefService.getService(nsIPrefBranch);

const prefNames =  // XXXjjb TODO distribute to modules
[
    // Global
    "defaultPanelName", "throttleMessages", "textSize", "showInfoTips",
    "commandEditor", "textWrapWidth", "framePosition", "showErrorCount",
    "activateSameOrigin", "allPagesActivation", "hiddenPanels",
    "panelTabMinWidth", "sourceLinkLabelWidth", "currentVersion",
    "useDefaultLocale", "toolbarCustomizationDone",
    "showBreakNotification", "stringCropLength", "showFirstRunPage",

    // Search
    "searchCaseSensitive", "searchGlobal", "searchUseRegularExpression",
    "netSearchHeaders", "netSearchParameters", "netSearchResponseBody",

    // Console
    "showJSErrors", "showJSWarnings", "showCSSErrors", "showXMLErrors",
    "showChromeErrors", "showChromeMessages",
    "showXMLHttpRequests", "showNetworkErrors", "tabularLogMaxHeight",
    "consoleFilterTypes", "alwaysShowCommandLine",
    "commandLineShowCompleterPopup",

    // HTML
    "showFullTextNodes", "showCommentNodes",
    "showTextNodesWithWhitespace", "entityDisplay",
    "highlightMutations", "expandMutations", "scrollToMutations", "shadeBoxModel",
    "showQuickInfoBox", "displayedAttributeValueLimit", "multiHighlightLimit",

    // CSS
    "onlyShowAppliedStyles",
    "showUserAgentCSS",
    "expandShorthandProps",
    "cssEditMode",
    "colorDisplay",

    // Computed
    "computedStylesDisplay",
    "showMozillaSpecificStyles",

    // Script
    "decompileEvals", "replaceTabs", "maxScriptLineLength",

    // DOM
    "showUserProps", "showUserFuncs", "showDOMProps", "showDOMFuncs", "showDOMConstants",
    "ObjectShortIteratorMax", "showEnumerableProperties", "showOwnProperties",
    "showInlineEventHandlers", "showClosures",

    // Layout
    "showRulers",

    // Net
    "netFilterCategories", "netDisplayedResponseLimit",
    "netDisplayedPostBodyLimit", "netPhaseInterval", "sizePrecision",
    "netParamNameLimit", "netShowPaintEvents", "netShowBFCacheResponses",
    "netHtmlPreviewHeight",

    // JSON Preview
    "sortJsonPreview",

    // Stack
    "omitObjectPathStack",

    "showStackTrace", // Console
    "filterSystemURLs", // Stack
    "breakOnErrors",  "trackThrowCatch" // Script
];

var optionUpdateMap = {};

// ********************************************************************************************* //

/**
 * Interface to preference storage.
 * Panels send commands to request option change.
 * Backend responds with events when the change is accepted.
 */
var Options =
/** @lends Options */
{
    prefDomain: "extensions.firebug",

    getPrefDomain: function()
    {
        return this.prefDomain;
    },

    initialize: function(prefDomain)
    {
        this.prefDomain = prefDomain;

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("options.initialize with prefDomain " + this.prefDomain);

        this.initializePrefs();
    },

    shutdown: function()
    {
        prefs.removeObserver(this.prefDomain, this, false);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Custom Listeners

    listeners: [],

    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        for (var i=0; i<this.listeners.length; ++i)
            if (this.listeners[i] == listener)
                return this.listeners.splice(i, 1);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // nsIPrefObserver

    observe: function(subject, topic, data)
    {
        if (data.indexOf(Options.prefDomain) === -1)
            return;

        var name = data.substr(Options.prefDomain.length+1);  // +1 for .
        var value = this.get(name);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.observe name = value: "+name+"= "+value+"\n");

        this.updatePref(name, value);
    },

    updatePref: function(name, value)
    {
        // Prevent infinite recursion due to pref observer
        if (optionUpdateMap.hasOwnProperty(name))
            return;

        try
        {
            optionUpdateMap[name] = 1;
            Firebug[name] = value;

            Events.dispatch(this.listeners, "updateOption", [name, value]);
        }
        catch (err)
        {
            if (FBTrace.DBG_OPTIONS || FBTrace.DBG_ERRORS)
                FBTrace.sysout("options.updatePref EXCEPTION:" + err, err);
        }
        finally
        {
            delete optionUpdateMap[name];
        }

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.updatePref EXIT: "+name+"="+value+"\n");
    },

    register: function(name, value)
    {
        var currentValue = this.getPref(this.prefDomain, name);

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("registerPreference "+name+" -> "+value+" type "+typeof(value)+
                " with currentValue "+currentValue);

        if (currentValue === undefined)
        {
            // https://developer.mozilla.org/en/Code_snippets/Preferences
            // This is the reason why you should usually pass strings ending with a dot to
            // getBranch(), like prefs.getBranch("accessibility.").
            var defaultBranch = prefService.getDefaultBranch(this.prefDomain+"."); //

            var type = this.getPreferenceTypeByExample(typeof(value));
            if (this.setPreference(name, value, type, defaultBranch))
                return true;
        }

        return false;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options
    // TODO support per context options eg break on error

    initializePrefs: function()
    {
        for (var i = 0; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        prefs.addObserver(this.prefDomain, this, false);

        var basePrefNames = prefNames.length;

        for (var i = basePrefNames; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        if (FBTrace.DBG_OPTIONS)
        {
             for (var i = 0; i < prefNames.length; ++i)
             {
                FBTrace.sysout("options.initialize option "+this.prefDomain+"."+prefNames[i]+"="+
                    Firebug[prefNames[i]]+"\n");
             }
        }
    },

    togglePref: function(name)
    {
        this.set(name, !this.get(name));
    },

    get: function(name)
    {
        return Options.getPref(this.prefDomain, name);
    },

    getPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;

        var type = prefs.getPrefType(prefName);

        var value = null;
        if (type == nsIPrefBranch.PREF_STRING)
            value = prefs.getCharPref(prefName);
        else if (type == nsIPrefBranch.PREF_INT)
            value = prefs.getIntPref(prefName);
        else if (type == nsIPrefBranch.PREF_BOOL)
            value = prefs.getBoolPref(prefName);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.getPref "+prefName+" has type "+
                this.getPreferenceTypeName(type)+" and value "+value);

        return value;
    },

    set: function(name, value)
    {
        Options.setPref(Options.prefDomain, name, value);
    },

    /**
     * Set a preference value.
     *
     * @param prefDomain, e.g. "extensions.firebug"
     * @param name Name of the preference (the part after prfDomain without dot)
     * @param value New value for the preference.
     * @param prefType optional pref type useful when adding a new preference.
     */
    setPref: function(prefDomain, name, value, prefType)
    {
        var prefName = prefDomain + "." + name;

        var type = this.getPreferenceTypeByExample((prefType ? prefType : typeof(value)));
        if (!this.setPreference(prefName, value, type, prefs))
            return;

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.setPref type="+type+" name="+prefName+" value="+value);
    },

    setPreference: function(prefName, value, type, prefBranch)
    {
        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("setPreference "+prefName, {prefName: prefName, value: value});

        if (type == nsIPrefBranch.PREF_STRING)
            prefBranch.setCharPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INT)
            prefBranch.setIntPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_BOOL)
            prefBranch.setBoolPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INVALID)
        {
            FBTrace.sysout("options.setPref FAILS: Invalid preference "+prefName+" with type "+
                type+", check that it is listed in defaults/prefs.js");

            return false;
        }

        return true;
    },

    getPreferenceTypeByExample: function(prefType)
    {
        var type = nsIPrefBranch.PREF_INVALID;
        if (prefType)
        {
            if (prefType === typeof("s"))
                type = nsIPrefBranch.PREF_STRING;
            else if (prefType === typeof(1))
                type = nsIPrefBranch.PREF_INT;
            else if (prefType === typeof(true))
                type = nsIPrefBranch.PREF_BOOL;
        }
        else
        {
            type = prefs.getPrefType(prefName);
        }

        return type;
    },

    getPreferenceTypeName: function(prefType)
    {
        if (prefType == Ci.nsIPrefBranch.PREF_STRING)
            return "string";
        else if (prefType == Ci.nsIPrefBranch.PREF_INT)
            return "int";
        else if (prefType == Ci.nsIPrefBranch.PREF_BOOL)
            return "boolean";
    },

    clear: function(name)
    {
        Options.clearPref(Options.prefDomain, name);
    },

    clearPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;
        if (prefs.prefHasUserValue(prefName))
            prefs.clearUserPref(prefName);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug UI text zoom

    changeTextSize: function(amt)
    {
        var textSize = Options.get("textSize");
        var newTextSize = textSize + amt;
        if ((newTextSize < 0 && Math.abs(newTextSize) < this.negativeZoomFactors.length) ||
            (newTextSize >= 0 && textSize+amt < this.positiveZoomFactors.length))
        {
            this.setTextSize(textSize+amt);
        }
    },

    setTextSize: function(value)
    {
        var setValue = value;
        if (value >= this.positiveZoomFactors.length)
            setValue = this.positiveZoomFactors[this.positiveZoomFactors.length-1];
        else if (value < 0 && Math.abs(value) >= this.negativeZoomFactors.length)
            setValue = this.negativeZoomFactors[this.negativeZoomFactors.length-1];
        this.set("textSize", setValue);
    },

    positiveZoomFactors: [1, 1.1, 1.2, 1.3, 1.5, 2, 3],
    negativeZoomFactors: [1, 0.95, 0.8, 0.7, 0.5],

    getZoomByTextSize: function(value)
    {
        var zoom = value >= 0 ? this.positiveZoomFactors[value] :
            this.negativeZoomFactors[Math.abs(value)];

        return zoom;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    /**
     * Resets all Firebug options to default state. Note that every option
     * starting with "extensions.firebug" is considered as a Firebug option.
     *
     * Options starting with DBG_ are intended for Firebug Tracing Console (FBTrace)
     * and ignored (their state is not changed).
     */
    resetAllOptions: function()
    {
        var preferences = prefs.getChildList("extensions.firebug", {});
        for (var i = 0; i < preferences.length; i++)
        {
            if (preferences[i].indexOf("DBG_") == -1)
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Clearing option: " + i + ") " + preferences[i]);

                if (prefs.prefHasUserValue(preferences[i]))  // avoid exception
                    prefs.clearUserPref(preferences[i]);
            }
            else
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Skipped clearing option: " + i + ") " + preferences[i]);
            }
        }
    },

    forceSave: function()
    {
        prefs.savePrefFile(null);
    }
};

// ********************************************************************************************* //
// Registration

return Options;

// ********************************************************************************************* //
});
<commit_msg>Added functions for getting default values for preferences<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/events",
    "firebug/lib/trace"
],
function factoryOptions(Events, FBTrace) {

// ********************************************************************************************* //
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const nsIPrefBranch = Ci.nsIPrefBranch;
const PrefService = Cc["@mozilla.org/preferences-service;1"];

const nsIPrefService = Ci.nsIPrefService;
const prefService = PrefService.getService(nsIPrefService);
const prefs = PrefService.getService(nsIPrefBranch);

const prefNames =  // XXXjjb TODO distribute to modules
[
    // Global
    "defaultPanelName", "throttleMessages", "textSize", "showInfoTips",
    "commandEditor", "textWrapWidth", "framePosition", "showErrorCount",
    "activateSameOrigin", "allPagesActivation", "hiddenPanels",
    "panelTabMinWidth", "sourceLinkLabelWidth", "currentVersion",
    "useDefaultLocale", "toolbarCustomizationDone",
    "showBreakNotification", "stringCropLength", "showFirstRunPage",

    // Search
    "searchCaseSensitive", "searchGlobal", "searchUseRegularExpression",
    "netSearchHeaders", "netSearchParameters", "netSearchResponseBody",

    // Console
    "showJSErrors", "showJSWarnings", "showCSSErrors", "showXMLErrors",
    "showChromeErrors", "showChromeMessages",
    "showXMLHttpRequests", "showNetworkErrors", "tabularLogMaxHeight",
    "consoleFilterTypes", "alwaysShowCommandLine",
    "commandLineShowCompleterPopup",

    // HTML
    "showFullTextNodes", "showCommentNodes",
    "showTextNodesWithWhitespace", "entityDisplay",
    "highlightMutations", "expandMutations", "scrollToMutations", "shadeBoxModel",
    "showQuickInfoBox", "displayedAttributeValueLimit", "multiHighlightLimit",

    // CSS
    "onlyShowAppliedStyles",
    "showUserAgentCSS",
    "expandShorthandProps",
    "cssEditMode",
    "colorDisplay",

    // Computed
    "computedStylesDisplay",
    "showMozillaSpecificStyles",

    // Script
    "decompileEvals", "replaceTabs", "maxScriptLineLength",

    // DOM
    "showUserProps", "showUserFuncs", "showDOMProps", "showDOMFuncs", "showDOMConstants",
    "ObjectShortIteratorMax", "showEnumerableProperties", "showOwnProperties",
    "showInlineEventHandlers", "showClosures",

    // Layout
    "showRulers",

    // Net
    "netFilterCategories", "netDisplayedResponseLimit",
    "netDisplayedPostBodyLimit", "netPhaseInterval", "sizePrecision",
    "netParamNameLimit", "netShowPaintEvents", "netShowBFCacheResponses",
    "netHtmlPreviewHeight",

    // JSON Preview
    "sortJsonPreview",

    // Stack
    "omitObjectPathStack",

    "showStackTrace", // Console
    "filterSystemURLs", // Stack
    "breakOnErrors",  "trackThrowCatch" // Script
];

var optionUpdateMap = {};

// ********************************************************************************************* //

/**
 * Interface to preference storage.
 * Panels send commands to request option change.
 * Backend responds with events when the change is accepted.
 */
var Options =
/** @lends Options */
{
    prefDomain: "extensions.firebug",

    getPrefDomain: function()
    {
        return this.prefDomain;
    },

    initialize: function(prefDomain)
    {
        this.prefDomain = prefDomain;

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("options.initialize with prefDomain " + this.prefDomain);

        this.initializePrefs();
    },

    shutdown: function()
    {
        prefs.removeObserver(this.prefDomain, this, false);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Custom Listeners

    listeners: [],

    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        for (var i=0; i<this.listeners.length; ++i)
            if (this.listeners[i] == listener)
                return this.listeners.splice(i, 1);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // nsIPrefObserver

    observe: function(subject, topic, data)
    {
        if (data.indexOf(Options.prefDomain) === -1)
            return;

        var name = data.substr(Options.prefDomain.length+1);  // +1 for .
        var value = this.get(name);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.observe name = value: "+name+"= "+value+"\n");

        this.updatePref(name, value);
    },

    updatePref: function(name, value)
    {
        // Prevent infinite recursion due to pref observer
        if (optionUpdateMap.hasOwnProperty(name))
            return;

        try
        {
            optionUpdateMap[name] = 1;
            Firebug[name] = value;

            Events.dispatch(this.listeners, "updateOption", [name, value]);
        }
        catch (err)
        {
            if (FBTrace.DBG_OPTIONS || FBTrace.DBG_ERRORS)
                FBTrace.sysout("options.updatePref EXCEPTION:" + err, err);
        }
        finally
        {
            delete optionUpdateMap[name];
        }

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.updatePref EXIT: "+name+"="+value+"\n");
    },

    register: function(name, value)
    {
        var currentValue = this.getPref(this.prefDomain, name);

        if (FBTrace.DBG_INITIALIZE)
            FBTrace.sysout("registerPreference "+name+" -> "+value+" type "+typeof(value)+
                " with currentValue "+currentValue);

        if (currentValue === undefined)
        {
            // https://developer.mozilla.org/en/Code_snippets/Preferences
            // This is the reason why you should usually pass strings ending with a dot to
            // getBranch(), like prefs.getBranch("accessibility.").
            var defaultBranch = prefService.getDefaultBranch(this.prefDomain+"."); //

            var type = this.getPreferenceTypeByExample(typeof(value));
            if (this.setPreference(name, value, type, defaultBranch))
                return true;
        }

        return false;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Options
    // TODO support per context options eg break on error

    initializePrefs: function()
    {
        for (var i = 0; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        prefs.addObserver(this.prefDomain, this, false);

        var basePrefNames = prefNames.length;

        for (var i = basePrefNames; i < prefNames.length; ++i)
            Firebug[prefNames[i]] = this.getPref(this.prefDomain, prefNames[i]);

        if (FBTrace.DBG_OPTIONS)
        {
             for (var i = 0; i < prefNames.length; ++i)
             {
                FBTrace.sysout("options.initialize option "+this.prefDomain+"."+prefNames[i]+"="+
                    Firebug[prefNames[i]]+"\n");
             }
        }
    },

    togglePref: function(name)
    {
        this.set(name, !this.get(name));
    },

    get: function(name)
    {
        return Options.getPref(this.prefDomain, name);
    },

    getPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;

        var type = prefs.getPrefType(prefName);

        var value = null;
        if (type == nsIPrefBranch.PREF_STRING)
            value = prefs.getCharPref(prefName);
        else if (type == nsIPrefBranch.PREF_INT)
            value = prefs.getIntPref(prefName);
        else if (type == nsIPrefBranch.PREF_BOOL)
            value = prefs.getBoolPref(prefName);

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.getPref "+prefName+" has type "+
                this.getPreferenceTypeName(type)+" and value "+value);

        return value;
    },

    getDefault: function(name)
    {
        return Options.getDefaultPref(this.prefDomain, name);
    },

    getDefaultPref: function(prefDomain, name)
    {
        var defaultPrefs = prefService.getDefaultBranch(prefDomain + ".");
        var type = defaultPrefs.getPrefType(name);

        var value = null;
        if (type == nsIPrefBranch.PREF_STRING)
            value = defaultPrefs.getCharPref(name);
        else if (type == nsIPrefBranch.PREF_INT)
            value = defaultPrefs.getIntPref(name);
        else if (type == nsIPrefBranch.PREF_BOOL)
            value = defaultPrefs.getBoolPref(name);

        if (FBTrace.DBG_OPTIONS)
        {
            FBTrace.sysout("options.getDefaultPref "+prefName+" has type "+
                this.getPreferenceTypeName(type)+" and value "+value);
        }

        return value;
    },

    set: function(name, value)
    {
        Options.setPref(Options.prefDomain, name, value);
    },

    /**
     * Set a preference value.
     *
     * @param prefDomain, e.g. "extensions.firebug"
     * @param name Name of the preference (the part after prfDomain without dot)
     * @param value New value for the preference.
     * @param prefType optional pref type useful when adding a new preference.
     */
    setPref: function(prefDomain, name, value, prefType)
    {
        var prefName = prefDomain + "." + name;

        var type = this.getPreferenceTypeByExample((prefType ? prefType : typeof(value)));
        if (!this.setPreference(prefName, value, type, prefs))
            return;

        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("options.setPref type="+type+" name="+prefName+" value="+value);
    },

    setPreference: function(prefName, value, type, prefBranch)
    {
        if (FBTrace.DBG_OPTIONS)
            FBTrace.sysout("setPreference "+prefName, {prefName: prefName, value: value});

        if (type == nsIPrefBranch.PREF_STRING)
            prefBranch.setCharPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INT)
            prefBranch.setIntPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_BOOL)
            prefBranch.setBoolPref(prefName, value);
        else if (type == nsIPrefBranch.PREF_INVALID)
        {
            FBTrace.sysout("options.setPref FAILS: Invalid preference "+prefName+" with type "+
                type+", check that it is listed in defaults/prefs.js");

            return false;
        }

        return true;
    },

    getPreferenceTypeByExample: function(prefType)
    {
        var type = nsIPrefBranch.PREF_INVALID;
        if (prefType)
        {
            if (prefType === typeof("s"))
                type = nsIPrefBranch.PREF_STRING;
            else if (prefType === typeof(1))
                type = nsIPrefBranch.PREF_INT;
            else if (prefType === typeof(true))
                type = nsIPrefBranch.PREF_BOOL;
        }
        else
        {
            type = prefs.getPrefType(prefName);
        }

        return type;
    },

    getPreferenceTypeName: function(prefType)
    {
        if (prefType == Ci.nsIPrefBranch.PREF_STRING)
            return "string";
        else if (prefType == Ci.nsIPrefBranch.PREF_INT)
            return "int";
        else if (prefType == Ci.nsIPrefBranch.PREF_BOOL)
            return "boolean";
    },

    clear: function(name)
    {
        Options.clearPref(Options.prefDomain, name);
    },

    clearPref: function(prefDomain, name)
    {
        var prefName = prefDomain + "." + name;
        if (prefs.prefHasUserValue(prefName))
            prefs.clearUserPref(prefName);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Firebug UI text zoom

    changeTextSize: function(amt)
    {
        var textSize = Options.get("textSize");
        var newTextSize = textSize + amt;
        if ((newTextSize < 0 && Math.abs(newTextSize) < this.negativeZoomFactors.length) ||
            (newTextSize >= 0 && textSize+amt < this.positiveZoomFactors.length))
        {
            this.setTextSize(textSize+amt);
        }
    },

    setTextSize: function(value)
    {
        var setValue = value;
        if (value >= this.positiveZoomFactors.length)
            setValue = this.positiveZoomFactors[this.positiveZoomFactors.length-1];
        else if (value < 0 && Math.abs(value) >= this.negativeZoomFactors.length)
            setValue = this.negativeZoomFactors[this.negativeZoomFactors.length-1];
        this.set("textSize", setValue);
    },

    positiveZoomFactors: [1, 1.1, 1.2, 1.3, 1.5, 2, 3],
    negativeZoomFactors: [1, 0.95, 0.8, 0.7, 0.5],

    getZoomByTextSize: function(value)
    {
        var zoom = value >= 0 ? this.positiveZoomFactors[value] :
            this.negativeZoomFactors[Math.abs(value)];

        return zoom;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    /**
     * Resets all Firebug options to default state. Note that every option
     * starting with "extensions.firebug" is considered as a Firebug option.
     *
     * Options starting with DBG_ are intended for Firebug Tracing Console (FBTrace)
     * and ignored (their state is not changed).
     */
    resetAllOptions: function()
    {
        var preferences = prefs.getChildList("extensions.firebug", {});
        for (var i = 0; i < preferences.length; i++)
        {
            if (preferences[i].indexOf("DBG_") == -1)
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Clearing option: " + i + ") " + preferences[i]);

                if (prefs.prefHasUserValue(preferences[i]))  // avoid exception
                    prefs.clearUserPref(preferences[i]);
            }
            else
            {
                if (FBTrace.DBG_OPTIONS)
                    FBTrace.sysout("Skipped clearing option: " + i + ") " + preferences[i]);
            }
        }
    },

    forceSave: function()
    {
        prefs.savePrefFile(null);
    }
};

// ********************************************************************************************* //
// Registration

return Options;

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


<commit_before>console.log('hello')

var lineData = {};
var routeParams = window.location.pathname.split("/");
var username = (routeParams[routeParams.length-1]);

if (username.toLowerCase() === 'userinfo') {
  username = "";
}

$.get( "/api/" + username, function( data ) {
  lineData = data.dailySteps;
  initChart(lineData);
});

function initChart(data) {
  //on resize, remove old chart
  d3.select("svg").remove();
  //insert new chart
  var canvas = d3.select("#main.card").append("svg");
  canvas.attr('id', 'visualisation');

  var vis = d3.select('#visualisation'),
      WIDTH = $('#visualisation').width(),
      HEIGHT = $('#visualisation').height(),
      MARGINS = {
        top: 20,
        right: 20,
        bottom: 20,
        left: 50
      },
      xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function(d, index) {
        return index;
      }), d3.max(lineData, function(d, index) {
        return index;
      })]),
      yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function(d) {
        return 0;
      }), d3.max(lineData, function(d) {
        return d.dailySteps;
      })]),
      xAxis = d3.svg.axis()
        .scale(xRange)
        .tickSize(5)
        .tickSubdivide(true),
      yAxis = d3.svg.axis()
        .scale(yRange)
        .tickSize(5)
        .orient('left')
        .tickSubdivide(true);

  vis.append('svg:g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')')
    .call(xAxis);

  vis.append('svg:g')
    .attr('class', 'y axis')
    .attr('transform', 'translate(' + (MARGINS.left) + ',0)')
    .call(yAxis);

  var lineFunc = d3.svg.line()
    .x(function(d, index) {
      return xRange(index);
    })
    .y(function(d) {
      return yRange(d.dailySteps);
    })
    // .interpolate('linear');

  vis.append('svg:path')
    .attr('d', lineFunc(lineData))
    .attr('stroke', 'blue')
    .attr('stroke-width', 2)
    .attr('fill', 'none');

}

$( window ).resize(function() {
  initChart(lineData);
});<commit_msg>only hit API for username routes<commit_after>console.log('hello')

var lineData = {};
var routeParams = window.location.pathname.split("/");

if (routeParams[routeParams.length-2].toLowerCase() === 'userinfo') {
var username = (routeParams[routeParams.length-1]);
    $.get( "/api/" + username, function( data ) {
    lineData = data.dailySteps;
    initChart(lineData);
  });
}

function initChart(data) {
  //on resize, remove old chart
  d3.select("svg").remove();
  //insert new chart
  var canvas = d3.select("#main.card").append("svg");
  canvas.attr('id', 'visualisation');

  var vis = d3.select('#visualisation'),
      WIDTH = $('#visualisation').width(),
      HEIGHT = $('#visualisation').height(),
      MARGINS = {
        top: 20,
        right: 20,
        bottom: 20,
        left: 50
      },
      xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function(d, index) {
        return index;
      }), d3.max(lineData, function(d, index) {
        return index;
      })]),
      yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function(d) {
        return 0;
      }), d3.max(lineData, function(d) {
        return d.dailySteps;
      })]),
      xAxis = d3.svg.axis()
        .scale(xRange)
        .tickSize(5)
        .tickSubdivide(true),
      yAxis = d3.svg.axis()
        .scale(yRange)
        .tickSize(5)
        .orient('left')
        .tickSubdivide(true);

  vis.append('svg:g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')')
    .call(xAxis);

  vis.append('svg:g')
    .attr('class', 'y axis')
    .attr('transform', 'translate(' + (MARGINS.left) + ',0)')
    .call(yAxis);

  var lineFunc = d3.svg.line()
    .x(function(d, index) {
      return xRange(index);
    })
    .y(function(d) {
      return yRange(d.dailySteps);
    })
    // .interpolate('linear');

  vis.append('svg:path')
    .attr('d', lineFunc(lineData))
    .attr('stroke', 'blue')
    .attr('stroke-width', 2)
    .attr('fill', 'none');

}

$( window ).resize(function() {
  initChart(lineData);
});<|endoftext|>


<commit_before>var socket = io.connect('http://vader.mapado.com');

function updatePlayer(player) {
    var playerDiv = $('#players .cloud:nth-child(' + player.position + ')');
    playerDiv.find('.username').text(player.name);
    playerDiv.find('.avatar img')
        .addClass('present')
        .attr('src', player.avatar);
}

function updateTitle(playerCount) {
    if (playerCount > 1) {
        $('#nb-places-restantes').text(playerCount);
    } else if (playerCount == 1){
        $('#titlestart').html("1 place");
    } else if (playerCount == -1){
        $('#pagetitle').text("Desole, le jeu est complet !");
    } else {
        $('#pagetitle').text("C'est parti!");
    }
}

socket.on('welcome', function (data) {
    console.log(data);
});

socket.on('player list', function (playerList) {
    newPlayerCount = 5 - playerList.length;
    if (newPlayerCount == 0) {
        updateTitle(-1);
        $('#username-content').hide();
        $('#login-select').hide();
    } else {
        updateTitle(newPlayerCount);
    }

    for (i in playerList) {
        updatePlayer(playerList[i]);
    }
});

socket.on('new player', function (player) {
    oldPlayerCount = $('#nb-places-restantes').text();
    newPlayerCount = oldPlayerCount - 1;
    updateTitle(newPlayerCount);
    console.log('new player', player);
    updatePlayer(player);
});

socket.on('character spawned', function (data) {
    console.log(data);
});

socket.on('player updated', function (player) {
    console.log('player updated', player);
    updatePlayer(player);
});

// Hide the username text input after having joined the game
socket.on('game full', function () {
    updateTitle(-1);
    $('#username-content').hide();
    $('#login-select').hide();
});

socket.on('game stop', function () {
    console.log("GAME STOP");
});

$(function() {
    $('.twitter-connect, .connect').on('click', function () {
        if ($(this).hasClass('twitter-connect')) {
            $('#isTwitter').val('1');
        } else {
            $('#isTwitter').val('0');
        }
        $('#username-content').show();
        $('#login-select').hide();
        $('#username').select();

        return false;
    });

    $('#username-content').on('submit', function () {
        // lets connect to the user
        socket.emit(
            'logged in',
            {
                'name': $('#username').val(),
                'isTwitter': $('#isTwitter').val() == '1'
            }
        )

        $('#username-content').hide();

        return false;
    });
});
<commit_msg>@twitterusername of name<commit_after>var socket = io.connect('http://vader.mapado.com');

function updatePlayer(player) {
    var playerDiv = $('#players .cloud:nth-child(' + player.position + ')');
    playerDiv.find('.username').text(player.name);
    playerDiv.find('.avatar img')
        .addClass('present')
        .attr('src', player.avatar);
}

function updateTitle(playerCount) {
    if (playerCount > 1) {
        $('#nb-places-restantes').text(playerCount);
    } else if (playerCount == 1){
        $('#titlestart').html("1 place");
    } else if (playerCount == -1){
        $('#pagetitle').text("Desole, le jeu est complet !");
    } else {
        $('#pagetitle').text("C'est parti!");
    }
}

socket.on('welcome', function (data) {
    console.log(data);
});

socket.on('player list', function (playerList) {
    newPlayerCount = 5 - playerList.length;
    if (newPlayerCount == 0) {
        updateTitle(-1);
        $('#username-content').hide();
        $('#login-select').hide();
    } else {
        updateTitle(newPlayerCount);
    }

    for (i in playerList) {
        updatePlayer(playerList[i]);
    }
});

socket.on('new player', function (player) {
    oldPlayerCount = $('#nb-places-restantes').text();
    newPlayerCount = oldPlayerCount - 1;
    updateTitle(newPlayerCount);
    console.log('new player', player);
    updatePlayer(player);
});

socket.on('character spawned', function (data) {
    console.log(data);
});

socket.on('player updated', function (player) {
    console.log('player updated', player);
    updatePlayer(player);
});

// Hide the username text input after having joined the game
socket.on('game full', function () {
    updateTitle(-1);
    $('#username-content').hide();
    $('#login-select').hide();
});

socket.on('game stop', function () {
    console.log("GAME STOP");
});

$(function() {
    $('.twitter-connect, .connect').on('click', function () {
        $('#username-content').show();
        $('#login-select').hide();
        $('#username').select();

        return false;
    });

    $('#username-content').on('submit', function () {
        // lets connect to the user
        username = $('#username').val()
        isTwitter = username[0] == '@'

        // remove @ from twitter username
        if (isTwitter) {
            username = username.slice(1)
        }
        socket.emit(
            'logged in',
            {
                'name': username,
                'isTwitter': isTwitter,
            }
        )

        $('#username-content').hide();

        return false;
    });
});
<|endoftext|>