<commit_before>var Firebase = require('firebase');

var ref = new Firebase('https://sagavera.firebaseio.com');
var rand = Math.random;
var TDIFF;

console.time('timestamp');
ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
	ref.child('test/ts').once('value', function(ss){
		TDIFF = Date.now() - ss.val();
		console.timeEnd('timestamp');
		console.log('timedifference',TDIFF);
		// fine to know when exactly is firebase ready :)
		// also getting exact server time is benefitial as well
		_start();
	});
});

function _start(){
/*
ref.child('test')
.on('child_added', function(ss){
	console.log("listener on root : ", ss.exportVal());
});

*/
ref.child('test/first/second/third/fourth/fifth')
.on('child_moved', function(ss){
	console.timeEnd('sv');
	console.log("listener for fifth: ", ss.exportVal());
});

/*
// change something deep nested
setTimeout(function(){
	console.log(" new obj writing to 5. level...");
	ref.child('test').child('first/second/third/fourth/fifth')
	.set({prop1: rand(), prop2:rand()}, function(err){
	});
}, 4000);

// ad something deep nested
setTimeout(function(){
	console.log("new prop writing at 5. level... ");
	ref.child('test').child('first/second/third/fourth/fifth/prop3')
	.set(rand(), function(err){
	});
}, 5000);

// add something at the same level
setTimeout(function(){
	console.log("new prop writing at 3. level... ");
	ref.child('test').child('first/second/third/prop3')
	.set(rand(), function(err){
	});
}, 6000);
*/

setTimeout(function(){
	console.log("priority ...");
	console.time('sv');
	ref.child('test').child('first/second/third/fourth/fifth/prop2')
	.setPriority(TDIFF + Date.now());
}, 3000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test').child('first/second/third/fourth/fifth/prop3')
	.setPriority(TDIFF + Date.now());
}, 3100);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test').child('first/second/third/fourth/fifth/prop1')
	.setPriority(TDIFF + Date.now());
}, 3200);
/*
*/

/*
setTimeout(function(){
	console.log("priority ...");
	console.time('sv');
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop2')
			.setPriority(ss.val());
		});
	});
}, 2000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop3')
			.setPriority(ss.val());
		});
	});
}, 3000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop1')
			.setPriority(ss.val());
		});
	});
}, 4000);
*/
/*
setTimeout(function(){
	ref.child('test').child('first/second/third/fourth')
	.set({s1: "prve", s2:"druhe"}, function(err){
		console.log("... written");
	});
}, 6000);
*/

/*
conclusion:

child added
to get triggered something needs to be added at the same level as the listener is set
so when child is added at the deeper level this will not get triggered
note: child_added is triggered as many times for the first time as there is a items in that level
needs to be limited to last.

value:
is triggered whenever anything is changed within the location, even in deep nested level
snapshot always returns the whole location even of only one thing is changed deep nested inside

child_changed regarding priority
listening on the same level returns the child which changed priority regardess the ordering effect
ding the same with child_moved - triggers event only if reordered
child_changed returns as well the whole object from listened location if the priority of some nested child changes

however - when using Firebase ServerValue.TIMESTAMP as priority
the process is as follows
prioroty is replaced with placeholder, and the callback is immediatelly fired (where is the priority from I have no idea)
right after the Server replace the placeholder with timestamp the event is triggered again showing the correct timestamp

*/

}
<commit_msg>done with this<commit_after>var Firebase = require('firebase');

var ref = new Firebase('https://sagavera.firebaseio.com');
var rand = Math.random;
var TDIFF;

console.time('timestamp');
ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
	ref.child('test/ts').once('value', function(ss){
		TDIFF = Date.now() - ss.val();
		console.timeEnd('timestamp');
		console.log('timedifference',TDIFF);
		// fine to know when exactly is firebase ready :)
		// also getting exact server time is benefitial as well
		_start();
	});
});

function _start(){
/*
ref.child('test')
.on('child_added', function(ss){
	console.log("listener on root : ", ss.exportVal());
});

*/
ref.child('test/first/second/third/fourth/fifth')
.on('child_moved', function(ss){
	console.timeEnd('sv');
	console.log("listener for fifth: ", ss.exportVal());
});

/*
// change something deep nested
setTimeout(function(){
	console.log(" new obj writing to 5. level...");
	ref.child('test').child('first/second/third/fourth/fifth')
	.set({prop1: rand(), prop2:rand()}, function(err){
	});
}, 4000);

// ad something deep nested
setTimeout(function(){
	console.log("new prop writing at 5. level... ");
	ref.child('test').child('first/second/third/fourth/fifth/prop3')
	.set(rand(), function(err){
	});
}, 5000);

// add something at the same level
setTimeout(function(){
	console.log("new prop writing at 3. level... ");
	ref.child('test').child('first/second/third/prop3')
	.set(rand(), function(err){
	});
}, 6000);
*/

setTimeout(function(){
	console.log("priority ...");
	console.time('sv');
	ref.child('test').child('first/second/third/fourth/fifth/prop2')
	.setPriority(TDIFF + Date.now());
}, 3000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test').child('first/second/third/fourth/fifth/prop3')
	.setPriority(TDIFF + Date.now());
}, 3100);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test').child('first/second/third/fourth/fifth/prop1')
	.setPriority(TDIFF + Date.now());
}, 3200);
/*
*/

/*
setTimeout(function(){
	console.log("priority ...");
	console.time('sv');
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop2')
			.setPriority(ss.val());
		});
	});
}, 2000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop3')
			.setPriority(ss.val());
		});
	});
}, 3000);
setTimeout(function(){
	console.log("priority ...");
	ref.child('test/ts').set(Firebase.ServerValue.TIMESTAMP, function(err){
		ref.child('test/ts').once('value', function(ss){
			ref.child('test').child('first/second/third/fourth/fifth/prop1')
			.setPriority(ss.val());
		});
	});
}, 4000);
*/
/*
setTimeout(function(){
	ref.child('test').child('first/second/third/fourth')
	.set({s1: "prve", s2:"druhe"}, function(err){
		console.log("... written");
	});
}, 6000);
*/

/*
conclusion:

child added
to get triggered something needs to be added at the same level as the listener is set
so when child is added at the deeper level this will not get triggered
note: child_added is triggered as many times for the first time as there is a items in that level
needs to be limited to last.

value:
is triggered whenever anything is changed within the location, even in deep nested level
snapshot always returns the whole location even of only one thing is changed deep nested inside

child_changed regarding priority
listening on the same level returns the child which changed priority regardess the ordering effect
ding the same with child_moved - triggers event only if reordered
child_changed returns as well the whole object from listened location if the priority of some nested child changes

however - when using Firebase ServerValue.TIMESTAMP as priority
the process is as follows
prioroty is replaced with placeholder, and the callback is immediatelly fired (where is the priority from I have no idea) as the write op is very fast (about 4ms)
right after the Server replace the placeholder with timestamp (350ms) the event is triggered again showing the correct timestamp

*/

}
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
import { PrismAsyncLight as SyntaxHighlighter} from '../src';
import clike from '../languages/prism/clike';
import markup from '../languages/prism/markup';
import markupTemplating from '../languages/prism/markup-templating';
import ExamplesLinks from './examples-links';

SyntaxHighlighter.registerLanguage('markup', markup);
SyntaxHighlighter.registerLanguage('markup-templating', markupTemplating);
SyntaxHighlighter.registerLanguage('clike', clike);

const availableStyles = [
  // TODO: Generate list
];

const availableLanguages = [
  'text',
  'javascript',
  'java',
  'yaml'
]

class Component extends React.Component {
  constructor() {
    super();
    const initialCodeString = `function createStyleObject(classNames, style) {
  return classNames.reduce((styleObject, className) => {
    return {...styleObject, ...style[className]};
  }, {});
}

function createClassNameString(classNames) {
  return classNames.join(' ');
}

function createChildren(style, useInlineStyles) {
  let childrenCount = 0;
  return children => {
    childrenCount += 1;
    return children.map((child, i) => createElement({
      node: child,
      style,
      useInlineStyles,
      key:\`code-segment-$\{childrenCount}-$\{i}\`
    }));
  }
}

function createElement({ node, style, useInlineStyles, key }) {
  const { properties, type, tagName, value } = node;
  if (type === "text") {
    return value;
  } else if (tagName) {
    const TagName = tagName;
    const childrenCreator = createChildren(style, useInlineStyles);
    const props = (
      useInlineStyles
      ?
      { style: createStyleObject(properties.className, style) }
      :
      { className: createClassNameString(properties.className) }
    );
    const children = childrenCreator(node.children);
    return <TagName key={key} {...props}>{children}</TagName>;
  }
}
  `;
    this.state = {
      selected: 'atom-dark',
      style: require('../styles/prism/atom-dark').default,
      code: initialCodeString,
      showLineNumbers: false,
      language: 'text'
    }
  }

  render() {
    const h1Style = {
      fontSize: 42,
      color: 'aliceblue'
    };
    const h2 = {
      fontSize: 24,
      color: 'aliceblue'
    }

    return (

React Syntax Highlighter Prism Async Light

        <ExamplesLinks />
        {/*
Change Style

        <select
          value={this.state.selected}
          onChange={(e) => this.setState({style: require(`../styles/prism/${e.target.value}`).default, selected: e.target.value})}
        >
          {availableStyles.map(s => <option key={s} value={s}>{s}</option>)}
        </select> */}

Change Language

        <select
          value={this.state.language}
          onChange={(e) => this.setState({language: e.target.value})}
        >
          {availableLanguages.map(s => <option key={s} value={s}>{s}</option>)}
        </select>

          Show Line Numbers:
          <input
            type="checkbox"
            checked={this.state.showLineNumbers}
            onChange={() => this.setState({ showLineNumbers: !this.state.showLineNumbers })}
            id="showLineNumbers"
          />

          <textarea
            style={{flex: 1, marginTop: 11}}
            rows={40}
            cols={100}
            value={this.state.code}
            onChange={(e) => this.setState({code: e.target.value})}
          />

            <SyntaxHighlighter
              style={this.state.style}
              showLineNumbers={this.state.showLineNumbers}
              wrapLines={true}
              lineProps={(lineNumber) => ({
                style: { display: "block", cursor: "pointer" },
                onClick() {
                  alert(`Line Number Clicked: ${lineNumber}`);
                }
              })}
              language={this.state.language}
            >
              {this.state.code}
            </SyntaxHighlighter>

    );
  }
}

render(<Component />, document.getElementById('app'));
<commit_msg>fix broken import<commit_after>import React from 'react';
import { render } from 'react-dom';
import SyntaxHighlighter from '../src/prism-async-light';
import clike from '../languages/prism/clike';
import markup from '../languages/prism/markup';
import markupTemplating from '../languages/prism/markup-templating';
import ExamplesLinks from './examples-links';

SyntaxHighlighter.registerLanguage('markup', markup);
SyntaxHighlighter.registerLanguage('markup-templating', markupTemplating);
SyntaxHighlighter.registerLanguage('clike', clike);

const availableStyles = [
  // TODO: Generate list
];

const availableLanguages = [
  'text',
  'javascript',
  'java',
  'yaml'
]

class Component extends React.Component {
  constructor() {
    super();
    const initialCodeString = `function createStyleObject(classNames, style) {
  return classNames.reduce((styleObject, className) => {
    return {...styleObject, ...style[className]};
  }, {});
}

function createClassNameString(classNames) {
  return classNames.join(' ');
}

function createChildren(style, useInlineStyles) {
  let childrenCount = 0;
  return children => {
    childrenCount += 1;
    return children.map((child, i) => createElement({
      node: child,
      style,
      useInlineStyles,
      key:\`code-segment-$\{childrenCount}-$\{i}\`
    }));
  }
}

function createElement({ node, style, useInlineStyles, key }) {
  const { properties, type, tagName, value } = node;
  if (type === "text") {
    return value;
  } else if (tagName) {
    const TagName = tagName;
    const childrenCreator = createChildren(style, useInlineStyles);
    const props = (
      useInlineStyles
      ?
      { style: createStyleObject(properties.className, style) }
      :
      { className: createClassNameString(properties.className) }
    );
    const children = childrenCreator(node.children);
    return <TagName key={key} {...props}>{children}</TagName>;
  }
}
  `;
    this.state = {
      selected: 'atom-dark',
      style: require('../styles/prism/atom-dark').default,
      code: initialCodeString,
      showLineNumbers: false,
      language: 'text'
    }
  }

  render() {
    const h1Style = {
      fontSize: 42,
      color: 'aliceblue'
    };
    const h2 = {
      fontSize: 24,
      color: 'aliceblue'
    }

    return (

React Syntax Highlighter Prism Async Light

        <ExamplesLinks />
        {/*
Change Style

        <select
          value={this.state.selected}
          onChange={(e) => this.setState({style: require(`../styles/prism/${e.target.value}`).default, selected: e.target.value})}
        >
          {availableStyles.map(s => <option key={s} value={s}>{s}</option>)}
        </select> */}

Change Language

        <select
          value={this.state.language}
          onChange={(e) => this.setState({language: e.target.value})}
        >
          {availableLanguages.map(s => <option key={s} value={s}>{s}</option>)}
        </select>

          Show Line Numbers:
          <input
            type="checkbox"
            checked={this.state.showLineNumbers}
            onChange={() => this.setState({ showLineNumbers: !this.state.showLineNumbers })}
            id="showLineNumbers"
          />

          <textarea
            style={{flex: 1, marginTop: 11}}
            rows={40}
            cols={100}
            value={this.state.code}
            onChange={(e) => this.setState({code: e.target.value})}
          />

            <SyntaxHighlighter
              style={this.state.style}
              showLineNumbers={this.state.showLineNumbers}
              wrapLines={true}
              lineProps={(lineNumber) => ({
                style: { display: "block", cursor: "pointer" },
                onClick() {
                  alert(`Line Number Clicked: ${lineNumber}`);
                }
              })}
              language={this.state.language}
            >
              {this.state.code}
            </SyntaxHighlighter>

    );
  }
}

render(<Component />, document.getElementById('app'));
<|endoftext|>


<commit_before>var dp = jQuery;
dp.noConflict();
dp(document).ready(function() {

    //SMOOTH SCROLL
    dp('a[href^="#"]').bind('click.smoothscroll', function(e) {
        e.preventDefault();
        dp('html,body').animate({
            scrollTop: dp(this.hash).offset().top
        }, 1200);
    });

    //SUPER SLIDES
    dp('#home-slide').superslides({
        animation: 'fade', // You can choose either fade or slide
        play: 6000
    });

    //ANIMAZE
    dp('.animaze').bind('inview', function(event, visible) {
        if (visible) {
            dp(this).stop().animate({
                opacity: 1,
                top: '0px'
            }, 500);
        }
        /* REMOVE THIS if you want to repeat the animation after the element not in view
              else {
                $(this).stop().animate({ opacity: 0 });
                $(this).removeAttr('style');
              }*/
    });
    dp('.animaze').stop().animate({
        opacity: 0
    });

    //SERVICES
    dp("#dp-service").sudoSlider({
        customLink: 'a.servicesLink',
        responsive: true,
        speed: 350,
        prevNext: false,
        useCSS: true,
        effect: "fadeOutIn",
        continuous: true,
        updateBefore: true
    });

    //TEXT ROTATOR
    dp(".rotatez").textrotator({
        animation: "fade",
        separator: ",",
        speed: 1700
    });

    //PORTFOLIO
    dp('.portfolioContainer').mixitup({
        filterSelector: '.portfolioFilter a',
        targetSelector: '.portfolio-item',
        effects: ['fade', 'scale']
    });

    //QUOTE SLIDE
    dp("#quote-slider").sudoSlider({
        customLink: 'a.quoteLink',
        speed: 425,
        prevNext: true,
        responsive: true,
        prevHtml: '',
        nextHtml: '',
        useCSS: true,
        continuous: true,
        effect: "fadeOutIn",
        updateBefore: true
    });

    //MAGNIFIC POPUP
    dp('.popup').magnificPopup({
        type: 'image'
    });

    //PARALLAX
    dp('.parallaxize').parallax("50%", 0.3);

    // CONTACT SLIDER
    dp("#contact-slider").sudoSlider({
        customLink: 'a.contactLink',
        speed: 750,
        responsive: true,
        prevNext: false,
        useCSS: false,
        continuous: false,
        updateBefore: true,
        effect: "fadeOutIn"
    });

    //Map
    dp('#map').gmap3({
            map: {
                options: {
                    maxZoom: 15
                }
            },
            marker: {
                address: "Haltern am See, Weseler Str. 151", // PUT YOUR ADDRESS HERE
                options: {
                    icon: new google.maps.MarkerImage(
                        "http://cdn.webiconset.com/map-icons/images/pin6.png",
                        new google.maps.Size(42, 69, "px", "px")
                    )
                }
            }
        },
        "autofit");
});
dp(window).load(function() {
    dp("#lazyload").fadeOut();
});
<commit_msg>improved the way that user info is sent and recived<commit_after>var dp = jQuery;
dp.noConflict();
dp(document).ready(function() {

    //SMOOTH SCROLL
    dp('a[href^="#"]').bind('click.smoothscroll', function(e) {
        e.preventDefault();
        dp('html,body').animate({
            scrollTop: dp(this.hash).offset().top
        }, 1200);
    });

    //SUPER SLIDES
//    dp('#home-slide').superslides({
//        animation: 'fade', // You can choose either fade or slide
//        play: 6000
//    });

    //ANIMAZE
    dp('.animaze').bind('inview', function(event, visible) {
        if (visible) {
            dp(this).stop().animate({
                opacity: 1,
                top: '0px'
            }, 500);
        }
        /* REMOVE THIS if you want to repeat the animation after the element not in view
              else {
                $(this).stop().animate({ opacity: 0 });
                $(this).removeAttr('style');
              }*/
    });
    dp('.animaze').stop().animate({
        opacity: 0
    });

    //SERVICES
    dp("#dp-service").sudoSlider({
        customLink: 'a.servicesLink',
        responsive: true,
        speed: 350,
        prevNext: false,
        useCSS: true,
        effect: "fadeOutIn",
        continuous: true,
        updateBefore: true
    });

    //TEXT ROTATOR
    dp(".rotatez").textrotator({
        animation: "fade",
        separator: ",",
        speed: 1700
    });

    //PORTFOLIO
    dp('.portfolioContainer').mixitup({
        filterSelector: '.portfolioFilter a',
        targetSelector: '.portfolio-item',
        effects: ['fade', 'scale']
    });

    //QUOTE SLIDE
    dp("#quote-slider").sudoSlider({
        customLink: 'a.quoteLink',
        speed: 425,
        prevNext: true,
        responsive: true,
        prevHtml: '',
        nextHtml: '',
        useCSS: true,
        continuous: true,
        effect: "fadeOutIn",
        updateBefore: true
    });

    //MAGNIFIC POPUP
    dp('.popup').magnificPopup({
        type: 'image'
    });

    //PARALLAX
    dp('.parallaxize').parallax("50%", 0.3);

    // CONTACT SLIDER
    dp("#contact-slider").sudoSlider({
        customLink: 'a.contactLink',
        speed: 750,
        responsive: true,
        prevNext: false,
        useCSS: false,
        continuous: false,
        updateBefore: true,
        effect: "fadeOutIn"
    });

    //Map
    dp('#map').gmap3({
            map: {
                options: {
                    maxZoom: 15
                }
            },
            marker: {
                address: "Haltern am See, Weseler Str. 151", // PUT YOUR ADDRESS HERE
                options: {
                    icon: new google.maps.MarkerImage(
                        "http://cdn.webiconset.com/map-icons/images/pin6.png",
                        new google.maps.Size(42, 69, "px", "px")
                    )
                }
            }
        },
        "autofit");
});
dp(window).load(function() {
    dp("#lazyload").fadeOut();
});
<|endoftext|>


<commit_before>ig.module(
  'game.entities.soldier'
).requires(
  'impact.entity'
).defines(function() {

EntitySoldier = ig.Entity.extend({
  size: {x: 128, y: 64}
  , animSheet: new ig.AnimationSheet('media/man_run.png', 64, 64)
  , accelWalk: 800
  , type: ig.Entity.TYPE.B
  , checkAgainst: ig.Entity.TYPE.A

  , init: function(x, y, settings) {
	this.parent(x, y, settings);

	this.addAnim('idle', .2, [0, 1, 0]);
	this.addAnim( 'walkleft', 0.4, [0,1,0] );
	this.addAnim( 'walkright', 0.4, [0,1,0] );
	this.addAnim( 'dead', 1, [1]);
	this.humanMove = Math.floor(Math.random() * 20) +1;
	this.timer = new ig.Timer(1);
	this.movin = 0;
  }

	, update: function() {
	var accel = this.accelWalk
		, playa = ig.player.pos.x
		, dist = this.distanceTo(ig.player)
		, soldier = this.pos.x;

	if (soldier > playa) {
		this.currentAnim = this.anims.walkleft;
		this.accel.x = -accel;

		if(dist < 300) {
console.log(dist);
			this.currentAnim = this.anims.idle;
			this.accel.x = 0;
			return;

		}
	}

	else if (soldier > playa && dist > 300) {
		this.currentAnim = this.anims.walkright;
		this.accel.x = accel;

	} else if (dist < 300) {
		this.currentAnim = this.anims.idle;
		this.accel.x = 0;

		if(dist < 300) {
			this.currentAnim = this.anims.idle;
			this.accel.x = 0;

		}
	}

	this.parent();
  }

  , check: function(other) {
		this.kill();
  }

	});
});
<commit_msg>soldier stops!<commit_after>ig.module(
  'game.entities.soldier'
).requires(
  'impact.entity'
).defines(function() {

EntitySoldier = ig.Entity.extend({
  size: {x: 128, y: 64}
  , animSheet: new ig.AnimationSheet('media/man_run.png', 64, 64)
  , accelWalk: 800
  , type: ig.Entity.TYPE.B
  , checkAgainst: ig.Entity.TYPE.A

  , init: function(x, y, settings) {
	this.parent(x, y, settings);

	this.addAnim('idle', .2, [0,1,0]);
	this.addAnim( 'walkleft', 0.07, [0,1,0] );
	this.addAnim( 'walkright', 0.7, [0,1,0] );
	this.addAnim( 'dead', 1, [1]);
	this.humanMove = Math.floor(Math.random() * 20) +1;
	this.timer = new ig.Timer(1);
	this.movin = 0;
  }

	, update: function() {
	var accel = this.accelWalk
		, playa = ig.player.pos.x
		, dist = this.distanceTo(ig.player)
		, soldier = this.pos.x;

	if (soldier > playa) {
		var totes = soldier - playa;

		this.currentAnim = this.anims.walkleft;
		this.accel.x = -accel;

		if(totes < 300) {
console.log(dist);
			this.currentAnim = this.anims.idle;
			this.accel.x = 0;
			return;

		}
	}

	else if (soldier < playa) {
		this.currentAnim = this.anims.walkright;
		this.accel.x = accel;

	} else if (dist < 300) {
		this.currentAnim = this.anims.idle;
		this.accel.x = 0;

		if(dist < 300) {
			this.currentAnim = this.anims.idle;
			this.accel.x = 0;

		}
	}

	this.parent();
  }

  , check: function(other) {
		this.kill();
  }

	});
});
<|endoftext|>


<commit_before>define(function(require) {
  "use strict";

  describe("Simple tests examples", function() {
    it("should detect true", function() {
      assert.equal(true, true);
    });

    it("should increments values", function() {
      var mike = 0;

      assert.equal(mike++ === 0, true);
      assert.equal(mike === 1, true);
    });

    it("should increments values (improved)", function() {
      var mike = 0;

      assert.equal(mike++, 0);
      assert.equal(mike, 1);
    });
  });

  describe("Tests with before/after hooks", function() {
    var a = 0;

    beforeEach(function() {
      a++;
    });

    afterEach(function() {
      a = 0
    });

    it("should increment value", function() {
      assert.equal(a, 1);
    });

    it("should reset after each test", function() {
      assert.equal(a, 1);
    });
  });

  describe("Async tests", function() {
    it("should wait timer", function(done) {
      setTimeout(function() {
        assert.equal(true, true);
        done();
      }, 500);
    });
  });
});
<commit_msg>NAM-46 開発基盤:CI環境作成<commit_after><|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { List } from 'immutable';
import { OpponentHand, MinionsOnBoard, BoardSide, Minion } from 'components';

export default class Opponent extends Component {
  static propTypes = {
    name: PropTypes.string,
    handCount: PropTypes.number,
    deckCount: PropTypes.number,
    board: PropTypes.instanceOf(List),
  }

  render() {
    const { name, handCount, board } = this.props;
    const styles = require('./Opponent.scss');

    const minions = board.map((card, index) => (
      <Minion key={index} card={card} />
    ));

    return (

          { name || 'Unnamed' }

          <OpponentHand handCount={handCount} />

        <BoardSide>
          <MinionsOnBoard>
            { minions }
          </MinionsOnBoard>
        </BoardSide>

    );
  }
}
<commit_msg>Turn Opponent in stateless func<commit_after>import React, { PropTypes } from 'react';
import { List } from 'immutable';
import { OpponentHand, MinionsOnBoard, BoardSide, Minion } from 'components';

const Opponent = ({ name, handCount, board }) => {
  const styles = require('./Opponent.scss');

  const minions = board.map((card, index) => (
    <Minion key={index} card={card} />
  ));

  return (

        { name || 'Unnamed' }

        <OpponentHand handCount={handCount} />

      <BoardSide>
        <MinionsOnBoard>
          { minions }
        </MinionsOnBoard>
      </BoardSide>

  );
};

Opponent.propTypes = {
  name: PropTypes.string,
  handCount: PropTypes.number,
  deckCount: PropTypes.number,
  board: PropTypes.instanceOf(List),
};

export default Opponent;
<|endoftext|>


<commit_before>function sonyTVPowerOn() {
    $.ajax({
        type: "POST",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: {
            "displays": [{
                "name": "dp1",
                "power": "on"
            }]
        },
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}

function sonyTVPowerOff() {
    $.ajax({
        type: "POST",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: {
            "displays": [{
                "name": "dp1",
                "power": "off"
            }]
        },
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}

function switchInput(inputName) {
    var inputBody = {
        "currentVideoInput": inputName
    };

    $.ajax({
        type: "PUT",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(inputBody),
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}
<commit_msg>Changing a couple POSTs to PUTs<commit_after>function sonyTVPowerOn() {
    $.ajax({
        type: "PUT",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: {
            "displays": [{
                "name": "dp1",
                "power": "on"
            }]
        },
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}

function sonyTVPowerOff() {
    $.ajax({
        type: "PUT",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: {
            "displays": [{
                "name": "dp1",
                "power": "off"
            }]
        },
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}

function switchInput(inputName) {
    var inputBody = {
        "currentVideoInput": inputName
    };

    $.ajax({
        type: "PUT",
        url: "http://localhost:8000/buildings/ITB/rooms/1110",
        headers: {
            'Access-Control-Allow-Origin': '*'
        },
        data: JSON.stringify(inputBody),
        success: sweetAlert("Yay!", "Command sent successfully!", "success"),
        contentType: "application/json; charset=utf-8"
    });
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var l10n = require('gcli/l10n');
var types = require('gcli/types');

var Conversion = types.Conversion;
var Type = types.Type;
var Status = types.Status;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  types.registerType(JavascriptType);
};

exports.shutdown = function() {
  types.unregisterType(JavascriptType);
};

/**
 * The object against which we complete, which is usually 'window' if it exists
 * but could be something else in non-web-content environments.
 */
var globalObject;
if (typeof window !== 'undefined') {
  globalObject = window;
}

/**
 * Setter for the object against which JavaScript completions happen
 */
exports.setGlobalObject = function(obj) {
  globalObject = obj;
};

/**
 * Getter for the object against which JavaScript completions happen, for use
 * in testing
 */
exports.getGlobalObject = function() {
  return globalObject;
};

/**
 * Remove registration of object against which JavaScript completions happen
 */
exports.unsetGlobalObject = function() {
  globalObject = undefined;
};

/**
 * 'javascript' handles scripted input
 */
function JavascriptType(typeSpec) {
  if (typeSpec != null) {
    throw new Error('JavascriptType can not be customized');
  }
}

JavascriptType.prototype = Object.create(Type.prototype);

JavascriptType.prototype.stringify = function(value) {
  if (value == null) {
    return '';
  }
  return value;
};

/**
 * When sorting out completions, there is no point in displaying millions of
 * matches - this the number of matches that we aim for
 */
JavascriptType.MAX_COMPLETION_MATCHES = 10;

JavascriptType.prototype.parse = function(arg) {
  var typed = arg.text;
  var scope = globalObject;

  // Analyze the input text and find the beginning of the last part that
  // should be completed.
  var beginning = this._findCompletionBeginning(typed);

  // There was an error analyzing the string.
  if (beginning.err) {
    return new Conversion(typed, arg, Status.ERROR, beginning.err);
  }

  // If the current state is not ParseState.NORMAL, then we are inside of a
  // string which means that no completion is possible.
  if (beginning.state !== ParseState.NORMAL) {
    return new Conversion(typed, arg, Status.INCOMPLETE, '');
  }

  var completionPart = typed.substring(beginning.startPos);
  var properties = completionPart.split('.');
  var matchProp;
  var prop;

  if (properties.length > 1) {
    matchProp = properties.pop().trimLeft();
    for (var i = 0; i < properties.length; i++) {
      prop = properties[i].trim();

      // We can't complete on null.foo, so bail out
      if (scope == null) {
        return new Conversion(typed, arg, Status.ERROR,
                l10n.lookup('jstypeParseScope'));
      }

      if (prop === '') {
        return new Conversion(typed, arg, Status.INCOMPLETE, '');
      }

      // Check if prop is a getter function on 'scope'. Functions can change
      // other stuff so we can't execute them to get the next object. Stop here.
      if (this._isSafeProperty(scope, prop)) {
        return new Conversion(typed, arg);
      }

      try {
        scope = scope[prop];
      }
      catch (ex) {
        // It would be nice to be able to report this error in some way but
        // as it can happen just when someone types '{sessionStorage.', it
        // almost doesn't really count as an error, so we ignore it
        return new Conversion(typed, arg, Status.INCOMPLETE, '');
      }
    }
  }
  else {
    matchProp = properties[0].trimLeft();
  }

  // If the reason we just stopped adjusting the scope was a non-simple string,
  // then we're not sure if the input is valid or invalid, so accept it
  if (prop && !prop.match(/^[0-9A-Za-z]*$/)) {
    return new Conversion(typed, arg);
  }

  // However if the prop was a simple string, it is an error
  if (scope == null) {
    return new Conversion(typed, arg, Status.ERROR,
        l10n.lookupFormat('jstypeParseMissing', [ prop ]));
  }

  // If the thing we're looking for isn't a simple string, then we're not going
  // to find it, but we're not sure if it's valid or invalid, so accept it
  if (!matchProp.match(/^[0-9A-Za-z]*$/)) {
    return new Conversion(typed, arg);
  }

  // Skip Iterators and Generators.
  if (this._isIteratorOrGenerator(scope)) {
    return null;
  }

  var matchLen = matchProp.length;
  var prefix = matchLen === 0 ? typed : typed.slice(0, -matchLen);
  var status = Status.INCOMPLETE;
  var message = '';

  // We really want an array of matches (for sorting) but it's easier to
  // detect existing members if we're using a map initially
  var matches = {};

  // We only display a maximum of MAX_COMPLETION_MATCHES, so there is no point
  // in digging up the prototype chain for matches that we're never going to
  // use. Initially look for matches directly on the object itself and then
  // look up the chain to find more
  var distUpPrototypeChain = 0;
  var root = scope;
  try {
    while (root != null &&
        Object.keys(matches).length < JavascriptType.MAX_COMPLETION_MATCHES) {

      Object.keys(root).forEach(function(property) {
        // Only add matching properties. Also, as we're walking up the
        // prototype chain, properties on 'higher' prototypes don't override
        // similarly named properties lower down
        if (property.indexOf(matchProp) === 0 && !(property in matches)) {
          matches[property] = {
            prop: property,
            distUpPrototypeChain: distUpPrototypeChain
          };
        }
      });

      distUpPrototypeChain++;
      root = Object.getPrototypeOf(root);
    }
  }
  catch (ex) {
    return new Conversion(typed, arg, Status.INCOMPLETE, '');
  }

  // Convert to an array for sorting, and while we're at it, note if we got
  // an exact match so we know that this input is valid
  matches = Object.keys(matches).map(function(property) {
    if (property === matchProp) {
      status = Status.VALID;
    }
    return matches[property];
  });

  // The sort keys are:
  // - Being on the object itself, not in the prototype chain
  // - The lack of existence of a vendor prefix
  // - The name
  matches.sort(function(m1, m2) {
    if (m1.distUpPrototypeChain !== m2.distUpPrototypeChain) {
      return m1.distUpPrototypeChain - m2.distUpPrototypeChain;
    }
    // Push all vendor prefixes to the bottom of the list
    return isVendorPrefixed(m1.prop) ?
      (isVendorPrefixed(m2.prop) ? m1.prop.localeCompare(m2.prop) : 1) :
      (isVendorPrefixed(m2.prop) ? -1 : m1.prop.localeCompare(m2.prop));
  });

  // Trim to size. There is a bug for doing a better job of finding matches
  // (bug 682694), but in the mean time there is a performance problem
  // associated with creating a large number of DOM nodes that few people will
  // ever read, so trim ...
  if (matches.length > JavascriptType.MAX_COMPLETION_MATCHES) {
    matches = matches.slice(0, JavascriptType.MAX_COMPLETION_MATCHES - 1);
  }

  // Decorate the matches with:
  // - a description
  // - a value (for the menu) and,
  // - an incomplete flag which reports if we should assume that the user isn't
  //   going to carry on the JS expression with this input so far
  var predictions = matches.map(function(match) {
    var description;
    var incomplete = true;

    if (this._isSafeProperty(scope, match.prop)) {
      description = '(function property)';
    }
    else {
      try {
        var value = scope[match.prop];

        if (typeof value === 'function') {
          description = '(function)';
        }
        else if (typeof value === 'boolean' || typeof value === 'number') {
          description = '= ' + value;
          incomplete = false;
        }
        else if (typeof value === 'string') {
          if (value.length > 40) {
            value = value.substring(0, 37) + '...';
          }
          description = '= \'' + value + '\'';
          incomplete = false;
        }
        else {
          description = '(' + typeof value + ')';
        }
      }
      catch (ex) {
        description = '(Error)';
      }
    }

    return {
      name: prefix + match.prop,
      value: {
        name: prefix + match.prop,
        description: description
      },
      description: description,
      incomplete: incomplete
    };
  }, this);

  if (predictions.length === 0) {
    status = Status.ERROR;
    message = l10n.lookupFormat('jstypeParseMissing', [ matchProp ]);
  }

  // If the match is the only one possible, and its VALID, predict nothing
  if (predictions.length === 1 && status === Status.VALID) {
    predictions = undefined;
  }

  return new Conversion(typed, arg, status, message, predictions);
};

/**
 * Does the given property have a prefix that indicates that it is vendor
 * specific?
 */
function isVendorPrefixed(name) {
  return name.indexOf('moz') === 0 ||
         name.indexOf('webkit') === 0 ||
         name.indexOf('ms') === 0;
}

/**
 * Constants used in return value of _findCompletionBeginning()
 */
var ParseState = {
  NORMAL: 0,
  QUOTE: 2,
  DQUOTE: 3
};

var OPEN_BODY = '{[('.split('');
var CLOSE_BODY = '}])'.split('');
var OPEN_CLOSE_BODY = {
  '{': '}',
  '[': ']',
  '(': ')'
};

/**
 * Analyzes a given string to find the last statement that is interesting for
 * later completion.
 * @param text A string to analyze
 * @return If there was an error in the string detected, then a object like
 *   { err: 'ErrorMesssage' }
 * is returned, otherwise a object like
 *   {
 *     state: ParseState.NORMAL|ParseState.QUOTE|ParseState.DQUOTE,
 *     startPos: index of where the last statement begins
 *   }
 */
JavascriptType.prototype._findCompletionBeginning = function(text) {
  var bodyStack = [];

  var state = ParseState.NORMAL;
  var start = 0;
  var c;
  for (var i = 0; i < text.length; i++) {
    c = text[i];

    switch (state) {
      // Normal JS state.
      case ParseState.NORMAL:
        if (c === '"') {
          state = ParseState.DQUOTE;
        }
        else if (c === '\'') {
          state = ParseState.QUOTE;
        }
        else if (c === ';') {
          start = i + 1;
        }
        else if (c === ' ') {
          start = i + 1;
        }
        else if (OPEN_BODY.indexOf(c) != -1) {
          bodyStack.push({
            token: c,
            start: start
          });
          start = i + 1;
        }
        else if (CLOSE_BODY.indexOf(c) != -1) {
          var last = bodyStack.pop();
          if (!last || OPEN_CLOSE_BODY[last.token] != c) {
            return { err: l10n.lookup('jstypeBeginSyntax') };
          }
          if (c === '}') {
            start = i + 1;
          }
          else {
            start = last.start;
          }
        }
        break;

      // Double quote state > " <
      case ParseState.DQUOTE:
        if (c === '\\') {
          i ++;
        }
        else if (c === '\n') {
          return { err: l10n.lookup('jstypeBeginUnterm') };
        }
        else if (c === '"') {
          state = ParseState.NORMAL;
        }
        break;

      // Single quote state > ' <
      case ParseState.QUOTE:
        if (c === '\\') {
          i ++;
        }
        else if (c === '\n') {
          return { err: l10n.lookup('jstypeBeginUnterm') };
        }
        else if (c === '\'') {
          state = ParseState.NORMAL;
        }
        break;
    }
  }

  return {
    state: state,
    startPos: start
  };
};

/**
 * Return true if the passed object is either an iterator or a generator, and
 * false otherwise
 * @param obj The object to check
 */
JavascriptType.prototype._isIteratorOrGenerator = function(obj) {
  if (obj === null) {
    return false;
  }

  if (typeof aObject === 'object') {
    if (typeof obj.__iterator__ === 'function' ||
        obj.constructor && obj.constructor.name === 'Iterator') {
      return true;
    }

    try {
      var str = obj.toString();
      if (typeof obj.next === 'function' &&
          str.indexOf('[object Generator') === 0) {
        return true;
      }
    }
    catch (ex) {
      // window.history.next throws in the typeof check above.
      return false;
    }
  }

  return false;
};

/**
 * Would calling 'scope[prop]' cause the invocation of a non-native (i.e. user
 * defined) function property?
 * Since calling functions can have side effects, it's only safe to do that if
 * explicitly requested, rather than because we're trying things out for the
 * purposes of completion.
 */
JavascriptType.prototype._isSafeProperty = function(scope, prop) {
  if (typeof scope !== 'object') {
    return false;
  }

  // Walk up the prototype chain of 'scope' looking for a property descriptor
  // for 'prop'
  var propDesc;
  while (scope) {
    try {
      propDesc = Object.getOwnPropertyDescriptor(scope, prop);
      if (propDesc) {
        break;
      }
    }
    catch (ex) {
      // Native getters throw here. See bug 520882.
      if (ex.name === 'NS_ERROR_XPC_BAD_CONVERT_JS' ||
          ex.name === 'NS_ERROR_XPC_BAD_OP_ON_WN_PROTO') {
        return false;
      }
      return true;
    }
    scope = Object.getPrototypeOf(scope);
  }

  if (!propDesc) {
    return false;
  }

  if (!propDesc.get) {
    return false;
  }

  // The property is safe if 'get' isn't a function or if the function has a
  // prototype (in which case it's native)
  return typeof propDesc.get !== 'function' || 'prototype' in propDesc.get;
};

JavascriptType.prototype.name = 'javascript';

exports.JavascriptType = JavascriptType;

});
<commit_msg>Bug 694932 (js security): Review fix See https://github.com/joewalker/gcli/commit/61c3f58bb70052f52ed59ebd6b857fc8bcbb9574#commitcomment-688544<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var l10n = require('gcli/l10n');
var types = require('gcli/types');

var Conversion = types.Conversion;
var Type = types.Type;
var Status = types.Status;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  types.registerType(JavascriptType);
};

exports.shutdown = function() {
  types.unregisterType(JavascriptType);
};

/**
 * The object against which we complete, which is usually 'window' if it exists
 * but could be something else in non-web-content environments.
 */
var globalObject;
if (typeof window !== 'undefined') {
  globalObject = window;
}

/**
 * Setter for the object against which JavaScript completions happen
 */
exports.setGlobalObject = function(obj) {
  globalObject = obj;
};

/**
 * Getter for the object against which JavaScript completions happen, for use
 * in testing
 */
exports.getGlobalObject = function() {
  return globalObject;
};

/**
 * Remove registration of object against which JavaScript completions happen
 */
exports.unsetGlobalObject = function() {
  globalObject = undefined;
};

/**
 * 'javascript' handles scripted input
 */
function JavascriptType(typeSpec) {
  if (typeSpec != null) {
    throw new Error('JavascriptType can not be customized');
  }
}

JavascriptType.prototype = Object.create(Type.prototype);

JavascriptType.prototype.stringify = function(value) {
  if (value == null) {
    return '';
  }
  return value;
};

/**
 * When sorting out completions, there is no point in displaying millions of
 * matches - this the number of matches that we aim for
 */
JavascriptType.MAX_COMPLETION_MATCHES = 10;

JavascriptType.prototype.parse = function(arg) {
  var typed = arg.text;
  var scope = globalObject;

  // Analyze the input text and find the beginning of the last part that
  // should be completed.
  var beginning = this._findCompletionBeginning(typed);

  // There was an error analyzing the string.
  if (beginning.err) {
    return new Conversion(typed, arg, Status.ERROR, beginning.err);
  }

  // If the current state is not ParseState.NORMAL, then we are inside of a
  // string which means that no completion is possible.
  if (beginning.state !== ParseState.NORMAL) {
    return new Conversion(typed, arg, Status.INCOMPLETE, '');
  }

  var completionPart = typed.substring(beginning.startPos);
  var properties = completionPart.split('.');
  var matchProp;
  var prop;

  if (properties.length > 1) {
    matchProp = properties.pop().trimLeft();
    for (var i = 0; i < properties.length; i++) {
      prop = properties[i].trim();

      // We can't complete on null.foo, so bail out
      if (scope == null) {
        return new Conversion(typed, arg, Status.ERROR,
                l10n.lookup('jstypeParseScope'));
      }

      if (prop === '') {
        return new Conversion(typed, arg, Status.INCOMPLETE, '');
      }

      // Check if prop is a getter function on 'scope'. Functions can change
      // other stuff so we can't execute them to get the next object. Stop here.
      if (this._isSafeProperty(scope, prop)) {
        return new Conversion(typed, arg);
      }

      try {
        scope = scope[prop];
      }
      catch (ex) {
        // It would be nice to be able to report this error in some way but
        // as it can happen just when someone types '{sessionStorage.', it
        // almost doesn't really count as an error, so we ignore it
        return new Conversion(typed, arg, Status.INCOMPLETE, '');
      }
    }
  }
  else {
    matchProp = properties[0].trimLeft();
  }

  // If the reason we just stopped adjusting the scope was a non-simple string,
  // then we're not sure if the input is valid or invalid, so accept it
  if (prop && !prop.match(/^[0-9A-Za-z]*$/)) {
    return new Conversion(typed, arg);
  }

  // However if the prop was a simple string, it is an error
  if (scope == null) {
    return new Conversion(typed, arg, Status.ERROR,
        l10n.lookupFormat('jstypeParseMissing', [ prop ]));
  }

  // If the thing we're looking for isn't a simple string, then we're not going
  // to find it, but we're not sure if it's valid or invalid, so accept it
  if (!matchProp.match(/^[0-9A-Za-z]*$/)) {
    return new Conversion(typed, arg);
  }

  // Skip Iterators and Generators.
  if (this._isIteratorOrGenerator(scope)) {
    return null;
  }

  var matchLen = matchProp.length;
  var prefix = matchLen === 0 ? typed : typed.slice(0, -matchLen);
  var status = Status.INCOMPLETE;
  var message = '';

  // We really want an array of matches (for sorting) but it's easier to
  // detect existing members if we're using a map initially
  var matches = {};

  // We only display a maximum of MAX_COMPLETION_MATCHES, so there is no point
  // in digging up the prototype chain for matches that we're never going to
  // use. Initially look for matches directly on the object itself and then
  // look up the chain to find more
  var distUpPrototypeChain = 0;
  var root = scope;
  try {
    while (root != null &&
        Object.keys(matches).length < JavascriptType.MAX_COMPLETION_MATCHES) {

      Object.keys(root).forEach(function(property) {
        // Only add matching properties. Also, as we're walking up the
        // prototype chain, properties on 'higher' prototypes don't override
        // similarly named properties lower down
        if (property.indexOf(matchProp) === 0 && !(property in matches)) {
          matches[property] = {
            prop: property,
            distUpPrototypeChain: distUpPrototypeChain
          };
        }
      });

      distUpPrototypeChain++;
      root = Object.getPrototypeOf(root);
    }
  }
  catch (ex) {
    return new Conversion(typed, arg, Status.INCOMPLETE, '');
  }

  // Convert to an array for sorting, and while we're at it, note if we got
  // an exact match so we know that this input is valid
  matches = Object.keys(matches).map(function(property) {
    if (property === matchProp) {
      status = Status.VALID;
    }
    return matches[property];
  });

  // The sort keys are:
  // - Being on the object itself, not in the prototype chain
  // - The lack of existence of a vendor prefix
  // - The name
  matches.sort(function(m1, m2) {
    if (m1.distUpPrototypeChain !== m2.distUpPrototypeChain) {
      return m1.distUpPrototypeChain - m2.distUpPrototypeChain;
    }
    // Push all vendor prefixes to the bottom of the list
    return isVendorPrefixed(m1.prop) ?
      (isVendorPrefixed(m2.prop) ? m1.prop.localeCompare(m2.prop) : 1) :
      (isVendorPrefixed(m2.prop) ? -1 : m1.prop.localeCompare(m2.prop));
  });

  // Trim to size. There is a bug for doing a better job of finding matches
  // (bug 682694), but in the mean time there is a performance problem
  // associated with creating a large number of DOM nodes that few people will
  // ever read, so trim ...
  if (matches.length > JavascriptType.MAX_COMPLETION_MATCHES) {
    matches = matches.slice(0, JavascriptType.MAX_COMPLETION_MATCHES - 1);
  }

  // Decorate the matches with:
  // - a description
  // - a value (for the menu) and,
  // - an incomplete flag which reports if we should assume that the user isn't
  //   going to carry on the JS expression with this input so far
  var predictions = matches.map(function(match) {
    var description;
    var incomplete = true;

    if (this._isSafeProperty(scope, match.prop)) {
      description = '(property getter)';
    }
    else {
      try {
        var value = scope[match.prop];

        if (typeof value === 'function') {
          description = '(function)';
        }
        else if (typeof value === 'boolean' || typeof value === 'number') {
          description = '= ' + value;
          incomplete = false;
        }
        else if (typeof value === 'string') {
          if (value.length > 40) {
            value = value.substring(0, 37) + '...';
          }
          description = '= \'' + value + '\'';
          incomplete = false;
        }
        else {
          description = '(' + typeof value + ')';
        }
      }
      catch (ex) {
        description = '(Error)';
      }
    }

    return {
      name: prefix + match.prop,
      value: {
        name: prefix + match.prop,
        description: description
      },
      description: description,
      incomplete: incomplete
    };
  }, this);

  if (predictions.length === 0) {
    status = Status.ERROR;
    message = l10n.lookupFormat('jstypeParseMissing', [ matchProp ]);
  }

  // If the match is the only one possible, and its VALID, predict nothing
  if (predictions.length === 1 && status === Status.VALID) {
    predictions = undefined;
  }

  return new Conversion(typed, arg, status, message, predictions);
};

/**
 * Does the given property have a prefix that indicates that it is vendor
 * specific?
 */
function isVendorPrefixed(name) {
  return name.indexOf('moz') === 0 ||
         name.indexOf('webkit') === 0 ||
         name.indexOf('ms') === 0;
}

/**
 * Constants used in return value of _findCompletionBeginning()
 */
var ParseState = {
  NORMAL: 0,
  QUOTE: 2,
  DQUOTE: 3
};

var OPEN_BODY = '{[('.split('');
var CLOSE_BODY = '}])'.split('');
var OPEN_CLOSE_BODY = {
  '{': '}',
  '[': ']',
  '(': ')'
};

/**
 * Analyzes a given string to find the last statement that is interesting for
 * later completion.
 * @param text A string to analyze
 * @return If there was an error in the string detected, then a object like
 *   { err: 'ErrorMesssage' }
 * is returned, otherwise a object like
 *   {
 *     state: ParseState.NORMAL|ParseState.QUOTE|ParseState.DQUOTE,
 *     startPos: index of where the last statement begins
 *   }
 */
JavascriptType.prototype._findCompletionBeginning = function(text) {
  var bodyStack = [];

  var state = ParseState.NORMAL;
  var start = 0;
  var c;
  for (var i = 0; i < text.length; i++) {
    c = text[i];

    switch (state) {
      // Normal JS state.
      case ParseState.NORMAL:
        if (c === '"') {
          state = ParseState.DQUOTE;
        }
        else if (c === '\'') {
          state = ParseState.QUOTE;
        }
        else if (c === ';') {
          start = i + 1;
        }
        else if (c === ' ') {
          start = i + 1;
        }
        else if (OPEN_BODY.indexOf(c) != -1) {
          bodyStack.push({
            token: c,
            start: start
          });
          start = i + 1;
        }
        else if (CLOSE_BODY.indexOf(c) != -1) {
          var last = bodyStack.pop();
          if (!last || OPEN_CLOSE_BODY[last.token] != c) {
            return { err: l10n.lookup('jstypeBeginSyntax') };
          }
          if (c === '}') {
            start = i + 1;
          }
          else {
            start = last.start;
          }
        }
        break;

      // Double quote state > " <
      case ParseState.DQUOTE:
        if (c === '\\') {
          i ++;
        }
        else if (c === '\n') {
          return { err: l10n.lookup('jstypeBeginUnterm') };
        }
        else if (c === '"') {
          state = ParseState.NORMAL;
        }
        break;

      // Single quote state > ' <
      case ParseState.QUOTE:
        if (c === '\\') {
          i ++;
        }
        else if (c === '\n') {
          return { err: l10n.lookup('jstypeBeginUnterm') };
        }
        else if (c === '\'') {
          state = ParseState.NORMAL;
        }
        break;
    }
  }

  return {
    state: state,
    startPos: start
  };
};

/**
 * Return true if the passed object is either an iterator or a generator, and
 * false otherwise
 * @param obj The object to check
 */
JavascriptType.prototype._isIteratorOrGenerator = function(obj) {
  if (obj === null) {
    return false;
  }

  if (typeof aObject === 'object') {
    if (typeof obj.__iterator__ === 'function' ||
        obj.constructor && obj.constructor.name === 'Iterator') {
      return true;
    }

    try {
      var str = obj.toString();
      if (typeof obj.next === 'function' &&
          str.indexOf('[object Generator') === 0) {
        return true;
      }
    }
    catch (ex) {
      // window.history.next throws in the typeof check above.
      return false;
    }
  }

  return false;
};

/**
 * Would calling 'scope[prop]' cause the invocation of a non-native (i.e. user
 * defined) function property?
 * Since calling functions can have side effects, it's only safe to do that if
 * explicitly requested, rather than because we're trying things out for the
 * purposes of completion.
 */
JavascriptType.prototype._isSafeProperty = function(scope, prop) {
  if (typeof scope !== 'object') {
    return false;
  }

  // Walk up the prototype chain of 'scope' looking for a property descriptor
  // for 'prop'
  var propDesc;
  while (scope) {
    try {
      propDesc = Object.getOwnPropertyDescriptor(scope, prop);
      if (propDesc) {
        break;
      }
    }
    catch (ex) {
      // Native getters throw here. See bug 520882.
      if (ex.name === 'NS_ERROR_XPC_BAD_CONVERT_JS' ||
          ex.name === 'NS_ERROR_XPC_BAD_OP_ON_WN_PROTO') {
        return false;
      }
      return true;
    }
    scope = Object.getPrototypeOf(scope);
  }

  if (!propDesc) {
    return false;
  }

  if (!propDesc.get) {
    return false;
  }

  // The property is safe if 'get' isn't a function or if the function has a
  // prototype (in which case it's native)
  return typeof propDesc.get !== 'function' || 'prototype' in propDesc.get;
};

JavascriptType.prototype.name = 'javascript';

exports.JavascriptType = JavascriptType;

});
<|endoftext|>


<commit_before>/**
 * File: Pages, Project
 * Main logic for Project page.
 *
 * Filename:
 * project.js
 *
 * Dependencies:
 * - tc.gam.base.js
 * - tc.utils.js
 * - tc.gam.app.js
 * - tc.gam.project.js
 * - tc.gam.invite.js
 */

/**
 * App Page Feature: Nice Drop Downs
 * Utilizes jqDropDown to make nice drop downs for selects.
 */
app_page.features.push(function(app) {
    tc.jQ("select.duration").jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.duration'
    });

    tc.jQ("select.point_person").jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.point_person'
    });

    tc.jQ("select.message_filter_select").show().jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.message_filter_select'
    });
});

/**
 * App Page Feature: Tab Navigation
 * Handle tab navigation.  The assumption is that the second class in the
 * "ul.project-tabs li a" corresponds to the ".project-sections div" class
 * that will be shown.
 */
app_page.features.push(function(app) {
    // Hide any non-current content.
    tc.jQ('.project-sections div.project-section:not(.current)').hide();

    // Handle tab links.
    tc.jQ('ul.project-tabs li a').each(function(index) {
        var $this_tab = tc.jQ(this);
        var classes = $this_tab.attr("class").split(' ');

        // Assume that the second class is the one that corresponds to
        // the content to show/hide.
        var section = classes[1];

        // Add click event.
        $this_tab.click(function(e) {
            e.preventDefault();

            // Handle showing and hiding of content.
            tc.jQ('.project-sections div.project-section')
                .hide().removeClass('current');
            tc.jQ('.project-sections div.project-section.' + section)
                .show().addClass('current');

            // Hash change.
            window.location.hash = section;

            // Mark as tab links
            tc.jQ('.project-tabs li a').removeClass('current');
            tc.jQ(this).addClass('current');
        });
    });
});

/**
 * App Page Feature: Visual Enhancements
 * Various visual enhancements
 */
app_page.features.push(function(app) {
    // random note-card backgrounds
    tc.randomNoteCardBg(tc.jQ('.ideas-invite .items'));

    // add 'official resource' tags to resources
    tc.addOfficialResourceTags(tc.jQ('.box.resources .organizations table.resources-list'));
});

/**
 * App Page Feature: Project Data Events
 * This handles image uploading, and joining and leaving a project.  Also
 * handling idea invite action.
 */
app_page.features.push(function(app) {
    // Create new project object.
    app.components.project = new tc.gam.project({
        app: app,
        data: app_page.data.project,
        project_user: app_page.project_user,
        dom: tc.jQ('.continent.project')
    });

    // Bind "create-image-uploaded" to document to handle uploading
    // and image via AJAX call.  when successful, display new image as the
    // project image.
    tc.jQ(document).unbind('create-image-uploaded').bind('create-image-uploaded', {
        app: app,
        project: app.components.project
    }, function(e, d) {
        e.data.app.components.modal.hide();
        if (d.responseJSON.thumbnail_id) {
            tc.jQ.ajax({
                type: 'POST',
                url: '/project/photo',
                data: {
                    project_id: e.data.project.data.project_id,
                    image_id: d.responseJSON.thumbnail_id
                },
                dataType: 'text',
                success: function(data,ts,xhr) {
                    tc.jQ('img.proj').attr('src', e.data.app.app_page.media_root +
                        'images/' + (d.responseJSON.thumbnail_id % 10) + '/' +
                        d.responseJSON.thumbnail_id + '.png');
                }
            });
        }
    });

    // Handle modal dialog for project image upload.  Utilize file uploader
    // library; pass the modal definition as event data.  Trigger
    // "create-image-uploaded" when successful.
    tc.jQ('a.change-image').bind('click', {
        app: app,
        source_element: tc.jQ('.modal-content.upload-image'),
        init: function(modal, callback) {
            var uploader = new qq.FileUploader({
                element: modal.options.element.find('.file-uploader').get(0),
                action: '/create/photo',
                onComplete: function(id, fileName, responseJSON) {
                    // Trigger uploaded event with new image IDs
                    tc.jQ(document).trigger('create-image-uploaded',{
                        id: id,
                        fileName: fileName,
                        responseJSON: responseJSON
                    });
                    return true;
                }
            });

            // Call callback if available.
            if(tc.jQ.isFunction(callback)){
                callback(modal);
            }
        }
    },
    function(e, d) {
        // Handle click event.
        e.preventDefault();
        e.data.app.components.modal.show(e.data);
    });

    // Handle join project click event.  Utilize a merlin modal dialogue and define
    // it in the click event data.  On no user, do?
    tc.jQ('a.join-project').bind('click', {
        app: app,
        no_user: {
            source_element: tc.jQ('.modal-content.join-no-user'),
            init: function(modal, event_target, callback) {
                if (tc.jQ.isFunction(callback)) {
                    callback(modal);
                }
            }
        },
        user: {
            source_element: tc.jQ('.modal-content.introduce-yourself'),
            init: function(modal, event_target, callback) {
                var modal_merlin = new tc.merlin(app, tc.app.merlin_join_modal(modal, event_target, callback));

                if(tc.jQ.isFunction(callback)){
                    callback(modal);
                }
            }
        }
    },
    function(e,d) {
        // Check user, choose appropriate modal.
        if (!e.data.app.app_page.user) {
            e.data.app.components.modal.show(e.data.no_user, e.target);
        } else {
            e.data.app.components.modal.show(e.data.user, e.target);
        }
    });

    // Handle leaving project event.  This is done with a modal and AJAX call.
    tc.jQ('a.leave-project').bind('click', { app:app }, function(e, d) {
        var t = tc.jQ(this);
        e.preventDefault();

        // Handle modal.
        e.data.app.components.modal.show({
            app: app,
            source_element: tc.jQ('.modal-content.leave-project'),
            submit: function(modal, callback) {
                tc.jQ.ajax({
                    type: 'POST',
                    url: '/project/leave',
                    data: {
                        project_id: t.attr('href').split(',')[1]
                    },
                    context: app,
                    dataType: 'text',
                    success: function(data, ts, xhr) {
                        if (data == 'False') {
                            return false;
                        }

                        // Reload page.
                        window.location.reload(true);
                    }
                });
            }
        });
    });

    // Handle idea invites.
    tc.gam.ideas_invite(app, {
        elements: tc.jQ('a.invite'),
        ref_project_id: app.components.project.data.project_id
    });
});

/**
 * Function: tc.app.merlin_join_modal
 * Defines modal merlin object for project join process.
 */
tc.app.merlin_join_modal = function(modal, event_target, callback) {
    return {
        dom: modal.options.element.find('.introduce-yourself'),
        first_step: 'introduce-message-step',
        data: {
            project_id: app_page.data.project.project_id,
            message: null
        },
        use_hashchange: false,
        steps: {
            'introduce-message-step': {
                selector: '.introduce-message-step',
                inputs: {
                    message: {
                        selector: 'textarea.introduce-message',
                        validators: ['max-200']
                    }
                },
                init: function(merlin, dom) {
                    merlin.dom.mouseenter(function() {
                        merlin.current_step.inputs.message.dom.focus();
                    });
                    dom.find('.submit').bind('click', { merlin: merlin, dom: dom}, function(e,d) {
                        e.preventDefault();
                        if (dom.hasClass('invalid')) {
                            return;
                        }
                        e.data.merlin.show_step('finish');
                    });
                },
                finish: function(merlin,dom) {
                    merlin.options.data.message = merlin.current_step.inputs.message.dom.val();
                }
            },
            'finish': {
                selector: '.finish',
                init: function(merlin, dom) {
                    tc.jQ.ajax({
                        type: 'POST',
                        url: '/project/join',
                        data: merlin.options.data,
                        context: merlin,
                        dataType: 'text',
                        success: function(data,ts,xhr) {
                            window.location.reload(true);
                        }
                    });
                }
            }
        }
    };
};<commit_msg>update options used in project.js<commit_after>/**
 * File: Pages, Project
 * Main logic for Project page.
 *
 * Filename:
 * project.js
 *
 * Dependencies:
 * - tc.gam.base.js
 * - tc.utils.js
 * - tc.gam.app.js
 * - tc.gam.project.js
 * - tc.gam.invite.js
 */

/**
 * App Page Feature: Nice Drop Downs
 * Utilizes jqDropDown to make nice drop downs for selects.
 */
app_page.features.push(function(app) {
    tc.jQ("select.duration").jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.duration'
    });

    tc.jQ("select.point_person").jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.point_person'
    });

    tc.jQ("select.message_filter_select").show().jqDropDown({
        direction: 'down',
        effect: 'fade',
        effectSpeed: 150,
        placeholder: '.message_filter_select'
    });
});

/**
 * App Page Feature: Tab Navigation
 * Handle tab navigation.  The assumption is that the second class in the
 * "ul.project-tabs li a" corresponds to the ".project-sections div" class
 * that will be shown.
 */
app_page.features.push(function(app) {
    // Hide any non-current content.
    tc.jQ('.project-sections div.project-section:not(.current)').hide();

    // Handle tab links.
    tc.jQ('ul.project-tabs li a').each(function(index) {
        var $this_tab = tc.jQ(this);
        var classes = $this_tab.attr("class").split(' ');

        // Assume that the second class is the one that corresponds to
        // the content to show/hide.
        var section = classes[1];

        // Add click event.
        $this_tab.click(function(e) {
            e.preventDefault();

            // Handle showing and hiding of content.
            tc.jQ('.project-sections div.project-section')
                .hide().removeClass('current');
            tc.jQ('.project-sections div.project-section.' + section)
                .show().addClass('current');

            // Hash change.
            window.location.hash = section;

            // Mark as tab links
            tc.jQ('.project-tabs li a').removeClass('current');
            tc.jQ(this).addClass('current');
        });
    });
});

/**
 * App Page Feature: Visual Enhancements
 * Various visual enhancements
 */
app_page.features.push(function(app) {
    // random note-card backgrounds
    tc.randomNoteCardBg(tc.jQ('.ideas-invite .items'));

    // add 'official resource' tags to resources
    tc.addOfficialResourceTags(tc.jQ('.box.resources .organizations table.resources-list'));
});

/**
 * App Page Feature: Project Data Events
 * This handles image uploading, and joining and leaving a project.  Also
 * handling idea invite action.
 */
app_page.features.push(function(app) {
    // Create new project object.
    app.components.project = new tc.gam.project({
        app: app,
        data: app_page.data.project,
        project_user: app_page.project_user,
        dom: tc.jQ('.continent.project')
    });

    // Bind "create-image-uploaded" to document to handle uploading
    // and image via AJAX call.  when successful, display new image as the
    // project image.
    tc.jQ(document).unbind('create-image-uploaded').bind('create-image-uploaded', {
        app: app
    }, function(e, d) {
        e.data.app.components.modal.hide();
        if (d.responseJSON.thumbnail_id) {
            tc.jQ.ajax({
                type: 'POST',
                url: '/project/photo',
                data: {
                    project_id: app_page.data.project.project_id,
                    image_id: d.responseJSON.thumbnail_id
                },
                dataType: 'text',
                success: function(data,ts,xhr) {
                    tc.jQ('img.proj').attr('src', e.data.app.app_page.media_root +
                        'images/' + (d.responseJSON.thumbnail_id % 10) + '/' +
                        d.responseJSON.thumbnail_id + '.png');
                }
            });
        }
    });

    // Handle modal dialog for project image upload.  Utilize file uploader
    // library; pass the modal definition as event data.  Trigger
    // "create-image-uploaded" when successful.
    tc.jQ('a.change-image').bind('click', {
        app: app,
        source_element: tc.jQ('.modal-content.upload-image'),
        init: function(modal, callback) {
            var uploader = new qq.FileUploader({
                element: modal.options.element.find('.file-uploader').get(0),
                action: '/create/photo',
                onComplete: function(id, fileName, responseJSON) {
                    // Trigger uploaded event with new image IDs
                    tc.jQ(document).trigger('create-image-uploaded',{
                        id: id,
                        fileName: fileName,
                        responseJSON: responseJSON
                    });
                    return true;
                }
            });

            // Call callback if available.
            if(tc.jQ.isFunction(callback)){
                callback(modal);
            }
        }
    },
    function(e, d) {
        // Handle click event.
        e.preventDefault();
        e.data.app.components.modal.show(e.data);
    });

    // Handle join project click event.  Utilize a merlin modal dialogue and define
    // it in the click event data.  On no user, do?
    tc.jQ('a.join-project').bind('click', {
        app: app,
        no_user: {
            source_element: tc.jQ('.modal-content.join-no-user'),
            init: function(modal, event_target, callback) {
                if (tc.jQ.isFunction(callback)) {
                    callback(modal);
                }
            }
        },
        user: {
            source_element: tc.jQ('.modal-content.introduce-yourself'),
            init: function(modal, event_target, callback) {
                var modal_merlin = new tc.merlin(app, tc.app.merlin_join_modal(modal, event_target, callback));

                if(tc.jQ.isFunction(callback)){
                    callback(modal);
                }
            }
        }
    },
    function(e,d) {
        // Check user, choose appropriate modal.
        if (!e.data.app.app_page.user) {
            e.data.app.components.modal.show(e.data.no_user, e.target);
        } else {
            e.data.app.components.modal.show(e.data.user, e.target);
        }
    });

    // Handle leaving project event.  This is done with a modal and AJAX call.
    tc.jQ('a.leave-project').bind('click', { app:app }, function(e, d) {
        var t = tc.jQ(this);
        e.preventDefault();

        // Handle modal.
        e.data.app.components.modal.show({
            app: app,
            source_element: tc.jQ('.modal-content.leave-project'),
            submit: function(modal, callback) {
                tc.jQ.ajax({
                    type: 'POST',
                    url: '/project/leave',
                    data: {
                        project_id: t.attr('href').split(',')[1]
                    },
                    context: app,
                    dataType: 'text',
                    success: function(data, ts, xhr) {
                        if (data == 'False') {
                            return false;
                        }

                        // Reload page.
                        window.location.reload(true);
                    }
                });
            }
        });
    });

    // Handle idea invites.
    tc.gam.ideas_invite(app, {
        elements: tc.jQ('a.invite'),
        ref_project_id: app_page.data.project.project_id
    });
});

/**
 * Function: tc.app.merlin_join_modal
 * Defines modal merlin object for project join process.
 */
tc.app.merlin_join_modal = function(modal, event_target, callback) {
    return {
        dom: modal.options.element.find('.introduce-yourself'),
        first_step: 'introduce-message-step',
        data: {
            project_id: app_page.data.project.project_id,
            message: null
        },
        use_hashchange: false,
        steps: {
            'introduce-message-step': {
                selector: '.introduce-message-step',
                inputs: {
                    message: {
                        selector: 'textarea.introduce-message',
                        validators: ['max-200']
                    }
                },
                init: function(merlin, dom) {
                    merlin.dom.mouseenter(function() {
                        merlin.current_step.inputs.message.dom.focus();
                    });
                    dom.find('.submit').bind('click', { merlin: merlin, dom: dom}, function(e,d) {
                        e.preventDefault();
                        if (dom.hasClass('invalid')) {
                            return;
                        }
                        e.data.merlin.show_step('finish');
                    });
                },
                finish: function(merlin,dom) {
                    merlin.options.data.message = merlin.current_step.inputs.message.dom.val();
                }
            },
            'finish': {
                selector: '.finish',
                init: function(merlin, dom) {
                    tc.jQ.ajax({
                        type: 'POST',
                        url: '/project/join',
                        data: merlin.options.data,
                        context: merlin,
                        dataType: 'text',
                        success: function(data,ts,xhr) {
                            window.location.reload(true);
                        }
                    });
                }
            }
        }
    };
};<|endoftext|>