<commit_before>$( function () {

  if ( $('.edit_comment').length > 0) {
    $('.toggle-edit-comment').each(function(){
      var isEditing = false;

      $(this).click(function() {
        var $parent = $(event.target).parents('form.edit_comment')
        if (isEditing) {
          showComment($parent);
        }
        else {
          editComment($parent);
        }
        isEditing = !isEditing;
      });
    });

    $('button.save-edit-comment').click(function() {
      var $parent = $(event.target).parents('form.edit_comment');

      saveComment($parent);
      showComment($parent);
    });
  }

  $('#new_comment').submit( function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: this.action,
      data: $('#new_comment').serialize(),
      success: function (data) {
        // so it worked, add to the comment list
        refresh_comments();

        // clear comment field for next comment
        $('#comment_content').val('');
      },
      error: function() {
        alert('error saving comment');
      }
    });
  });

  $('#delete_comment').live('submit', function(e) {
    e.preventDefault();
    if(confirm('Are you sure you want to delete this?')) {
      $.ajax({
        type: 'POST',
        url: this.action,
        data: $(this).serialize(),
        success: function (data) {
          // so it worked, add to the comment list
          refresh_comments();
        },
        statusCode: {
          401: function() {
            alert('not authorized to delete this comment');
          }
        },
        error: function() {
        },
      });
    }
  });
});

function editComment($parent) {
  $parent.find('.read-only-comment').hide();
  $parent.find('.editable-comment').show();
  $parent.find('.toggle-edit-comment').removeClass('btn-primary').text('Cancel');
  $parent.find('.save-edit-comment').show();
}

function showComment($parent) {
  $parent.find('.read-only-comment').show();
  $parent.find('.editable-comment').hide();
  $parent.find('.toggle-edit-comment').addClass('btn-primary').text('Edit');
  $parent.find('.save-edit-comment').hide();
}

function saveComment($form) {
  var $url = $form.attr('action');
  var serialized_form = $form.serialize();

  $.ajax({
        url: $url,
        type: 'POST',
        data: serialized_form
      }).success(function() {
          $.get($url, function(data) {
            $form.find('.read-only-comment').html(data);
          })

        }).error( function() {
          $form.find('.read-only-comment').html("Comment update error.");
          })
}

function refresh_comments() {
  var url = window.location + '/comments';
  $.get(url, function(data) {
    $('#comment_table').html(data);
  });
}
<commit_msg>Fixes having to hit edit twice<commit_after>$( function () {

  if ( $('.edit_comment').length > 0) {
    var isEditing = false;

    $('.toggle-edit-comment').each(function(){
      $(this).click(function() {
        var $parent = $(event.target).parents('form.edit_comment');

        if (isEditing) {
          showComment($parent);
        }
        else {
          editComment($parent);
        }
        isEditing = !isEditing;
      });
    });

    $('button.save-edit-comment').click(function() {
      var $parent = $(event.target).parents('form.edit_comment');

      saveComment($parent);
      showComment($parent);

      isEditing = !isEditing;
    });
  }

  $('#new_comment').submit( function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: this.action,
      data: $('#new_comment').serialize(),
      success: function (data) {
        // so it worked, add to the comment list
        refresh_comments();

        // clear comment field for next comment
        $('#comment_content').val('');
      },
      error: function() {
        alert('error saving comment');
      }
    });
  });

  $('#delete_comment').live('submit', function(e) {
    e.preventDefault();
    if(confirm('Are you sure you want to delete this?')) {
      $.ajax({
        type: 'POST',
        url: this.action,
        data: $(this).serialize(),
        success: function (data) {
          // so it worked, add to the comment list
          refresh_comments();
        },
        statusCode: {
          401: function() {
            alert('not authorized to delete this comment');
          }
        },
        error: function() {
        },
      });
    }
  });
});

function editComment($parent) {
  $parent.find('.read-only-comment').hide();
  $parent.find('.editable-comment').show();
  $parent.find('.toggle-edit-comment').removeClass('btn-primary').text('Cancel');
  $parent.find('.save-edit-comment').show();
}

function showComment($parent) {
  $parent.find('.read-only-comment').show();
  $parent.find('.editable-comment').hide();
  $parent.find('.toggle-edit-comment').addClass('btn-primary').text('Edit');
  $parent.find('.save-edit-comment').hide();
}

function saveComment($form) {
  var $url = $form.attr('action');
  var serialized_form = $form.serialize();

  $.ajax({
        url: $url,
        type: 'POST',
        data: serialized_form
      }).success(function() {
          $.get($url, function(data) {
            $form.find('.read-only-comment').html(data);
          })

        }).error( function() {
          $form.find('.read-only-comment').html("Comment update error.");
          })
}

function refresh_comments() {
  var url = window.location + '/comments';
  $.get(url, function(data) {
    $('#comment_table').html(data);
  });
}
<|endoftext|>


<commit_before><<<<<<< HEAD
$(document).ready(function(){
	let iOS = /iPad|iPhone|iPod/.test(navigator.platform);
	if( iOS ) {
	    var background_videos = document.querySelectorAll('.bgvid');
	    for( i=0; i<background_videos.length; i++ ) {
	        background_videos[i].parentNode.removeChild(background_videos[i]);
	    }
	}
=======

// let iOS = /iPad|iPhone|iPod/.test(navigator.platform);
// if( iOS ) {
//     var background_videos = document.querySelectorAll('.bgvid');
//     for( i=0; i<background_videos.length; i++ ) {
//         background_videos[i].parentNode.removeChild(background_videos[i]);
//     }
// }

$(document).ready(function(){

	if (localStorage.getItem("demo") === null) {
		var oReq = new XMLHttpRequest();
		var url = "http://encoding.com.result.s3.amazonaws.com/574960b7c4fea3206b98299299a004e9_386231_208279910.mp4";
		oReq.open('POST', url, true);
		oReq.responseType = "arraybuffer";console.log(oReq.response);
		oReq.onload = function(oEvent) {
			let blob = new Blob([oReq.response], {type: 'video/mp4'});
			let reader = new FileReader();
			reader.readAsDataURL(blob);
			reader.onload = function(e) {
				var dataURL = reader.result;
				localStorage.setItem("demo", dataURL);
				location.reload();
			}
			oReq.send();
		}
	}

	var videlem = document.createElement("video");
	videlem.autoplay = true;
	videlem.loop = true;
	videlem.poster = "https://www.dropbox.com/s/gfsu9tdeaam9kas/Coffee-Shot.jpg?raw=1";
	videlem.id = "bgvid";
	var sourceMP4 = document.createElement("source");
	sourceMP4.type = "video/mp4";
	sourceMP4.src = localStorage.getItem("demo");
	sourceMP4.autoPlay = true;
	videlem.appendChild(sourceMP4);
	document.body.appendChild(videlem);

});

$(document).ready(function(){
>>>>>>> 7a8198bc029e2c4d226aa40105b134bce3e49655
	let fade_in_videos = document.querySelectorAll('.fade-in-video');
	for( i=0; i<fade_in_videos.length; i++ ) {
	    fade_in_videos[i].addEventListener("playing", function(){
	        this.className += ' is-playing';
	    });
	}
})

$(window).on('load', function(){
	$('body').addClass('active');
	$('.container').show(function(){
		$('.center-wrapper').fadeOut(0).delay(800).fadeIn(1200, 'swing', function(){
			$('.tile').fadeTo(0, 0.5, 'linear')
			.delay(150).fadeTo(0, 1, 'linear')
			.delay(150).fadeTo(0, 0.5, 'linear')
			.delay(150).fadeTo(0, 1, 'linear')
			.delay(150).fadeTo(0, 0.7, 'linear', function(){
				$('#startBtn').css('background-color', 'hsl(0, 41%, 43%)');
				$('#strictBtn').css('background-color', 'hsl(48, 46%, 41%)');
				$('.center').css('background-color', '#999');
				$('#cog_icon').fadeIn(900);
				$('body').removeClass('active');
			});
		});
	});
});

let sequence = [];
let copy = [];
let turn = 0;
let timeouts = [];
let delay;
let boardTimeoutId;
let simon = {};

simon.masterSw = false;
simon.strict = false;

simon.start = function() {

	simon.reset();
	delay = setTimeout(function() {
		advanceTurn();
		playSeq();
	},1500);
}

simon.reset = function() {
	clearTimeout(delay);
	stopTimeouts();
	disableBoard();
	sequence = sequence.slice(0, 0);
	copy = copy.slice(0, 0);
	turn = 0;
}

function finalAnimation() {
	$('body').css('overflow', 'hidden');
	$('body').find('.board').addClass('rollEnd');
	$('.center-wrapper').fadeOut(2000);
	$('#displayTurn').children('h2').text('--');
	simon.reset;

	setTimeout(function(){
		$('.final').fadeIn(1500).delay(2000).fadeOut(500);
	}, 2000);

	$('.board').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
		$('body').css('overflow', 'auto');
		$('.board').removeClass('rollEnd');

		setTimeout(function(){
			$('.center-wrapper').fadeIn(400);
		}, 400);
	});
}

let playSound = function(_note) {
	$('audio')[_note].currentTime=0;
	$('audio')[_note].play();
}

let animate = function(_note) {
	let tiles = $('.tile');
	let trgTile = $(tiles[_note]);

	tiles.removeClass('active');
	trgTile.addClass('active');

	setTimeout(function() {
		trgTile.removeClass('active');
	}, 300);
}

let advanceTurn = function () {
	let random = Math.floor(Math.random() * 4);
	sequence.push(random);
	++turn;
	turn = turn < 10 ? '0' + turn : turn;
	$('#displayTurn').children('h2').text(turn);
}

let incrementalTimeout = function(i, _note, _playRate) {

	let timeoutId = setTimeout(function() {
		playSound(_note);
		animate(_note);

		if (timeouts[0] === timeoutId) {
			timeouts.shift();
		}
		if(!timeouts.length) {

			setTimeout(function() {
				copy = sequence.slice(0);
				enableBoard();
			}, 200);
		}

	}, i * _playRate);

	timeouts.push(timeoutId); 	//console.log('timeouts arr: ' + timeouts);
};

let stopTimeouts = function() {
	for(let i = 0; i < timeouts.length; ++i) {
		clearTimeout(timeouts[i]);
	}
	timeouts = timeouts.slice(0, 0);
}

let playSeq = function() {
	clearTimeout(boardTimeoutId);

	for (let i = 0; i < sequence.length; ++i) {
		let note = sequence[i];
		let playRate;
		if (turn <= 15) playRate = 1250 - (50 * turn);
		else playRate = 450;
		incrementalTimeout(i, note, playRate);
	}

};

let inputCheck = function(note) {

	if(copy[0] == note) {
		playSound(note);
		copy.shift();

		if (!copy.length && sequence.length >= 20) {
			disableBoard();
			setTimeout(function() {
				finalAnimation()
				sequence = sequence.slice(0, 0);
			},500);
		}
		else if (!copy.length) {
			disableBoard();
			delay = setTimeout(function() {
				advanceTurn();
				playSeq();
			},1500);
		}
	}
	else {
		if (simon.strict) {
			playSound(4);
			simon.start();
		}
		else {
			playSound(4);
			disableBoard();
			delay = setTimeout(function() {
				playSeq();
			},1500);
		}
	}
}

function enableControls() {
	$('#displayTurn').children('h2').text('--').css('color', 'rgba(255, 56, 56, 1)');

	$('#startBtn').on('click', function(e){
		e.preventDefault();
		simon.start();
		$('#displayTurn').children('h2').text('--').css('color', 'rgba(255, 56, 56, 1)');
	})

	$('#strictBtn').on('click', function(e){
		e.preventDefault();
		let led = $('.led');
		led.toggleClass('strictModeOn');

		if (led.hasClass('strictModeOn')) {
			simon.strict = true;
		} else {
			simon.strict = false;
		}
	});
}

function disableControls() {
	$('#startBtn, #strictBtn').off('click');
	$('#displayTurn').children('h2').text('--').css('color', '#100');
}

$('.center').on('click', '.masterSwWrapper', function(){

	if (!simon.masterSw) {
		enableControls();
		simon.masterSw = true;
		simon.strict = false;
		$('.masterSwWrapper').children('.masterSw').addClass('active');
		$('.tile').fadeTo(0, 1, 'swing');
		$('#startBtn').css('background-color', 'hsl(0, 100%, 63%)');
		$('#strictBtn').css('background-color', 'hsl(48, 99%, 62%)');
		$('.center').css('background-color', '#bbb');
	}
	else {
		simon.masterSw = false;
		simon.reset();
		disableControls();
		$('.led').removeClass('strictModeOn');
		$('.masterSwWrapper').children('.masterSw').removeClass('active');
		$('.tile').fadeTo(0, 0.7, 'swing');
		$('#startBtn').css('background-color', 'hsl(0, 41%, 43%)');
		$('#strictBtn').css('background-color', 'hsl(48, 46%, 41%)');
		$('.center').css('background-color', '#999');
	}
});

let boardActiveTime = function() {
	clearTimeout(boardTimeoutId);
	boardTimeoutId = setTimeout(function(){
		disableBoard();
		playSeq();

	}, 6000);
}

function enableBoard(){

	boardActiveTime();

	$('.board')
		.on('click', '[data-tile]', function(e){
			let btnSelectd = $(e.target).data('tile');
			inputCheck(btnSelectd);
			boardActiveTime();
		})

		.on('mousedown touchstart', '[data-tile]', function(){
			$(this).addClass('active');

		})

		.on('mouseup mouseout touchend', '[data-tile]', function(){
			$(this).removeClass('active');
		})
}

function disableBoard(){
	$('.board')
		.off('click touchend mousedown touchstart mouseup mouseout');
}

$('body').on('click', '#cog_icon', function(){
	let overl = $('.overlay').hasClass('active');
	if(!overl) {
		$('body, .overlay, .modal-wrapper').removeClass('unactive');
		$('body, .overlay, .modal-wrapper').addClass('active');
	}
	else {
		$('body, .overlay, .modal-wrapper').removeClass('active');
		$('body, .overlay, .modal-wrapper').addClass('unactive');
	}
});
<commit_msg>Fix main.js<commit_after>
$(document).ready(function(){
	let iOS = /iPad|iPhone|iPod/.test(navigator.platform);
	if( iOS ) {
	    var background_videos = document.querySelectorAll('.bgvid');
	    for( i=0; i<background_videos.length; i++ ) {
	        background_videos[i].parentNode.removeChild(background_videos[i]);
	    }
	}

	let fade_in_videos = document.querySelectorAll('.fade-in-video');
	for( i=0; i<fade_in_videos.length; i++ ) {
	    fade_in_videos[i].addEventListener("playing", function(){
	        this.className += ' is-playing';
	    });
	}
})

$(window).on('load', function(){
	$('body').addClass('active');
	$('.container').show(function(){
		$('.center-wrapper').fadeOut(0).delay(800).fadeIn(1200, 'swing', function(){
			$('.tile').fadeTo(0, 0.5, 'linear')
			.delay(150).fadeTo(0, 1, 'linear')
			.delay(150).fadeTo(0, 0.5, 'linear')
			.delay(150).fadeTo(0, 1, 'linear')
			.delay(150).fadeTo(0, 0.7, 'linear', function(){
				$('#startBtn').css('background-color', 'hsl(0, 41%, 43%)');
				$('#strictBtn').css('background-color', 'hsl(48, 46%, 41%)');
				$('.center').css('background-color', '#999');
				$('#cog_icon').fadeIn(900);
				$('body').removeClass('active');
			});
		});
	});
});

let sequence = [];
let copy = [];
let turn = 0;
let timeouts = [];
let delay;
let boardTimeoutId;
let simon = {};

simon.masterSw = false;
simon.strict = false;

simon.start = function() {

	simon.reset();
	delay = setTimeout(function() {
		advanceTurn();
		playSeq();
	},1500);
}

simon.reset = function() {
	clearTimeout(delay);
	stopTimeouts();
	disableBoard();
	sequence = sequence.slice(0, 0);
	copy = copy.slice(0, 0);
	turn = 0;
}

function finalAnimation() {
	$('body').css('overflow', 'hidden');
	$('body').find('.board').addClass('rollEnd');
	$('.center-wrapper').fadeOut(2000);
	$('#displayTurn').children('h2').text('--');
	simon.reset;

	setTimeout(function(){
		$('.final').fadeIn(1500).delay(2000).fadeOut(500);
	}, 2000);

	$('.board').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
		$('body').css('overflow', 'auto');
		$('.board').removeClass('rollEnd');

		setTimeout(function(){
			$('.center-wrapper').fadeIn(400);
		}, 400);
	});
}

let playSound = function(_note) {
	$('audio')[_note].currentTime=0;
	$('audio')[_note].play();
}

let animate = function(_note) {
	let tiles = $('.tile');
	let trgTile = $(tiles[_note]);

	tiles.removeClass('active');
	trgTile.addClass('active');

	setTimeout(function() {
		trgTile.removeClass('active');
	}, 300);
}

let advanceTurn = function () {
	let random = Math.floor(Math.random() * 4);
	sequence.push(random);
	++turn;
	turn = turn < 10 ? '0' + turn : turn;
	$('#displayTurn').children('h2').text(turn);
}

let incrementalTimeout = function(i, _note, _playRate) {

	let timeoutId = setTimeout(function() {
		playSound(_note);
		animate(_note);

		if (timeouts[0] === timeoutId) {
			timeouts.shift();
		}
		if(!timeouts.length) {

			setTimeout(function() {
				copy = sequence.slice(0);
				enableBoard();
			}, 200);
		}

	}, i * _playRate);

	timeouts.push(timeoutId); 	//console.log('timeouts arr: ' + timeouts);
};

let stopTimeouts = function() {
	for(let i = 0; i < timeouts.length; ++i) {
		clearTimeout(timeouts[i]);
	}
	timeouts = timeouts.slice(0, 0);
}

let playSeq = function() {
	clearTimeout(boardTimeoutId);

	for (let i = 0; i < sequence.length; ++i) {
		let note = sequence[i];
		let playRate;
		if (turn <= 15) playRate = 1250 - (50 * turn);
		else playRate = 450;
		incrementalTimeout(i, note, playRate);
	}

};

let inputCheck = function(note) {

	if(copy[0] == note) {
		playSound(note);
		copy.shift();

		if (!copy.length && sequence.length >= 20) {
			disableBoard();
			setTimeout(function() {
				finalAnimation()
				sequence = sequence.slice(0, 0);
			},500);
		}
		else if (!copy.length) {
			disableBoard();
			delay = setTimeout(function() {
				advanceTurn();
				playSeq();
			},1500);
		}
	}
	else {
		if (simon.strict) {
			playSound(4);
			simon.start();
		}
		else {
			playSound(4);
			disableBoard();
			delay = setTimeout(function() {
				playSeq();
			},1500);
		}
	}
}

function enableControls() {
	$('#displayTurn').children('h2').text('--').css('color', 'rgba(255, 56, 56, 1)');

	$('#startBtn').on('click', function(e){
		e.preventDefault();
		simon.start();
		$('#displayTurn').children('h2').text('--').css('color', 'rgba(255, 56, 56, 1)');
	})

	$('#strictBtn').on('click', function(e){
		e.preventDefault();
		let led = $('.led');
		led.toggleClass('strictModeOn');

		if (led.hasClass('strictModeOn')) {
			simon.strict = true;
		} else {
			simon.strict = false;
		}
	});
}

function disableControls() {
	$('#startBtn, #strictBtn').off('click');
	$('#displayTurn').children('h2').text('--').css('color', '#100');
}

$('.center').on('click', '.masterSwWrapper', function(){

	if (!simon.masterSw) {
		enableControls();
		simon.masterSw = true;
		simon.strict = false;
		$('.masterSwWrapper').children('.masterSw').addClass('active');
		$('.tile').fadeTo(0, 1, 'swing');
		$('#startBtn').css('background-color', 'hsl(0, 100%, 63%)');
		$('#strictBtn').css('background-color', 'hsl(48, 99%, 62%)');
		$('.center').css('background-color', '#bbb');
	}
	else {
		simon.masterSw = false;
		simon.reset();
		disableControls();
		$('.led').removeClass('strictModeOn');
		$('.masterSwWrapper').children('.masterSw').removeClass('active');
		$('.tile').fadeTo(0, 0.7, 'swing');
		$('#startBtn').css('background-color', 'hsl(0, 41%, 43%)');
		$('#strictBtn').css('background-color', 'hsl(48, 46%, 41%)');
		$('.center').css('background-color', '#999');
	}
});

let boardActiveTime = function() {
	clearTimeout(boardTimeoutId);
	boardTimeoutId = setTimeout(function(){
		disableBoard();
		playSeq();

	}, 6000);
}

function enableBoard(){

	boardActiveTime();

	$('.board')
		.on('click', '[data-tile]', function(e){
			let btnSelectd = $(e.target).data('tile');
			inputCheck(btnSelectd);
			boardActiveTime();
		})

		.on('mousedown touchstart', '[data-tile]', function(){
			$(this).addClass('active');

		})

		.on('mouseup mouseout touchend', '[data-tile]', function(){
			$(this).removeClass('active');
		})
}

function disableBoard(){
	$('.board')
		.off('click touchend mousedown touchstart mouseup mouseout');
}

$('body').on('click', '#cog_icon', function(){
	let overl = $('.overlay').hasClass('active');
	if(!overl) {
		$('body, .overlay, .modal-wrapper').removeClass('unactive');
		$('body, .overlay, .modal-wrapper').addClass('active');
	}
	else {
		$('body, .overlay, .modal-wrapper').removeClass('active');
		$('body, .overlay, .modal-wrapper').addClass('unactive');
	}
});
<|endoftext|>


<commit_before>'use strict';

// require your mailgun package
// Adding your key and domain to environment variables
// is important as you don’t want these values
// in your source control or otherwise exposed.
// process.env is an easy way to access your env variables
var   mongoose = require('mongoose'),
      User = mongoose.model('User'),
      mailgun_api = process.env.MAILGUN_API_KEY,
      mailgun_domain = process.env.MAILGUN_DOMAIN,
      Mailgun = require('mailgun-js'),
      Q = require('q'),
      //use nunjucks to render html templates w/ variables
      nunjucks = require('nunjucks');

// function to generate custom email
// for given users and return a mailing array
var mailCreator = function(users) {
  var mailing = [];

  for (var i = users.length - 1; i >= 0; i--) {
    // get an email template and pass in some variables
    var email = nunjucks.renderFile('app/views/templates/email.inlined.template.html', {
      username: users[i].firstName
    });
    // add qualified users and their customized
    // email to the mailing
    mailing.push({
      user: users[i].email,
      email: email
    });
  }

  return mailing;
}

// function to send user email given template and subject
var mailSender = function (userEmail, subject, html) {
    // setup promises
    var deffered = Q.defer();
    // create new mailgun instance with credentials
    var mailgun = new Mailgun({
      apiKey: mailgun_api,
      domain: mailgun_domain
    });
    // setup the basic mail data
    var mailData = {
      from: 'you@yourdomain.com',
      to: userEmail,
      subject:  subject,
      html: html
    };
    // send your mailgun instance the mailData
    mailgun.messages().send(mailData, function (err, body) {
      // If err console.log so we can debug
      if (err) {
        deffered.reject(console.log('failed: ' + err));
      } else {
        deffered.resolve(body)
      }
    });

    return deffered.promise;
};

module.exports.mailSender = mailSender;
module.exports.mailCreator = mailCreator;
<commit_msg>add mailer server routes<commit_after><|endoftext|>


<commit_before>var ProfessorInfo = React.createClass({
  render: function() {
    return (

{this.props.data.name}

    );
  }
});

var ProfessorList = React.createClass({
  dropdown: null,
  searchSchedule: null,
  getProfessor: function(name) {
    $.get({
      url: this.props.url,
      data: { name: name },
      success: (data) => {
        this.dropdown.removeClass("loading");
        this.setState({isLoading: false, data: JSON.parse(data).professors });
      }
    });
  },
  componentDidMount: function() {
    this.dropdown = $(this.props.dropdown);
    this.dropdown.dropdown();
    var input = this.dropdown.find(".search");
    input.change(() => {
      if (!this.state.isLoading) {
        this.setState({isLoading: true});
        this.dropdown.addClass("loading");
      }
      clearTimeout(this.searchSchedule);
      this.searchSchedule = setTimeout(() => {
        this.getProfessor(input.val());
      }, 600);
    });
  },
  getInitialState: function() {
    return { data: [], isLoading: false };
  },
  render: function() {
    var list = this.state.data.map(function(professor) {
      return (
        <ProfessorInfo data={professor} key={professor.id} />
      )
    });

    return (

        {list}

    );
  }
});

function initProfessorFinder(dropdown, container, searchUrl) {
  ReactDOM.render(
    <ProfessorList dropdown={dropdown} url={searchUrl} />,
    $(container)[0]
  );
}
<commit_msg>Remove unused codes<commit_after>
<|endoftext|>


<commit_before>'use strict';

var UIEngine = {
  // shell based on code by Codrops
  // http://tympanus.net/codrops/2013/08/28/transitions-for-off-canvas-navigations/

  _elements:{
    windowObj: $(window),
    siteContainer: $('.site_container'),
    menuButton: $('.site_container-menu-button'),
    menuItems: $('.site_container-menu-nav ul a'),
    menuGroupBtns: $('.site_container-menu-nav input'),
    siteContent: $('.site_container-pusher')
  },
  _animationSmallTime: 500,
  eventtype: null,

  // private funtions and methods
  _addListeners: function(){
    this._elements.menuButton.on('touchstart click', function(e){
      e.stopPropagation();
      e.preventDefault();

      // Side bar listeners
      UIEngine._elements.siteContainer.addClass('site_menu-effect-9');
      setTimeout( function() {
        UIEngine._elements.siteContainer.addClass('site_container-menu__is-open');
      }, 25 );
      UIEngine._elements.siteContent.one('touchstart click', function() {
        UIEngine._closeNav();
      });
      UIEngine._elements.menuItems.one('touchstart click', function() {
        // TODO: load content
        UIEngine._closeNav();
      });
      UIEngine._elements.menuGroupBtns.on('change', function(){
        var input = $(this);
        if(input.prop('checked')){
          input.siblings('ul').slideDown(UIEngine._animationSmallTime);
        }else{
          input.siblings('ul').slideUp(UIEngine._animationSmallTime);
        }
      });

    });
  },
  _closeNav: function() {
    this._elements.siteContainer.removeClass('site_container-menu__is-open');
  },

  // public functions and methods
  init: function() {
    this._addListeners();
    if(this.checkIsMobile()){
      this.eventtype = 'touchstart';
    }else{
      this.eventtype = 'click';
    }
  },
  checkIsMobile: function() {
		var check = false;
    (function(a, b) {
      if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {window.location = b;}
    })(navigator.userAgent || navigator.vendor || window.opera, 'http://detectmobilebrowser.com/mobile');
		return check;
	}
};

$(document).ready(function() {
  UIEngine.init();
});
<commit_msg>improved sidebar navigation behaviour<commit_after>'use strict';

var UIEngine = {
  // shell based on code by Codrops
  // http://tympanus.net/codrops/2013/08/28/transitions-for-off-canvas-navigations/

  _elements:{
    windowObj: $(window),
    site: $('body'),
    siteContainer: $('.site_container'),
    menuButton: $('.site_container-menu-button'),
    menuItems: $('.site_container-menu-nav a'),
    menuGroupBtns: $('.site_container-menu-nav input'),
    siteContent: $('.site_container-pusher')
  },
  _animationSmallTime: 500,
  eventtype: null,

  // private funtions and methods
  _addListeners: function(){
    this._elements.menuButton.on('touchstart click', function(e){
      e.stopPropagation();
      e.preventDefault();

      setTimeout( function() {
        UIEngine._elements.siteContainer.toggleClass('site_container-menu__is-open');
      }, 25 );
    });
    UIEngine._elements.site.on('touchstart click', function(e) {
      console.log(e.target, $(e.target).is('.site_container, .site_container-pusher'));
      if($(e.target).is('.site_container, .site_container-pusher')) {UIEngine._closeNav();}
    });
    UIEngine._elements.menuItems.one('touchstart click', function() {
      // TODO: load content
      UIEngine._closeNav();
    });
    UIEngine._elements.menuGroupBtns.on('change', function(){
      var input = $(this);
      if(input.prop('checked')){
        input.siblings('ul').slideDown(UIEngine._animationSmallTime);
      }else{
        input.siblings('ul').slideUp(UIEngine._animationSmallTime);
      }
    });
  },
  _closeNav: function() {
    this._elements.siteContainer.removeClass('site_container-menu__is-open');
  },

  // public functions and methods
  init: function() {
    this._addListeners();
    if(this.checkIsMobile()){
      this.eventtype = 'touchstart';
    }else{
      this.eventtype = 'click';
    }
  },
  checkIsMobile: function() {
		var check = false;
    (function(a, b) {
      if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {window.location = b;}
    })(navigator.userAgent || navigator.vendor || window.opera, 'http://detectmobilebrowser.com/mobile');
		return check;
	}
};

$(document).ready(function() {
  UIEngine.init();
});
<|endoftext|>


<commit_before>import React from 'react';
import Chartist from 'chartist';

export default class Chart extends React.Component {
  componentDidMount() {
    this.updateChart(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.updateChart(newProps);
  }

  componentWillUnmount() {
    this.chartist && this.chartist.detach();
  }

  render() {
    return

;
  }

  updateChart(configs) {
    const {type, data, options = {}, responsiveOptions = []} = configs;

    data.series && (this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions));
  }
}
<commit_msg>Add props validation<commit_after>import React from 'react';
import Chartist from 'chartist';

export default class Chart extends React.Component {
  componentDidMount() {
    this.updateChart(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.updateChart(newProps);
  }

  componentWillUnmount() {
    this.chartist && this.chartist.detach();
  }

  render() {
    return

;
  }

  updateChart(configs) {
    const {type, data, options = {}, responsiveOptions = []} = configs;

    data.series && (this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions));
  }
}

Chart.propTypes = {
  type: React.PropTypes.string.isRequired,
  data: React.PropTypes.object.isRequired,
  options: React.PropTypes.object,
  responsiveOptions: React.PropTypes.array
};
<|endoftext|>


<commit_before>/*global base64, config, Prism, Konami, translations, START, END, shortcuts, shortcut_names */
(function() {
	'use strict';

	var regexParts = [];

	jQuery(function($) {
		var placeholder = '',
			placeholderItems = 2,
			placeholderStart = false,
			maxSeed = translations.length-1;

		// Make sure we don't make this placeholder too long.
		while (placeholderItems > 0) {
			var lastNum = false,
				seeded = '';

			// If this is the first item, randomly choose whether to show "beginning of the line" or not.
			if (placeholderItems === 2 && doIt()) {
				// START will be in the 'expanded' translations file.
				placeholder+= START+', ';
				placeholderStart = true;
				placeholderItems--;
			}

			seeded = translations[randomInterval(0, maxSeed)];

			// Make sure this isn't one of our catchAll translations as they won't make sense as a placeholder.
			if (seeded.catchAll) {
				continue;
			}

			seeded = seeded.name;

			// If the placeholder has any ? symbols, replace these all with random numbers
			while (/\?/.test(seeded)) {
				// Each part will only ever have max 2 numbers
				lastNum = lastNum === false ? randomInterval(2,5) : randomInterval(6,9);
				// Use normal string replace to only replace first instance each time.
				seeded = seeded.replace('?', lastNum);
			}

			placeholder += seeded+', ';
			placeholderItems--;

			// If there's a space left, it's randomly decided that we want to add the "end", and there's no start of line item.
			if (placeholderItems === 1 && doIt() && !placeholderStart) {
				// END will be in the 'expanded' translations file.
				placeholder+= END;
				placeholderItems--;
			}
		}

		// Prepend our configured text to the placeholder (for example: "Try: ")
		placeholder = config.placeHolderPrepend + placeholder.replace(/, $/, '');

		$('.verbose').keyup(function(e) {
			// If the user presses enter (13), or types a comma (188)
			if (e.keyCode === 13 || e.keyCode === 188) {
				parseInput.call(this, this); // Pass this in as an argument to get around a jshint strict issue in the parseInput function
			}
		}).change(function() {
			parseInput.call(this, this);
		}).attr('placeholder', placeholder);

		$('.result, .copy-result').live('click', function() {
			var height = Number($('.result').outerHeight())+Number($('.result > .part').css('padding-bottom').replace('px', ''))+Number($('.result > .part').css('padding-top').replace('px', ''));

			$('.result-container').addClass('busy-copying');
			$('.copy-me').height(height).select();
		});
		$('.copy-me').live('blur', function() {
			$('.result-container').removeClass('busy-copying');
		});
	});

	/**
	 * Dynmaically add the shortcuts to the help panel
	 * on click, add them to the verbose input, trigger change
	 * and hide the help panel. Replace all ? with a random number.
	 */
	(function helpShortcuts(){
		var current,
			i,
			shortcutItem = '',
			shortcutsList = '';

		for (i = 0; i < shortcut_names.length; i++) {
			shortcutsList += '
' + shortcut_names[i] + '
';
		}

		$('#shortcuts-list').append(shortcutsList);

		$('#shortcuts-list a').on('click', function(e){
			var shortcut = $(this).text();

			current = $.trim($('.verbose').val());

			// If we already have some entered value
			if (current !== '') {
				shortcutItem = current;

				// If it doesn't end in a `,` add one.
				if (/[^,]$/.test(current)) {
					shortcutItem+=',';
				}
			}

			shortcutItem+= shortcut;

			$('.verbose').val(shortcutItem).focus().trigger('change');
			$('.help-tab').trigger('click');

			e.preventDefault();
			return false;
		});

	})();

	/**
	 *	This function receives a string that it parses into a regex Object.
	 */
	function parseInput(input) {
		var parts = input.value.replace(/, /g, ',').split(','),
			regex = strToRegex(parts),
			regexString = '',
			regexStringCopy = '';

		// If this looks like a regex, i.e.: It has anything EXCEPT a comma (since that separates parts in the input) between [] or {}
		if (/(\[[^,]*\]|\{[^,]*\})/.test(input.value)) {
			$('.noticed-regex').show();
		} else {
			$('.noticed-regex').hide();
		}

		for (var i=regex.length; i > 0; i--) {
			regexString+= ''+regex[regex.length-i]+'';
			regexStringCopy+= regex[regex.length-i];
		}

		// If the regex isn't empty, show the result, otherwise empty
		// the result and hide the container
		if ( regex[0] !== '' ) {
			$('.result').html(regexString);
			$('.copy-me').html(regexStringCopy);
			$('.result-container').slideDown(500, function(){
				// after slide down, set visible overflow to ensure
				// that the tooltips are visible above the container
				$('.result-container').css('overflow', 'visible');
			});

			$('.regexplained').attr('href', 'http://regexplained.co.uk/#' + base64.encode(JSON.stringify({pattern: regexStringCopy})));
		} else {
			$('.result').empty();
			$('.copy-me').empty();
			$('.result-container').slideUp();
		}
	}

	/**
	 *	This function receives a string that it parses into a regex Object.
	 *
	 *	@param parts An array of the individual bits of the string to parse
	 *	@returns regexParts The regex parts representing the regex string passed in. Use by doing `regexParts.join()`
	 */
	function strToRegex(parts) {
		// Reset the array.
		regexParts.length = 0;

		for (var i=parts.length; i > 0; i--) {
			var negation = false,
				part = $.trim(parts[parts.length - i]),
				partSolved = false;

			// If this part starts with not/no, trim it out and remember that this is a negation for later.
			if (config.negation.test(part)) {
				part = part.replace(config.negation, '');
				negation = true;
			}

			partSolved = probe(translations, part);

			// If this part has a regex match AND is a negation AND is a range that doesn't already have a negation in it.
			if (partSolved && negation && /\[[^\^]/.test(regexParts[regexParts.length-1])) {
				// Add the ^ symbol to the start of any range that doesn't already have it.
				regexParts[regexParts.length-1] = regexParts[regexParts.length-1].replace(/\[/, '[^');
			}

			// If none of the translations matched, and this part isn't a shortcut then just give back the same as was input.
			if (!partSolved && !probe(shortcuts, part)) {
				regexParts.push(escapeRegExp(part));
			}
		}

		return regexParts;
	}

	/**
	 *	This function probes the given list for the given part.
	 *
	 *	@param list The array of translations/shortcuts we're probing.
	 *	@param part The particular string we're probing for.
	 *	@returns partSolved Whether this particular part was found.
	 */
	function probe(list, part) {
		for (var j=list.length; j > 0; j--) {
			var catchAll,
				regex = new RegExp('^'+list[list.length-j].input+'$');

			// // If this part matches this translation, we have a winner.
			if ( regex.test(part.toLowerCase()) ) {
				if (list[list.length-j].catchAll) {
					// Don't lowercase as the user might expect capitals as input
					catchAll = part.replace(regex, list[list.length-j].output);

					// If the catch all doesn't begin with `[` or `(`
					if (!/^\[/.test(catchAll)) {
						catchAll = escapeRegExp(catchAll);
					}

					regexParts.push(catchAll.replace(/\[\-\]/g, '[\\-]'));
				} else {
					regexParts.push(part.toLowerCase().replace(regex, list[list.length-j].output));
				}

				return true;
			}
		}

		return false;
	}

	// This function was modified, but originally found here: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
	function escapeRegExp(str) {
		return str.replace(/[\-\[\/\{\(\)\*\+\?\.\\\^\$\|\>]/g, "\\$&");
	}

	/**
	 *	Simple function that picks a random number between the given range.
	 *
	 *	@param from The beginning of the range.
	 *	@param to The end of the range.
	 *	@returns A number between `from` and `to`.
	 */
	function randomInterval(from,to) {
		return Math.floor(Math.random()*(to-from+1)+from);
	}

	/**
	 *	This function simply makes a binary decision and returns true/false as required.
	 *
	 *	@returns boolean
	 */
	function doIt() {
		return randomInterval(0, 1) === 1;
	}

	/**
	 * No widows in running text
	 */
	$('p').each(function() {
		$(this).html(function(i, html){
			return html.replace(/\s([\S]+)$/,' $1');
		});
	});

	Prism.highlightAll();

	/*===== Just a little bit of fun. =====*/
	var konami = new Konami();
	konami.code = function() {
		if ($('body').hasClass('excavating')) {
			$('body').removeClass('excavating');
		} else {
			$('body').addClass('excavating');
		}
	};
	konami.load();
})();
<commit_msg>Remove unneeded bit from the test to check for whether regex was put in the verbose field.<commit_after>/*global base64, config, Prism, Konami, translations, START, END, shortcuts, shortcut_names */
(function() {
	'use strict';

	var regexParts = [];

	jQuery(function($) {
		var placeholder = '',
			placeholderItems = 2,
			placeholderStart = false,
			maxSeed = translations.length-1;

		// Make sure we don't make this placeholder too long.
		while (placeholderItems > 0) {
			var lastNum = false,
				seeded = '';

			// If this is the first item, randomly choose whether to show "beginning of the line" or not.
			if (placeholderItems === 2 && doIt()) {
				// START will be in the 'expanded' translations file.
				placeholder+= START+', ';
				placeholderStart = true;
				placeholderItems--;
			}

			seeded = translations[randomInterval(0, maxSeed)];

			// Make sure this isn't one of our catchAll translations as they won't make sense as a placeholder.
			if (seeded.catchAll) {
				continue;
			}

			seeded = seeded.name;

			// If the placeholder has any ? symbols, replace these all with random numbers
			while (/\?/.test(seeded)) {
				// Each part will only ever have max 2 numbers
				lastNum = lastNum === false ? randomInterval(2,5) : randomInterval(6,9);
				// Use normal string replace to only replace first instance each time.
				seeded = seeded.replace('?', lastNum);
			}

			placeholder += seeded+', ';
			placeholderItems--;

			// If there's a space left, it's randomly decided that we want to add the "end", and there's no start of line item.
			if (placeholderItems === 1 && doIt() && !placeholderStart) {
				// END will be in the 'expanded' translations file.
				placeholder+= END;
				placeholderItems--;
			}
		}

		// Prepend our configured text to the placeholder (for example: "Try: ")
		placeholder = config.placeHolderPrepend + placeholder.replace(/, $/, '');

		$('.verbose').keyup(function(e) {
			// If the user presses enter (13), or types a comma (188)
			if (e.keyCode === 13 || e.keyCode === 188) {
				parseInput.call(this, this); // Pass this in as an argument to get around a jshint strict issue in the parseInput function
			}
		}).change(function() {
			parseInput.call(this, this);
		}).attr('placeholder', placeholder);

		$('.result, .copy-result').live('click', function() {
			var height = Number($('.result').outerHeight())+Number($('.result > .part').css('padding-bottom').replace('px', ''))+Number($('.result > .part').css('padding-top').replace('px', ''));

			$('.result-container').addClass('busy-copying');
			$('.copy-me').height(height).select();
		});
		$('.copy-me').live('blur', function() {
			$('.result-container').removeClass('busy-copying');
		});
	});

	/**
	 * Dynmaically add the shortcuts to the help panel
	 * on click, add them to the verbose input, trigger change
	 * and hide the help panel. Replace all ? with a random number.
	 */
	(function helpShortcuts(){
		var current,
			i,
			shortcutItem = '',
			shortcutsList = '';

		for (i = 0; i < shortcut_names.length; i++) {
			shortcutsList += '
' + shortcut_names[i] + '
';
		}

		$('#shortcuts-list').append(shortcutsList);

		$('#shortcuts-list a').on('click', function(e){
			var shortcut = $(this).text();

			current = $.trim($('.verbose').val());

			// If we already have some entered value
			if (current !== '') {
				shortcutItem = current;

				// If it doesn't end in a `,` add one.
				if (/[^,]$/.test(current)) {
					shortcutItem+=',';
				}
			}

			shortcutItem+= shortcut;

			$('.verbose').val(shortcutItem).focus().trigger('change');
			$('.help-tab').trigger('click');

			e.preventDefault();
			return false;
		});

	})();

	/**
	 *	This function receives a string that it parses into a regex Object.
	 */
	function parseInput(input) {
		var parts = input.value.replace(/, /g, ',').split(','),
			regex = strToRegex(parts),
			regexString = '',
			regexStringCopy = '';

		// If this looks like a regex, i.e.: It has anything EXCEPT a comma (since that separates parts in the input) between [] or {}
		if (/(\[[^,]*\])/.test(input.value)) {
			$('.noticed-regex').show();
		} else {
			$('.noticed-regex').hide();
		}

		for (var i=regex.length; i > 0; i--) {
			regexString+= ''+regex[regex.length-i]+'';
			regexStringCopy+= regex[regex.length-i];
		}

		// If the regex isn't empty, show the result, otherwise empty
		// the result and hide the container
		if ( regex[0] !== '' ) {
			$('.result').html(regexString);
			$('.copy-me').html(regexStringCopy);
			$('.result-container').slideDown(500, function(){
				// after slide down, set visible overflow to ensure
				// that the tooltips are visible above the container
				$('.result-container').css('overflow', 'visible');
			});

			$('.regexplained').attr('href', 'http://regexplained.co.uk/#' + base64.encode(JSON.stringify({pattern: regexStringCopy})));
		} else {
			$('.result').empty();
			$('.copy-me').empty();
			$('.result-container').slideUp();
		}
	}

	/**
	 *	This function receives a string that it parses into a regex Object.
	 *
	 *	@param parts An array of the individual bits of the string to parse
	 *	@returns regexParts The regex parts representing the regex string passed in. Use by doing `regexParts.join()`
	 */
	function strToRegex(parts) {
		// Reset the array.
		regexParts.length = 0;

		for (var i=parts.length; i > 0; i--) {
			var negation = false,
				part = $.trim(parts[parts.length - i]),
				partSolved = false;

			// If this part starts with not/no, trim it out and remember that this is a negation for later.
			if (config.negation.test(part)) {
				part = part.replace(config.negation, '');
				negation = true;
			}

			partSolved = probe(translations, part);

			// If this part has a regex match AND is a negation AND is a range that doesn't already have a negation in it.
			if (partSolved && negation && /\[[^\^]/.test(regexParts[regexParts.length-1])) {
				// Add the ^ symbol to the start of any range that doesn't already have it.
				regexParts[regexParts.length-1] = regexParts[regexParts.length-1].replace(/\[/, '[^');
			}

			// If none of the translations matched, and this part isn't a shortcut then just give back the same as was input.
			if (!partSolved && !probe(shortcuts, part)) {
				regexParts.push(escapeRegExp(part));
			}
		}

		return regexParts;
	}

	/**
	 *	This function probes the given list for the given part.
	 *
	 *	@param list The array of translations/shortcuts we're probing.
	 *	@param part The particular string we're probing for.
	 *	@returns partSolved Whether this particular part was found.
	 */
	function probe(list, part) {
		for (var j=list.length; j > 0; j--) {
			var catchAll,
				regex = new RegExp('^'+list[list.length-j].input+'$');

			// // If this part matches this translation, we have a winner.
			if ( regex.test(part.toLowerCase()) ) {
				if (list[list.length-j].catchAll) {
					// Don't lowercase as the user might expect capitals as input
					catchAll = part.replace(regex, list[list.length-j].output);

					// If the catch all doesn't begin with `[` or `(`
					if (!/^\[/.test(catchAll)) {
						catchAll = escapeRegExp(catchAll);
					}

					regexParts.push(catchAll.replace(/\[\-\]/g, '[\\-]'));
				} else {
					regexParts.push(part.toLowerCase().replace(regex, list[list.length-j].output));
				}

				return true;
			}
		}

		return false;
	}

	// This function was modified, but originally found here: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
	function escapeRegExp(str) {
		return str.replace(/[\-\[\/\{\(\)\*\+\?\.\\\^\$\|\>]/g, "\\$&");
	}

	/**
	 *	Simple function that picks a random number between the given range.
	 *
	 *	@param from The beginning of the range.
	 *	@param to The end of the range.
	 *	@returns A number between `from` and `to`.
	 */
	function randomInterval(from,to) {
		return Math.floor(Math.random()*(to-from+1)+from);
	}

	/**
	 *	This function simply makes a binary decision and returns true/false as required.
	 *
	 *	@returns boolean
	 */
	function doIt() {
		return randomInterval(0, 1) === 1;
	}

	/**
	 * No widows in running text
	 */
	$('p').each(function() {
		$(this).html(function(i, html){
			return html.replace(/\s([\S]+)$/,' $1');
		});
	});

	Prism.highlightAll();

	/*===== Just a little bit of fun. =====*/
	var konami = new Konami();
	konami.code = function() {
		if ($('body').hasClass('excavating')) {
			$('body').removeClass('excavating');
		} else {
			$('body').addClass('excavating');
		}
	};
	konami.load();
})();
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// react-native-cli is installed globally on people's computers. This means
// that it is extremely difficult to have them upgrade the version and
// because there's only one global version installed, it is very prone to
// breaking changes.
//
// The only job of react-native-cli is to init the repository and then
// forward all the commands to the local version of react-native.
//
// If you need to add a new command, please add it to local-cli/.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `react-native init` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of react-native-cli.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'use strict';

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var chalk = require('chalk');
var prompt = require('prompt');
var semver = require('semver');

var CLI_MODULE_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'cli.js'
  );
};

var REACT_NATIVE_PACKAGE_JSON_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'package.json'
  );
};

checkForVersionArgument();

var cli;
var cliPath = CLI_MODULE_PATH();
if (fs.existsSync(cliPath)) {
  cli = require(cliPath);
}

if (cli) {
  cli.run();
} else {
  var args = process.argv.slice(2);
  if (args.length === 0) {
    console.error(
      'You did not pass any commands, did you mean to run `react-native init`?'
    );
    process.exit(1);
  }

  switch (args[0]) {
  case 'init':
    if (args[1]) {
      var verbose = process.argv.indexOf('--verbose') >= 0;
      init(args[1], verbose);
    } else {
      console.error(
        'Usage: react-native init <ProjectName> [--verbose]'
      );
      process.exit(1);
    }
    break;
  default:
    console.error(
      'Command `%s` unrecognized. ' +
      'Did you mean to run this inside a react-native project?',
      args[0]
    );
    process.exit(1);
    break;
  }
}

function validatePackageName(name) {
  if (!name.match(/^[$A-Z_][0-9A-Z_$]*$/i)) {
    console.error(
      '"%s" is not a valid name for a project. Please use a valid identifier ' +
        'name (alphanumeric).',
      name
    );
    process.exit(1);
  }

  if (name === 'React') {
    console.error(
      '"%s" is not a valid name for a project. Please do not use the ' +
        'reserved word "React".',
      name
    );
    process.exit(1);
  }
}

function init(name, verbose) {
  validatePackageName(name);

  if (fs.existsSync(name)) {
    createAfterConfirmation(name, verbose);
  } else {
    createProject(name, verbose);
  }
}

function createAfterConfirmation(name, verbose) {
  prompt.start();

  var property = {
    name: 'yesno',
    message: 'Directory ' + name + ' already exists. Continue?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'no'
  };

  prompt.get(property, function (err, result) {
    if (result.yesno[0] === 'y') {
      createProject(name, verbose);
    } else {
      console.log('Project initialization canceled');
      process.exit();
    }
  });
}

function createProject(name, verbose) {
  var root = path.resolve(name);
  var projectName = path.basename(root);

  console.log(
    'This will walk you through creating a new React Native project in',
    root
  );

  if (!fs.existsSync(root)) {
    fs.mkdirSync(root);
  }

  var packageJson = {
    name: projectName,
    version: '0.0.1',
    private: true,
    scripts: {
      start: 'react-native start'
    }
  };
  fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJson));
  process.chdir(root);

  console.log('Installing react-native package from npm...');

  if (verbose) {
    runVerbose(root, projectName);
  } else {
    run(root, projectName);
  }
}

function run(root, projectName) {
  exec('npm install --save react-native', function(e, stdout, stderr) {
    if (e) {
      console.log(stdout);
      console.error(stderr);
      console.error('`npm install --save react-native` failed');
      process.exit(1);
    }

    checkNodeVersion();

    var cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function runVerbose(root, projectName) {
  var proc = spawn('npm', ['install', '--verbose', '--save', 'react-native'], {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm install --save react-native` failed');
      return;
    }

    cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function checkNodeVersion() {
  var packageJson = require(REACT_NATIVE_PACKAGE_JSON_PATH());
  if (!packageJson.engines || !packageJson.engines.node) {
    return;
  }
  if (!semver.satisfies(process.version, packageJson.engines.node)) {
    console.error(chalk.red(
        'You are currently running Node %s but React Native requires %s. ' +
        'Please use a supported version of Node.\n' +
        'See https://facebook.github.io/react-native/docs/getting-started.html'
      ),
      process.version,
      packageJson.engines.node);
  }
}

function checkForVersionArgument() {
  if (process.argv.indexOf('-v') >= 0 || process.argv.indexOf('--version') >= 0) {
    var pjson = require('./package.json');
    console.log(pjson.version);
    process.exit();
  }
}
<commit_msg>npm progress shown on react init fixes #3771 for npm 5 and upwards<commit_after>#!/usr/bin/env node

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// react-native-cli is installed globally on people's computers. This means
// that it is extremely difficult to have them upgrade the version and
// because there's only one global version installed, it is very prone to
// breaking changes.
//
// The only job of react-native-cli is to init the repository and then
// forward all the commands to the local version of react-native.
//
// If you need to add a new command, please add it to local-cli/.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `react-native init` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of react-native-cli.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'use strict';

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var chalk = require('chalk');
var prompt = require('prompt');
var semver = require('semver');

var CLI_MODULE_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'cli.js'
  );
};

var REACT_NATIVE_PACKAGE_JSON_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'package.json'
  );
};

checkForVersionArgument();

var cli;
var cliPath = CLI_MODULE_PATH();
if (fs.existsSync(cliPath)) {
  cli = require(cliPath);
}

if (cli) {
  cli.run();
} else {
  var args = process.argv.slice(2);
  if (args.length === 0) {
    console.error(
      'You did not pass any commands, did you mean to run `react-native init`?'
    );
    process.exit(1);
  }

  switch (args[0]) {
  case 'init':
    if (args[1]) {
      var verbose = process.argv.indexOf('--verbose') >= 0;
      init(args[1], verbose);
    } else {
      console.error(
        'Usage: react-native init <ProjectName> [--verbose]'
      );
      process.exit(1);
    }
    break;
  default:
    console.error(
      'Command `%s` unrecognized. ' +
      'Did you mean to run this inside a react-native project?',
      args[0]
    );
    process.exit(1);
    break;
  }
}

function validatePackageName(name) {
  if (!name.match(/^[$A-Z_][0-9A-Z_$]*$/i)) {
    console.error(
      '"%s" is not a valid name for a project. Please use a valid identifier ' +
        'name (alphanumeric).',
      name
    );
    process.exit(1);
  }

  if (name === 'React') {
    console.error(
      '"%s" is not a valid name for a project. Please do not use the ' +
        'reserved word "React".',
      name
    );
    process.exit(1);
  }
}

function init(name, verbose) {
  validatePackageName(name);

  if (fs.existsSync(name)) {
    createAfterConfirmation(name, verbose);
  } else {
    createProject(name, verbose);
  }
}

function createAfterConfirmation(name, verbose) {
  prompt.start();

  var property = {
    name: 'yesno',
    message: 'Directory ' + name + ' already exists. Continue?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'no'
  };

  prompt.get(property, function (err, result) {
    if (result.yesno[0] === 'y') {
      createProject(name, verbose);
    } else {
      console.log('Project initialization canceled');
      process.exit();
    }
  });
}

function createProject(name, verbose) {
  var root = path.resolve(name);
  var projectName = path.basename(root);

  console.log(
    'This will walk you through creating a new React Native project in',
    root
  );

  if (!fs.existsSync(root)) {
    fs.mkdirSync(root);
  }

  var packageJson = {
    name: projectName,
    version: '0.0.1',
    private: true,
    scripts: {
      start: 'react-native start'
    }
  };
  fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJson));
  process.chdir(root);

  console.log('Installing react-native package from npm...');

  run(root, projectName, verbose);
}

function run(root, projectName, verbose) {
  var args = ['install', '--save'];
  if (verbose){
    args.push('--verbose');
  }
  args.push('react-native');
  var proc = spawn('npm', args, {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm install --save react-native` failed');
      return;
    }

    checkNodeVersion();

    cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function checkNodeVersion() {
  var packageJson = require(REACT_NATIVE_PACKAGE_JSON_PATH());
  if (!packageJson.engines || !packageJson.engines.node) {
    return;
  }
  if (!semver.satisfies(process.version, packageJson.engines.node)) {
    console.error(chalk.red(
        'You are currently running Node %s but React Native requires %s. ' +
        'Please use a supported version of Node.\n' +
        'See https://facebook.github.io/react-native/docs/getting-started.html'
      ),
      process.version,
      packageJson.engines.node);
  }
}

function checkForVersionArgument() {
  if (process.argv.indexOf('-v') >= 0 || process.argv.indexOf('--version') >= 0) {
    var pjson = require('./package.json');
    console.log(pjson.version);
    process.exit();
  }
}
<|endoftext|>


<commit_before>$_('game').main(function(){
    var engine= $_('gEngine');

    engine.newGame({
        playerFile : 'characters/player.json',
        dateFile : 'characters/ariane.json',
        canvas : $('dom').select('canvas')
    }).then(function(){
        engine.createLocation('home', [
            'scenes/opening.json',
            'scenes/get_to_know.json',
            'scenes/livingroom_sofa.json',
            'scenes/map_home.json',
            'scripts/actions/opening.js'
        ]);

        engine.loadLocation('home').then(function(){
//          everything loaded ready to play load first scene
            $$.console.log('ready!!');
            engine.goToScene('opening');
        });
    });
});<commit_msg>remove debug<commit_after>$_('game').main(function(){
    var engine= $_('gEngine');

    engine.newGame({
        playerFile : 'characters/player.json',
        dateFile : 'characters/ariane.json',
        canvas : $('dom').select('canvas')
    }).then(function(){
        engine.createLocation('home', [
            'scenes/opening.json',
            'scenes/get_to_know.json',
            'scenes/livingroom_sofa.json',
            'scenes/map_home.json',
            'scripts/actions/opening.js'
        ]);

        engine.loadLocation('home').then(function(){
//          everything loaded ready to play load first scene
            engine.goToScene('opening');
        });
    });
});<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// react-native-cli is installed globally on people's computers. This means
// that it is extremely difficult to have them upgrade the version and
// because there's only one global version installed, it is very prone to
// breaking changes.
//
// The only job of react-native-cli is to init the repository and then
// forward all the commands to the local version of react-native.
//
// If you need to add a new command, please add it to local-cli/.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `react-native init` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of react-native-cli.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'use strict';

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var chalk = require('chalk');
var prompt = require('prompt');
var semver = require('semver');
/**
 * Used arguments:
 *   -v --version - to print current version of react-native-cli and react-native dependency
 *   if you are in a RN app folder
 * init - to create a new project and npm install it
 *   --verbose - to print logs while init
 *   --version <alternative react-native package> - override default (https://registry.npmjs.org/react-native@latest),
 *      package to install, examples:
 *     - "0.22.0-rc1" - A new app will be created using a specific version of React Native from npm repo
 *     - "https://registry.npmjs.org/react-native/-/react-native-0.20.0.tgz" - a .tgz archive from any npm repo
 *     - "/Users/home/react-native/react-native-0.22.0.tgz" - for package prepared with `npm pack`, useful for e2e tests
 */
var argv = require('minimist')(process.argv.slice(2));

var CLI_MODULE_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'cli.js'
  );
};

var REACT_NATIVE_PACKAGE_JSON_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'package.json'
  );
};

checkForVersionArgument();

var cli;
var cliPath = CLI_MODULE_PATH();
if (fs.existsSync(cliPath)) {
  cli = require(cliPath);
}

// minimist api
var commands = argv._;
if (cli) {
  cli.run();
} else {
  if (commands.length === 0) {
    console.error(
      'You did not pass any commands, did you mean to run `react-native init`?'
    );
    process.exit(1);
  }

  switch (commands[0]) {
  case 'init':
    if (!commands[1]) {
      console.error(
        'Usage: react-native init <ProjectName> [--verbose]'
      );
      process.exit(1);
    } else {
      if (!argv.verbose) console.log('This may take some time...');
      init(commands[1], argv.verbose, argv.version);
    }
    break;
  default:
    console.error(
      'Command `%s` unrecognized. ' +
      'Make sure that you have run `npm install` and that you are inside a react-native project.',
      commands[0]
    );
    process.exit(1);
    break;
  }
}

function validatePackageName(name) {
  if (!name.match(/^[$A-Z_][0-9A-Z_$]*$/i)) {
    console.error(
      '"%s" is not a valid name for a project. Please use a valid identifier ' +
        'name (alphanumeric).',
      name
    );
    process.exit(1);
  }

  if (name === 'React') {
    console.error(
      '"%s" is not a valid name for a project. Please do not use the ' +
        'reserved word "React".',
      name
    );
    process.exit(1);
  }
}

function init(name, verbose, rnPackage) {
  validatePackageName(name);

  if (fs.existsSync(name)) {
    createAfterConfirmation(name, verbose, rnPackage);
  } else {
    createProject(name, verbose, rnPackage);
  }
}

function createAfterConfirmation(name, verbose, rnPackage) {
  prompt.start();

  var property = {
    name: 'yesno',
    message: 'Directory ' + name + ' already exists. Continue?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'no'
  };

  prompt.get(property, function (err, result) {
    if (result.yesno[0] === 'y') {
      createProject(name, verbose, rnPackage);
    } else {
      console.log('Project initialization canceled');
      process.exit();
    }
  });
}

function createProject(name, verbose, rnPackage) {
  var root = path.resolve(name);
  var projectName = path.basename(root);

  console.log(
    'This will walk you through creating a new React Native project in',
    root
  );

  if (!fs.existsSync(root)) {
    fs.mkdirSync(root);
  }

  var packageJson = {
    name: projectName,
    version: '0.0.1',
    private: true,
    scripts: {
      start: 'node node_modules/react-native/local-cli/cli.js start'
    }
  };
  fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJson));
  process.chdir(root);

  console.log('Installing react-native package from npm...');

  if (verbose) {
    runVerbose(root, projectName, rnPackage);
  } else {
    run(root, projectName, rnPackage);
  }
}

function getInstallPackage(rnPackage) {
  var packageToInstall = 'react-native';
  var valideSemver = semver.valid(rnPackage);
  if (valideSemver) {
    packageToInstall += '@' + valideSemver;
  } else if (rnPackage) {
    // for tar.gz or alternative paths
    packageToInstall = rnPackage;
  }
  return packageToInstall;
}

function run(root, projectName, rnPackage) {
  exec('npm install --save --save-exact ' + getInstallPackage(rnPackage), function(e, stdout, stderr) {
    if (e) {
      console.log(stdout);
      console.error(stderr);
      console.error('`npm install --save --save-exact react-native` failed');
      process.exit(1);
    }

    checkNodeVersion();

    var cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function runVerbose(root, projectName, rnPackage) {
  var proc = spawn('npm', ['install', '--verbose', '--save', '--save-exact', getInstallPackage(rnPackage)], {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm install --save --save-exact react-native` failed');
      return;
    }

    cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function checkNodeVersion() {
  var packageJson = require(REACT_NATIVE_PACKAGE_JSON_PATH());
  if (!packageJson.engines || !packageJson.engines.node) {
    return;
  }
  if (!semver.satisfies(process.version, packageJson.engines.node)) {
    console.error(chalk.red(
        'You are currently running Node %s but React Native requires %s. ' +
        'Please use a supported version of Node.\n' +
        'See https://facebook.github.io/react-native/docs/getting-started.html'
      ),
      process.version,
      packageJson.engines.node);
  }
}

function checkForVersionArgument() {
  if (argv._.length === 0 && (argv.v || argv.version)) {
    console.log('react-native-cli: ' + require('./package.json').version);
    try {
      console.log('react-native: ' + require(REACT_NATIVE_PACKAGE_JSON_PATH()).version);
    } catch (e) {
      console.log('react-native: n/a - not inside a React Native project directory');
    }
    process.exit();
  }
}
<commit_msg>remove the unnecessary 'var' in `runVerbose`<commit_after>#!/usr/bin/env node

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// react-native-cli is installed globally on people's computers. This means
// that it is extremely difficult to have them upgrade the version and
// because there's only one global version installed, it is very prone to
// breaking changes.
//
// The only job of react-native-cli is to init the repository and then
// forward all the commands to the local version of react-native.
//
// If you need to add a new command, please add it to local-cli/.
//
// The only reason to modify this file is to add more warnings and
// troubleshooting information for the `react-native init` command.
//
// Do not make breaking changes! We absolutely don't want to have to
// tell people to update their global version of react-native-cli.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// /!\ DO NOT MODIFY THIS FILE /!\
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

'use strict';

var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var chalk = require('chalk');
var prompt = require('prompt');
var semver = require('semver');
/**
 * Used arguments:
 *   -v --version - to print current version of react-native-cli and react-native dependency
 *   if you are in a RN app folder
 * init - to create a new project and npm install it
 *   --verbose - to print logs while init
 *   --version <alternative react-native package> - override default (https://registry.npmjs.org/react-native@latest),
 *      package to install, examples:
 *     - "0.22.0-rc1" - A new app will be created using a specific version of React Native from npm repo
 *     - "https://registry.npmjs.org/react-native/-/react-native-0.20.0.tgz" - a .tgz archive from any npm repo
 *     - "/Users/home/react-native/react-native-0.22.0.tgz" - for package prepared with `npm pack`, useful for e2e tests
 */
var argv = require('minimist')(process.argv.slice(2));

var CLI_MODULE_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'cli.js'
  );
};

var REACT_NATIVE_PACKAGE_JSON_PATH = function() {
  return path.resolve(
    process.cwd(),
    'node_modules',
    'react-native',
    'package.json'
  );
};

checkForVersionArgument();

var cli;
var cliPath = CLI_MODULE_PATH();
if (fs.existsSync(cliPath)) {
  cli = require(cliPath);
}

// minimist api
var commands = argv._;
if (cli) {
  cli.run();
} else {
  if (commands.length === 0) {
    console.error(
      'You did not pass any commands, did you mean to run `react-native init`?'
    );
    process.exit(1);
  }

  switch (commands[0]) {
  case 'init':
    if (!commands[1]) {
      console.error(
        'Usage: react-native init <ProjectName> [--verbose]'
      );
      process.exit(1);
    } else {
      if (!argv.verbose) console.log('This may take some time...');
      init(commands[1], argv.verbose, argv.version);
    }
    break;
  default:
    console.error(
      'Command `%s` unrecognized. ' +
      'Make sure that you have run `npm install` and that you are inside a react-native project.',
      commands[0]
    );
    process.exit(1);
    break;
  }
}

function validatePackageName(name) {
  if (!name.match(/^[$A-Z_][0-9A-Z_$]*$/i)) {
    console.error(
      '"%s" is not a valid name for a project. Please use a valid identifier ' +
        'name (alphanumeric).',
      name
    );
    process.exit(1);
  }

  if (name === 'React') {
    console.error(
      '"%s" is not a valid name for a project. Please do not use the ' +
        'reserved word "React".',
      name
    );
    process.exit(1);
  }
}

function init(name, verbose, rnPackage) {
  validatePackageName(name);

  if (fs.existsSync(name)) {
    createAfterConfirmation(name, verbose, rnPackage);
  } else {
    createProject(name, verbose, rnPackage);
  }
}

function createAfterConfirmation(name, verbose, rnPackage) {
  prompt.start();

  var property = {
    name: 'yesno',
    message: 'Directory ' + name + ' already exists. Continue?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'no'
  };

  prompt.get(property, function (err, result) {
    if (result.yesno[0] === 'y') {
      createProject(name, verbose, rnPackage);
    } else {
      console.log('Project initialization canceled');
      process.exit();
    }
  });
}

function createProject(name, verbose, rnPackage) {
  var root = path.resolve(name);
  var projectName = path.basename(root);

  console.log(
    'This will walk you through creating a new React Native project in',
    root
  );

  if (!fs.existsSync(root)) {
    fs.mkdirSync(root);
  }

  var packageJson = {
    name: projectName,
    version: '0.0.1',
    private: true,
    scripts: {
      start: 'node node_modules/react-native/local-cli/cli.js start'
    }
  };
  fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify(packageJson));
  process.chdir(root);

  console.log('Installing react-native package from npm...');

  if (verbose) {
    runVerbose(root, projectName, rnPackage);
  } else {
    run(root, projectName, rnPackage);
  }
}

function getInstallPackage(rnPackage) {
  var packageToInstall = 'react-native';
  var valideSemver = semver.valid(rnPackage);
  if (valideSemver) {
    packageToInstall += '@' + valideSemver;
  } else if (rnPackage) {
    // for tar.gz or alternative paths
    packageToInstall = rnPackage;
  }
  return packageToInstall;
}

function run(root, projectName, rnPackage) {
  exec('npm install --save --save-exact ' + getInstallPackage(rnPackage), function(e, stdout, stderr) {
    if (e) {
      console.log(stdout);
      console.error(stderr);
      console.error('`npm install --save --save-exact react-native` failed');
      process.exit(1);
    }

    checkNodeVersion();

    cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function runVerbose(root, projectName, rnPackage) {
  var proc = spawn('npm', ['install', '--verbose', '--save', '--save-exact', getInstallPackage(rnPackage)], {stdio: 'inherit'});
  proc.on('close', function (code) {
    if (code !== 0) {
      console.error('`npm install --save --save-exact react-native` failed');
      return;
    }

    cli = require(CLI_MODULE_PATH());
    cli.init(root, projectName);
  });
}

function checkNodeVersion() {
  var packageJson = require(REACT_NATIVE_PACKAGE_JSON_PATH());
  if (!packageJson.engines || !packageJson.engines.node) {
    return;
  }
  if (!semver.satisfies(process.version, packageJson.engines.node)) {
    console.error(chalk.red(
        'You are currently running Node %s but React Native requires %s. ' +
        'Please use a supported version of Node.\n' +
        'See https://facebook.github.io/react-native/docs/getting-started.html'
      ),
      process.version,
      packageJson.engines.node);
  }
}

function checkForVersionArgument() {
  if (argv._.length === 0 && (argv.v || argv.version)) {
    console.log('react-native-cli: ' + require('./package.json').version);
    try {
      console.log('react-native: ' + require(REACT_NATIVE_PACKAGE_JSON_PATH()).version);
    } catch (e) {
      console.log('react-native: n/a - not inside a React Native project directory');
    }
    process.exit();
  }
}
<|endoftext|>


<commit_before>(function ($) {
  Moebooru = {
    '__slug__': {}
  };
  Moe = $(Moebooru);

  Moebooru.addData = function (data) {
    if (data.posts)
      Moe.trigger("post:add", [data.posts]);
    if (data.tags)
      Moe.trigger("tag:add", [data.tags]);
    if (data.votes)
      Moe.trigger("vote:add", [data.votes]);
    if (data.voted_by)
      Moe.trigger("vote:add_user_list", [data.voted_by]);
    if (data.pools)
      Moe.trigger("pool:add", [data.pools]);
    if (data.pool_posts)
      Moe.trigger("pool:add_post", {
        pool_posts: data.pool_posts,
        posts: data.posts
      });
  };

  Moebooru.attach = function (key, obj) {
    Moebooru['__slug__'][key] = obj;
  };

  Moebooru.get = function (key) {
   return Moebooru['__slug__'][key];
  };

  Moebooru.request = function (url, params/*, type */) {
    $.ajax({
      url: Moebooru.path(url),
      type: arguments[2] || 'POST',
      dataType: 'json',
      data: params,
      statusCode: {
        403: function () {
          notice(t('error')+': '+t('denied'));
        }
      }
    }).done(function (data) {
      Moe.trigger(url+":ready", [data]);
    }).fail(function () {
      notice(t('error'));
    });
  };

  Moebooru.path = function (url) {
    return PREFIX === '/' ? url : PREFIX + url;
  }

  // XXX: Tested on chrome, mozilla, msie(9/10)
  // might or might not works in other browser
  Moebooru.dragElement = function(el) {
    var win = $(window), doc = $(document),
        prevPos = {x:-1, y:-1},
        button = 0;

    el.on('dragstart', function () { return false; });

    el.on('mousedown', function (e) {
      prevPos = {x: e.clientX, y: e.clientY};
      button = e.which;
      el.css('cursor', 'pointer');
      return false;
    });

    el.on('mousemove', function (e) {
      if (button === 1) {
        var scroll = current(e.clientX, e.clientY);
        scrollTo(scroll[0], scroll[1]);
      }
      return false;
    });

    doc.on('mouseup', function (e) {
      button = 0;
      el.css('cursor', 'auto');
      return false;
    });

    function current(x, y) {
      var off = [window.pageXOffset || document.documentElement.scrollLeft||document.body.scrollLeft,
                 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop],
          offset = [off[0] + (prevPos.x - x), off[1] + (prevPos.y - y)];
      offset[0] = (prevPos.x === x) ? off[0] : offset[0];
      offset[1] = (prevPos.y === y) ? off[1] : offset[1];
      prevPos.x = x; prevPos.y = y;
      return offset;
    }
  }
})(jQuery);
<commit_msg>Only save prevPos and set cursor when left button clicked<commit_after>(function ($) {
  Moebooru = {
    '__slug__': {}
  };
  Moe = $(Moebooru);

  Moebooru.addData = function (data) {
    if (data.posts)
      Moe.trigger("post:add", [data.posts]);
    if (data.tags)
      Moe.trigger("tag:add", [data.tags]);
    if (data.votes)
      Moe.trigger("vote:add", [data.votes]);
    if (data.voted_by)
      Moe.trigger("vote:add_user_list", [data.voted_by]);
    if (data.pools)
      Moe.trigger("pool:add", [data.pools]);
    if (data.pool_posts)
      Moe.trigger("pool:add_post", {
        pool_posts: data.pool_posts,
        posts: data.posts
      });
  };

  Moebooru.attach = function (key, obj) {
    Moebooru['__slug__'][key] = obj;
  };

  Moebooru.get = function (key) {
   return Moebooru['__slug__'][key];
  };

  Moebooru.request = function (url, params/*, type */) {
    $.ajax({
      url: Moebooru.path(url),
      type: arguments[2] || 'POST',
      dataType: 'json',
      data: params,
      statusCode: {
        403: function () {
          notice(t('error')+': '+t('denied'));
        }
      }
    }).done(function (data) {
      Moe.trigger(url+":ready", [data]);
    }).fail(function () {
      notice(t('error'));
    });
  };

  Moebooru.path = function (url) {
    return PREFIX === '/' ? url : PREFIX + url;
  }

  // XXX: Tested on chrome, mozilla, msie(9/10)
  // might or might not works in other browser
  Moebooru.dragElement = function(el) {
    var win = $(window), doc = $(document),
        prevPos = {x:-1, y:-1},
        button = 0;

    el.on('dragstart', function () { return false; });

    el.on('mousedown', function (e) {
      button = e.which;
      if (button == 1) {
        el.css('cursor', 'pointer');
        prevPos = {x: e.clientX, y: e.clientY};
      }
      return false;
    });

    el.on('mousemove', function (e) {
      if (button === 1) {
        var scroll = current(e.clientX, e.clientY);
        scrollTo(scroll[0], scroll[1]);
      }
      return false;
    });

    doc.on('mouseup', function (e) {
      button = 0;
      el.css('cursor', 'auto');
      return false;
    });

    function current(x, y) {
      var off = [window.pageXOffset || document.documentElement.scrollLeft||document.body.scrollLeft,
                 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop],
          offset = [off[0] + (prevPos.x - x), off[1] + (prevPos.y - y)];
      offset[0] = (prevPos.x === x) ? off[0] : offset[0];
      offset[1] = (prevPos.y === y) ? off[1] : offset[1];
      prevPos.x = x; prevPos.y = y;
      return offset;
    }
  }
})(jQuery);
<|endoftext|>


<commit_before>$(document).ready(function() {
  initTwitter();
  initTabIndexes();
  setupShareFacebookButton();
  setupSocialTracking();

  if(screen.width > 480) {
    $('#thanksModal').modal('toggle');
  }

  preventWhitespaceOn('#signature_email');
  applyRichTextEditorTo('#petition_description');

  $('form').on("submit", function(event) {
    if(!VK.signing_from_email) {
      var emailSuggestor = new EmailSuggestions();
      emailSuggestor.init();
      emailSuggestor.mailCheckSuggestions(event);
    }
    return event.go;
  });

  if($('#email_subject').has('.additional_title').length) {
    $('#email_subject').show();
    $('#email_subject_link').hide();
  }

  $('#email_subject_link').click(function() {
    $('#email_subject').show();
    $('#email_subject input').focus();
    $('#email_subject_link').hide();
  });

  if($('#facebook_title').has('.additional_title').length) {
    $('#facebook_title').show();
    $('#facebook_title_link').hide();
  }

  $('#facebook_title_link').click(function() {
    $('#facebook_title').show();
    $('#facebook_title_link').hide();
  });
});

function setupSocialTracking() {
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
        //Google doesn't export social event data yet, so we have to track social actions as events too
        _gaq.push(['_trackEvent', 'facebook', 'like', targetUrl]);
        $.ajax({
          url: VK.social_tracking_url,
          data: setUpParamsForSocialTracking('like','')
        });
        $('.tweet').show();
      });
      FB.Event.subscribe('edge.remove', function(targetUrl){
        _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
        _gaq.push(['_trackEvent', 'facebook', 'unlike', targetUrl]);
      });
    }
  } catch(e) {}
}

function setUpParamsForSocialTracking(facebook_action, action_id) {
  var params = {petition_id: VK.petition_id, facebook_action: facebook_action};
  if (VK.signature_id != "") {
    params = $.extend(params, {signature_id: VK.signature_id});
  }
  if(action_id != ""){
    params = $.extend(params, {action_id: action_id});
  }

  return params;
}

function setupShareFacebookButton() {
  var shareButton = $('.fb_share.btn')
  shareButton.click(function(event) {
    shareButton.hide();
    $('.tweet').show();
    $('#thanks-for-signing-message .share').text("Spread the word, share on Twitter!");
    submitFacebookAction();
  });
}

function submitFacebookAction() {
  FB.init({
    appId      : $('meta[property="fb:app_id"]').attr("content"),
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  FB.login(function(response) {
    if (response.authResponse) {
      console.log('Welcome!  Fetching your information.... ');
      FB.api(
        '/me/watchdognet:sign',
        'post',
        {
          petition: $('meta[property="og:url"]').attr("content")
        },
        function(response) {
          if (!response || response.error) {
            console.log('Error occured');
            console.log(response.error);
          } else {
            $.ajax({
            url: VK.social_tracking_url,
            data: setUpParamsForSocialTracking('share', response.id)
            });
            console.log('Sign was successful! Action ID: ' + response.id);
          }
        });
    } else {
      console.log('User cancelled login or did not fully authorize.');
    }}, {scope: 'publish_actions'});
}

function initTabIndexes() {
  $('#petition_title').attr('tabIndex', '1');
  $('iframe').attr('tabIndex', '2');
  if ($('#petition_to_send').length) {
    $('#petition_to_send').attr('tabIndex', '3');
    $('#petition_submit').attr('tabIndex', '4');
  }
  else {
    $('#petition_submit').attr('tabIndex', '3');
  }
}

function applyRichTextEditorTo(item) {
  $(item).wysihtml5();
}

function preventWhitespaceOn(input) {
  $(input).change(function() { this.value = this.value.replace(/ /g, ''); });
}

function EmailSuggestions() {
  var self = this;
  var $email = $('#signature_email');
  var $hint = $("#hint");

  this.init = function() {
    $('.suggested_email').live("click",function() {
      $email.val($(this).html());
      $hint.css('display', 'none');
      return false;
    });

  }

  this.mailCheckSuggestions = function(event) {
    $hint.css('display', 'none');
    $email.mailcheck({
      //annoyingly, mailcheck doesn't let you add to their default list of domains, so we have to duplicate them all here.
      domains: ["yahoo.com", "google.com", "hotmail.com", "gmail.com", "me.com", "aol.com", "mac.com",
                "live.com", "comcast.net", "googlemail.com", "msn.com", "hotmail.co.uk", "yahoo.co.uk",
                "facebook.com", "verizon.net", "sbcglobal.net", "att.net", "gmx.com", "mail.com", "q.com"],
      suggested: function(element, suggestion) {
        event.go = true;
        if(!$hint.html()) {
          var suggestion = 'Did you mean ' + suggestion.full + "?" +
              "
Click the '" + $("#sign_petition").val() + "' button again if your address is correct";
          $hint.html(suggestion).fadeIn(150);
          event.go = false;
        }
      }
    });
  }
}

function initTwitter() {
  !function(d,s,id) {
    var js,fjs=d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)) {
      js=d.createElement(s);
      js.id=id;js.src="//platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js,fjs);}
    }
    (document,"script","twitter-wjs");
}
<commit_msg>Disabling fb share button once clicked instead of hiding it<commit_after>$(document).ready(function() {
  initTwitter();
  initTabIndexes();
  setupShareFacebookButton();
  setupSocialTracking();

  if(screen.width > 480) {
    $('#thanksModal').modal('toggle');
  }

  preventWhitespaceOn('#signature_email');
  applyRichTextEditorTo('#petition_description');

  $('form').on("submit", function(event) {
    if(!VK.signing_from_email) {
      var emailSuggestor = new EmailSuggestions();
      emailSuggestor.init();
      emailSuggestor.mailCheckSuggestions(event);
    }
    return event.go;
  });

  if($('#email_subject').has('.additional_title').length) {
    $('#email_subject').show();
    $('#email_subject_link').hide();
  }

  $('#email_subject_link').click(function() {
    $('#email_subject').show();
    $('#email_subject input').focus();
    $('#email_subject_link').hide();
  });

  if($('#facebook_title').has('.additional_title').length) {
    $('#facebook_title').show();
    $('#facebook_title_link').hide();
  }

  $('#facebook_title_link').click(function() {
    $('#facebook_title').show();
    $('#facebook_title_link').hide();
  });
});

function setupSocialTracking() {
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
        //Google doesn't export social event data yet, so we have to track social actions as events too
        _gaq.push(['_trackEvent', 'facebook', 'like', targetUrl]);
        $.ajax({
          url: VK.social_tracking_url,
          data: setUpParamsForSocialTracking('like','')
        });
        $('.tweet').show();
      });
      FB.Event.subscribe('edge.remove', function(targetUrl){
        _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
        _gaq.push(['_trackEvent', 'facebook', 'unlike', targetUrl]);
      });
    }
  } catch(e) {}
}

function setUpParamsForSocialTracking(facebook_action, action_id) {
  var params = {petition_id: VK.petition_id, facebook_action: facebook_action};
  if (VK.signature_id != "") {
    params = $.extend(params, {signature_id: VK.signature_id});
  }
  if(action_id != ""){
    params = $.extend(params, {action_id: action_id});
  }

  return params;
}

function setupShareFacebookButton() {
  var shareButton = $('.fb_share.btn')
  shareButton.click(function(event) {
    if(shareButton.attr("disabled") == "disabled") {
      event.preventDefault();
      return false;
    }
    shareButton.attr("disabled", true);
    $('.tweet').show();
    $('#thanks-for-signing-message .share').text("Spread the word, share on Twitter!");
    submitFacebookAction();
  });
}

function submitFacebookAction() {
  FB.init({
    appId      : $('meta[property="fb:app_id"]').attr("content"),
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  FB.login(function(response) {
    if (response.authResponse) {
      console.log('Welcome!  Fetching your information.... ');
      FB.api(
        '/me/watchdognet:sign',
        'post',
        {
          petition: $('meta[property="og:url"]').attr("content")
        },
        function(response) {
          if (!response || response.error) {
            console.log('Error occured');
            console.log(response.error);
          } else {
            $.ajax({
            url: VK.social_tracking_url,
            data: setUpParamsForSocialTracking('share', response.id)
            });
            console.log('Sign was successful! Action ID: ' + response.id);
          }
        });
    } else {
      console.log('User cancelled login or did not fully authorize.');
    }}, {scope: 'publish_actions'});
}

function initTabIndexes() {
  $('#petition_title').attr('tabIndex', '1');
  $('iframe').attr('tabIndex', '2');
  if ($('#petition_to_send').length) {
    $('#petition_to_send').attr('tabIndex', '3');
    $('#petition_submit').attr('tabIndex', '4');
  }
  else {
    $('#petition_submit').attr('tabIndex', '3');
  }
}

function applyRichTextEditorTo(item) {
  $(item).wysihtml5();
}

function preventWhitespaceOn(input) {
  $(input).change(function() { this.value = this.value.replace(/ /g, ''); });
}

function EmailSuggestions() {
  var self = this;
  var $email = $('#signature_email');
  var $hint = $("#hint");

  this.init = function() {
    $('.suggested_email').live("click",function() {
      $email.val($(this).html());
      $hint.css('display', 'none');
      return false;
    });

  }

  this.mailCheckSuggestions = function(event) {
    $hint.css('display', 'none');
    $email.mailcheck({
      //annoyingly, mailcheck doesn't let you add to their default list of domains, so we have to duplicate them all here.
      domains: ["yahoo.com", "google.com", "hotmail.com", "gmail.com", "me.com", "aol.com", "mac.com",
                "live.com", "comcast.net", "googlemail.com", "msn.com", "hotmail.co.uk", "yahoo.co.uk",
                "facebook.com", "verizon.net", "sbcglobal.net", "att.net", "gmx.com", "mail.com", "q.com"],
      suggested: function(element, suggestion) {
        event.go = true;
        if(!$hint.html()) {
          var suggestion = 'Did you mean ' + suggestion.full + "?" +
              "
Click the '" + $("#sign_petition").val() + "' button again if your address is correct";
          $hint.html(suggestion).fadeIn(150);
          event.go = false;
        }
      }
    });
  }
}

function initTwitter() {
  !function(d,s,id) {
    var js,fjs=d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)) {
      js=d.createElement(s);
      js.id=id;js.src="//platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js,fjs);}
    }
    (document,"script","twitter-wjs");
}
<|endoftext|>