<commit_before>define(["sprd/data/SprdModel", "sprd/model/PaymentType", "sprd/entity/Payment", "underscore", "rAppid", "flow", "require"], function(SprdModel, PaymentType, Payment, _, rAppid, flow, require) {

    return SprdModel.inherit("sprd.model.Checkout", {

        defaults: {
            paymentType: null,
            payment: null,
            returnUrl: null,
            fingerPrint: null
        },

        $isDependentObject: true,

        schema: {
            paymentType: PaymentType,
            payment: Payment,
            returnUrl: String
        },

        save: function(cb) {

            var self = this,
                payment = this.$.payment;

            flow()
                .seq(function(cb) {
                    if (!payment) {
                        return cb();
                    }
                    payment._beforeCompose(cb);
                })
                .seq(function() {

                    var dataSource = self.$context.$dataSource;
                    var url = dataSource._buildUriForResource(self),
                    parameter = {};

                    _.defaults(parameter, self.$context.getQueryParameters(), dataSource.getQueryParameters("put", self));
                    delete parameter.mediaType;
                    url += "?" + rAppid.createQueryString(parameter);

                    var processor = dataSource.getProcessorForModel(self);
                    var formatProcessor = dataSource.getFormatProcessor("save", self);

                    var form = document.createElement("form");
                    form.setAttribute("method", "post");
                    form.setAttribute("action", url);

                    if (self.inIframe()) {
                        // do a navigation on the top frame, self
                        // could fail if a sandbox is defined without allow-top-navigation.

                        // to be more secure, we could just add self _top target, where we know
                        // that the loading checkout don't allow to run within an iframe
                        // (X-Frame-Options, see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options),
                        // which is the case for e.g. paypal
                        form.setAttribute("target", "_top");
                    }

                    var checkoutData = processor.compose(self, "save");

                    var fingerPrint = self.$.fingerPrint;
                    if (fingerPrint && checkoutData.payment) {
                        checkoutData.payment.fingerPrint = fingerPrint;
                    }

                    var valueField = document.createElement("input");
                    valueField.setAttribute("type", "hidden");
                    valueField.setAttribute("name", "value");
                    valueField.setAttribute("enctype", "multipart/form-data");
                    valueField.setAttribute("value", formatProcessor.serialize(checkoutData));

                    form.appendChild(valueField);
                    document.body.appendChild(form);
                    form.submit();

                })
                .exec(cb);

        },

        inIframe: function() {
            try {
                return window.self !== window.top;
            } catch (e) {
                return true;
            }
        },

        compose: function () {
            var ret = this.callBase();

            ret.payment = ret.payment || {};
            ret.paymentType = ret.paymentType || {};

            return ret;
        }

    });

});<commit_msg>removed unused require import<commit_after>define(["sprd/data/SprdModel", "sprd/model/PaymentType", "sprd/entity/Payment", "underscore", "rAppid", "flow"], function(SprdModel, PaymentType, Payment, _, rAppid, flow) {

    return SprdModel.inherit("sprd.model.Checkout", {

        defaults: {
            paymentType: null,
            payment: null,
            returnUrl: null,
            fingerPrint: null
        },

        $isDependentObject: true,

        schema: {
            paymentType: PaymentType,
            payment: Payment,
            returnUrl: String
        },

        save: function(cb) {

            var self = this,
                payment = this.$.payment;

            flow()
                .seq(function(cb) {
                    if (!payment) {
                        return cb();
                    }
                    payment._beforeCompose(cb);
                })
                .seq(function() {

                    var dataSource = self.$context.$dataSource;
                    var url = dataSource._buildUriForResource(self),
                    parameter = {};

                    _.defaults(parameter, self.$context.getQueryParameters(), dataSource.getQueryParameters("put", self));
                    delete parameter.mediaType;
                    url += "?" + rAppid.createQueryString(parameter);

                    var processor = dataSource.getProcessorForModel(self);
                    var formatProcessor = dataSource.getFormatProcessor("save", self);

                    var form = document.createElement("form");
                    form.setAttribute("method", "post");
                    form.setAttribute("action", url);

                    if (self.inIframe()) {
                        // do a navigation on the top frame, self
                        // could fail if a sandbox is defined without allow-top-navigation.

                        // to be more secure, we could just add self _top target, where we know
                        // that the loading checkout don't allow to run within an iframe
                        // (X-Frame-Options, see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options),
                        // which is the case for e.g. paypal
                        form.setAttribute("target", "_top");
                    }

                    var checkoutData = processor.compose(self, "save");

                    var fingerPrint = self.$.fingerPrint;
                    if (fingerPrint && checkoutData.payment) {
                        checkoutData.payment.fingerPrint = fingerPrint;
                    }

                    var valueField = document.createElement("input");
                    valueField.setAttribute("type", "hidden");
                    valueField.setAttribute("name", "value");
                    valueField.setAttribute("enctype", "multipart/form-data");
                    valueField.setAttribute("value", formatProcessor.serialize(checkoutData));

                    form.appendChild(valueField);
                    document.body.appendChild(form);
                    form.submit();

                })
                .exec(cb);

        },

        inIframe: function() {
            try {
                return window.self !== window.top;
            } catch (e) {
                return true;
            }
        },

        compose: function () {
            var ret = this.callBase();

            ret.payment = ret.payment || {};
            ret.paymentType = ret.paymentType || {};

            return ret;
        }

    });

});<|endoftext|>


<commit_before>var GeolocationService = require('service/GeolocationService');

function PoloWindow() {
	var self = Ti.UI.createWindow({
		title: 'Polo',
		backgroundColor: '#f6fa9c',
		barColor: '#8C001a'
	});

	self.add(Ti.UI.createLabel({
		top: 17,
		width: '80%',
		height: Ti.UI.SIZE,
		color: '#000',
		text: 'Enter your name'
	}));

	var txtPlayerName = Ti.UI.createTextField({
		top: 40,
		width: '80%',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		value: Ti.App.Properties.getString('PLAYER_NAME', '')
	});

	self.add(txtPlayerName);

	var btnCheckin = Ti.UI.createView({
		width: 200,
		height: 200,
		backgroundColor: '#8ca93e',
		borderColor: '#fff',
		borderWidth: 6,
		borderRadius: '100%'
	});

	btnCheckin.add(Ti.UI.createLabel({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		color: '#fff',
		text: 'Polo',
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
		font: {
			fontSize: '45sp',
			fontWeight: 'bold'
		}
	}));

	self.add(btnCheckin);

	var lblStatus = Ti.UI.createLabel({
		bottom: 0,
		width: Ti.UI.FILL,
		backgroundColor: '#6f0564',
		color: '#fff',
		opacity: 0.7,
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
	});

	self.add(lblStatus);

	btnCheckin.addEventListener('click', function(e) {
		if (txtPlayerName.value.length < 3) {
			alert('Please enter a valid name');
			return;
		}

		Ti.App.Properties.setString('PLAYER_NAME', txtPlayerName.value);

		lblStatus.text = 'Uploading location, please wait...';
		var geo = GeolocationService.findMe(lblStatus)
		lblStatus.text = geo.status;

		var placeId = Ti.App.Properties.getString('PLACE_ID', '');

		if (!placeId) {	 // No place for this user yet
			Cloud.Places.create({
				name: txtPlayerName.value,
				latitude: geo.latitude,
				longitude: geo.longitude
			}, function(e) {
				var place = e.places[0];

				Ti.App.Properties.setString('PLACE_ID', place.id);

				if (e.success) {
					lblStatus.text = 'Position saved to Cloud!';
				} else {
					Ti.API.error(msg);
				}
			});
		} else {  // A place already exists, so we update it
			Cloud.Places.update({
				place_id: placeId,
				name: txtPlayerName.text,
				latitude: geo.latitude,
				longitude: geo.longitude
			}, function(e) {
				if (e.success) {
					lblStatus.text = 'Cloud position updated successfully!';
				} else {
					Ti.API.error(msg);
				}
			});
		}
	});

	self.addEventListener('click', function() {
		txtPlayerName.blur();
	});

	return self;
}

module.exports = PoloWindow;<commit_msg>Moved all code in success block<commit_after>var GeolocationService = require('service/GeolocationService');

function PoloWindow() {
	var self = Ti.UI.createWindow({
		title: 'Polo',
		backgroundColor: '#f6fa9c',
		barColor: '#8C001a'
	});

	self.add(Ti.UI.createLabel({
		top: 17,
		width: '80%',
		height: Ti.UI.SIZE,
		color: '#000',
		text: 'Enter your name'
	}));

	var txtPlayerName = Ti.UI.createTextField({
		top: 40,
		width: '80%',
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		value: Ti.App.Properties.getString('PLAYER_NAME', '')
	});

	self.add(txtPlayerName);

	var btnCheckin = Ti.UI.createView({
		width: 200,
		height: 200,
		backgroundColor: '#8ca93e',
		borderColor: '#fff',
		borderWidth: 6,
		borderRadius: '100%'
	});

	btnCheckin.add(Ti.UI.createLabel({
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		color: '#fff',
		text: 'Polo',
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
		font: {
			fontSize: '45sp',
			fontWeight: 'bold'
		}
	}));

	self.add(btnCheckin);

	var lblStatus = Ti.UI.createLabel({
		bottom: 0,
		width: Ti.UI.FILL,
		backgroundColor: '#6f0564',
		color: '#fff',
		opacity: 0.7,
		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
	});

	self.add(lblStatus);

	btnCheckin.addEventListener('click', function(e) {
		if (txtPlayerName.value.length < 3) {
			alert('Please enter a valid name');
			return;
		}

		Ti.App.Properties.setString('PLAYER_NAME', txtPlayerName.value);

		lblStatus.text = 'Getting location, please wait...';
		var geo = GeolocationService.findMe()
		lblStatus.text = geo.status;

		var placeId = Ti.App.Properties.getString('PLACE_ID', '');

		if (!placeId) {	 // No place for this user yet
			Cloud.Places.create({
				name: txtPlayerName.value,
				latitude: geo.latitude,
				longitude: geo.longitude
			}, function(e) {

				if (e.success) {
					var place = e.places[0];

					Ti.App.Properties.setString('PLACE_ID', place.id);

					lblStatus.text = 'Position saved to Cloud!';
				} else {
					Ti.API.error(msg);
				}
			});
		} else {  // A place already exists, so we update it
			Cloud.Places.update({
				place_id: placeId,
				name: txtPlayerName.text,
				latitude: geo.latitude,
				longitude: geo.longitude
			}, function(e) {
				if (e.success) {
					lblStatus.text = 'Cloud position updated successfully!';
				} else {
					Ti.API.error(msg);
				}
			});
		}
	});

	self.addEventListener('click', function() {
		txtPlayerName.blur();
	});

	return self;
}

module.exports = PoloWindow;<|endoftext|>


<commit_before>var slideIndex = 0;
showSlides();

$.lang = {};
$.lang.en = {
	0: 'Welcome to Royal Caribbean\
International',
	1: 'YOUTUBE',
	2: 'TODAY\'S EVENTS',
	3: 'REQUEST',
	4: 'ENTERTAINMENT',
	5: 'EXCURSIONS'
};

$.lang.sp = {
	0: 'Bienvenido a Royal Caribbean\
International',
	1: 'YOUTUBE',
	2: 'EVENTO DE HOY',
	3: 'SOLICITUD',
	4: 'ENTRETENIMIENTO',
	5: 'EXCURSIONES'
}

$.lang.ch = {
	0: '欢迎来到皇家加勒比国际',
	1: 'YOUTUBE',
	2: '今天的事件',
	3: '请求',
	4: '娱乐',
	5: '游览'
}

function setLanguage(currentLanguage) {
	console.log('setLanguage : ' + currentLanguage);

	$('[data-langNum]').each(function () {
		var $this = $(this);
		$this.html($.lang[currentLanguage][$this.data('langnum')]);
	});
}

function clickLanguage(imgParam) {
	console.log(imgParam);
	var lang = imgParam.lang;
	console.log(lang);
	setLanguage(lang);
}

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    setTimeout(showSlides, 10000); // Change image every 2 seconds
}

function printClock() {
    var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	var day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    var clock = document.getElementById("time");            // 출력할 장소 선택
    var currentDate = new Date();                                     // 현재시간
    var calendar = currentDate.getFullYear() + "-" + (currentDate.getMonth()+1) + "-" + currentDate.getDate() // 현재 날짜
    var amPm = 'AM'; // 초기값 AM
    var currentHours = addZeros(currentDate.getHours(),2);
    var currentMinute = addZeros(currentDate.getMinutes() ,2);
    var currentSeconds =  addZeros(currentDate.getSeconds(),2);

    if (currentHours >= 12) { // 시간이 12보다 클 때 PM으로 세팅, 12를 빼줌
    	amPm = 'PM';
    	currentHours = addZeros(currentHours - 12,2);
    }

    if (currentSeconds >= 50) {// 50초 이상일 때 색을 변환해 준다.
       currentSeconds = ''+currentSeconds+''
    }
    clock.innerHTML = currentHours + ":"+currentMinute + "
" + day[currentDate.getDay()] + ", " + currentDate.getDate() + " " + month[currentDate.getMonth()]; //날짜를 출력해 줌

    setTimeout("printClock()",1000);         // 1초마다 printClock() 함수 호출
}

function addZeros(num, digit) { // 자릿수 맞춰주기
	  var zero = '';
	  num = num.toString();
	  if (num.length < digit) {
	    for (i = 0; i < digit - num.length; i++) {
	      zero += '0';
	    }
	  }
	  return zero + num;
}

navigator.bluetooth.requestLEScan({
  filters: [{manufacturerData: {0x004C: {dataPrefix: new Uint8Array([
    0x02, 0x15 // iBeacon identifier.
  ])}}}],
  keepRepeatedDevices: true
}).then(() => {
  navigator.bluetooth.addEventListener('advertisementreceived', event => {
    let appleData = event.manufacturerData.get(0x004C);
    if (appleData.byteLength != 23) {
      // Isn’t an iBeacon.
      return;
    }

    console.log(appleData);
    let major = appleData.getUint16(18, false);
    let minor = appleData.getUint16(20, false);
	  console.log(major, minor);
    let txPowerAt1m = -appleData.getInt8(22);
    let pathLossVs1m = txPowerAt1m - event.rssi;
  });
})

<commit_msg>Update main.js<commit_after>var slideIndex = 0;
showSlides();

$.lang = {};
$.lang.en = {
	0: 'Welcome to Royal Caribbean\
International',
	1: 'YOUTUBE',
	2: 'TODAY\'S EVENTS',
	3: 'REQUEST',
	4: 'ENTERTAINMENT',
	5: 'EXCURSIONS'
};

$.lang.sp = {
	0: 'Bienvenido a Royal Caribbean\
International',
	1: 'YOUTUBE',
	2: 'EVENTO DE HOY',
	3: 'SOLICITUD',
	4: 'ENTRETENIMIENTO',
	5: 'EXCURSIONES'
}

$.lang.ch = {
	0: '欢迎来到皇家加勒比国际',
	1: 'YOUTUBE',
	2: '今天的事件',
	3: '请求',
	4: '娱乐',
	5: '游览'
}

function setLanguage(currentLanguage) {
	console.log('setLanguage : ' + currentLanguage);

	$('[data-langNum]').each(function () {
		var $this = $(this);
		$this.html($.lang[currentLanguage][$this.data('langnum')]);
	});
}

function clickLanguage(imgParam) {
	console.log(imgParam);
	var lang = imgParam.lang;
	console.log(lang);
	setLanguage(lang);
}

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    setTimeout(showSlides, 10000); // Change image every 2 seconds
}

function printClock() {
    var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	var day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
    var clock = document.getElementById("time");            // 출력할 장소 선택
    var currentDate = new Date();                                     // 현재시간
    var calendar = currentDate.getFullYear() + "-" + (currentDate.getMonth()+1) + "-" + currentDate.getDate() // 현재 날짜
    var amPm = 'AM'; // 초기값 AM
    var currentHours = addZeros(currentDate.getHours(),2);
    var currentMinute = addZeros(currentDate.getMinutes() ,2);
    var currentSeconds =  addZeros(currentDate.getSeconds(),2);

    if (currentHours >= 12) { // 시간이 12보다 클 때 PM으로 세팅, 12를 빼줌
    	amPm = 'PM';
    	currentHours = addZeros(currentHours - 12,2);
    }

    if (currentSeconds >= 50) {// 50초 이상일 때 색을 변환해 준다.
       currentSeconds = ''+currentSeconds+''
    }
    clock.innerHTML = currentHours + ":"+currentMinute + "
" + day[currentDate.getDay()] + ", " + currentDate.getDate() + " " + month[currentDate.getMonth()]; //날짜를 출력해 줌

    setTimeout("printClock()",1000);         // 1초마다 printClock() 함수 호출
}

function addZeros(num, digit) { // 자릿수 맞춰주기
	  var zero = '';
	  num = num.toString();
	  if (num.length < digit) {
	    for (i = 0; i < digit - num.length; i++) {
	      zero += '0';
	    }
	  }
	  return zero + num;
}

async function StartScan() {
	var scan = await navigator.bluetooth.requestLEScan({
	  filters: [{manufacturerData: {0x004C: {dataPrefix: new Uint8Array([
	    0x02, 0x15 // iBeacon identifier.
	  ])}}}],
	  keepRepeatedDevices: true
	})
	  navigator.bluetooth.addEventListener('advertisementreceived', event => {
	    let appleData = event.manufacturerData.get(0x004C);
	    if (appleData.byteLength != 23) {
	      // Isn’t an iBeacon.
	      return;
	    }

	    console.log(appleData);
	    let major = appleData.getUint16(18, false);
	    let minor = appleData.getUint16(20, false);
		  console.log(major, minor);
	    let txPowerAt1m = -appleData.getInt8(22);
	    let pathLossVs1m = txPowerAt1m - event.rssi;
	  });
	});

}
<|endoftext|>


<commit_before>/**
 * Created by tushar.mathur on 01/10/16.
 */

'use strict'

const {Suite} = require('benchmark')
const {map} = require('../src/operators/Map')
const {filter} = require('../src/operators/Filter')
const {fromArray} = require('../src/sources/FromArray')
const {reduce} = require('../src/operators/Reduce')
const {takeN} = require('../src/operators/Slice')

function noop () {
}
function add1 (x) {
  return x + 1
}
function even (e) {
  return e % 2 === 0
}
function sum (a, b) {
  return a + b
}
const n = 1e6
const a = new Array(n)
for (var i = 0; i < a.length; ++i) {
  a[i] = i
}
const suite = new Suite('filter -> map -> reduce ' + n + ' integers')
function run (observable, deferred) {
  observable.subscribe({
    next: noop,
    error: noop,
    complete: () => deferred.resolve()
  })
}
const options = {defer: true}
suite.add('file -> map -> reduce',
  d =>
    run(reduce(sum, 0, map(add1, filter(even, fromArray(a)))), d),
  options
).add('file -> takeN(0, n/10)',
  d =>
    run(takeN(0, n / 10, fromArray(a)), d),
  options
).on('cycle', event => console.log(String(event.target))).run()
<commit_msg>whitespace changes<commit_after>/**
 * Created by tushar.mathur on 01/10/16.
 */

'use strict'

const {Suite} = require('benchmark')
const {map} = require('../src/operators/Map')
const {filter} = require('../src/operators/Filter')
const {fromArray} = require('../src/sources/FromArray')
const {reduce} = require('../src/operators/Reduce')
const {takeN} = require('../src/operators/Slice')

function noop () {
}
function add1 (x) {
  return x + 1
}
function even (e) {
  return e % 2 === 0
}
function sum (a, b) {
  return a + b
}
const n = 1e6
const a = new Array(n)
for (var i = 0; i < a.length; ++i) {
  a[i] = i
}
const suite = new Suite('filter -> map -> reduce ' + n + ' integers')
function run (observable, deferred) {
  observable.subscribe({
    next: noop,
    error: noop,
    complete: () => deferred.resolve()
  })
}
const options = {defer: true}
suite
  .add('file -> map -> reduce',
    d =>
      run(reduce(sum, 0, map(add1, filter(even, fromArray(a)))), d),
    options
  )
  .add('file -> takeN(0, n/10)',
    d =>
      run(takeN(0, n / 10, fromArray(a)), d),
    options
  )
  .on('cycle', event => console.log(String(event.target))).run()
<|endoftext|>


<commit_before>
var serialized_user_data;

function sound_play(x){
	var sound = document.createElement("AUDIO");
	sound.setAttribute("src","sounds/"+x+".mp3");
	sound.autoplay = true;
	document.body.appendChild(sound);
}

function display(x){
	if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else { // code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onload = document.getElementById("game").innerHTML += "
Loading...
";
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById("game").innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.open("POST", "engine.php?command="+x, true);
	xmlhttp.send();
}

function post_data(url, data, where_to_show){
	var post = $.post(url, data);
  	post.done(function(received_data) {
    	$("#"+where_to_show).html(received_data);
 	});
}

function login(){
	serialized_user_data = $("#login_form").serialize();
 	post_data('game/login.php', serialized_user_data, 'game');
}

function register(){
	serialized_user_data = $("#register_form").serialize();
 	post_data('game/register.php', serialized_user_data, 'game');
}

function logout(){
	post_data('game/logout.php', null, 'game');
}

function show_attack_gui(monster_id,type){
	post_data('game/attack_gui.php', 'monster_id='+monster_id+'&type='+type, 'game');
}

function shop_show_items(which){
	post_data('game/shop.php', 'which_items_to_show='+which, 'game');
}

function item_action(item_id,action){
	post_data('game/item_functions.php', 'item_index='+item_id+'&action='+action, 'game');
}

function open_chest(item_id){
	post_data('game/open_chest.php', 'item_index='+item_id, 'game');
}

function communicat(type, text){
	var data = "type="+type+"&text="+text;
	post_data('game/communicat.php', data, 'game');
}

function show_page(page_number){
	post_data('game/changepage.php', 'page='+page_number, 'game');
}

window.setInterval(function(){
  var seconds_left = parseInt($("#energy_seconds_left").text());
  if(seconds_left<1){
	  $("#energy_seconds_left").html(0);
  }else{
	seconds_left--;
	$("#energy_seconds_left").html(seconds_left);
  }
}, 1000);

function attack_animation(){
	$("#attack").animate({"opacity":"0"}, 500).animate({"opacity":"1"}, 500);
	var user_hp = parseInt($("#actual_user_hp").html());
	if(user_hp === NaN){
		user_hp = 1;
	}
	var max_user_hp = parseInt($("#user_hp").html());

	var user_hp = (user_hp/max_user_hp)*100;

	var opponent_hp = parseInt($("#actual_opponent_hp").html());
	var max_opponent_hp = parseInt($("#opponent_hp").html());

	if(opponent_hp === NaN){
		opponent_hp = 1;
	}
	var opponent_hp = (opponent_hp/max_opponent_hp)*100;
	$("#progress").animate({"width":user_hp+"%"}, 500);
	$("#progress_opponent").animate({"width":opponent_hp+"%"}, 500);
}

<commit_msg>Fixes<commit_after>
var serialized_user_data;

function sound_play(x){
	var sound = document.createElement("AUDIO");
	sound.setAttribute("src","sounds/"+x+".mp3");
	sound.autoplay = true;
	document.body.appendChild(sound);
}

function display(x){
	if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else { // code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onload = document.getElementById("game").innerHTML += "
Loading...
";
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById("game").innerHTML = xmlhttp.responseText;
		}
	}
	xmlhttp.open("POST", "engine.php?command="+x, true);
	xmlhttp.send();
}

function post_data(url, data, where_to_show){
	var post = $.post(url, data);
  	post.done(function(received_data) {
    	$("#"+where_to_show).html(received_data);
 	});
}

function login(){
	serialized_user_data = $("#login_form").serialize();
 	post_data('game/login.php', serialized_user_data, 'game');
}

function register(){
	serialized_user_data = $("#register_form").serialize();
 	post_data('game/register.php', serialized_user_data, 'game');
}

function logout(){
	post_data('game/logout.php', null, 'game');
}

function show_attack_gui(monster_id,type){
	post_data('game/attack_gui.php', 'monster_id='+monster_id+'&type='+type, 'game');
}

function shop_show_items(which){
	post_data('game/shop.php', 'which_items_to_show='+which, 'game');
}

function item_action(item_id,action){
	post_data('game/item_functions.php', 'item_index='+item_id+'&action='+action, 'game');
}

function open_chest(item_id){
	post_data('game/open_chest.php', 'item_index='+item_id, 'game');
}

function communicat(type, text){
	var data = "type="+type+"&text="+text;
	post_data('game/communicat.php', data, 'game');
}

function show_page(page_number){
	post_data('game/changepage.php', 'page='+page_number, 'game');
}

window.setInterval(function(){
  var seconds_left = parseInt($("#energy_seconds_left").text());
  if(seconds_left<1){
	  $("#energy_seconds_left").html(0);
  }else{
	seconds_left--;
	$("#energy_seconds_left").html(seconds_left);
  }
}, 1000);

function attack_animation(){
	$("#attack").animate({"opacity":"0"}, 100).animate({"opacity":"1"}, 100);
	var user_hp = parseInt($("#actual_user_hp").html());
	if(user_hp === NaN){
		user_hp = 1;
	}
	var max_user_hp = parseInt($("#user_hp").html());

	var user_hp = (user_hp/max_user_hp)*100;

	var opponent_hp = parseInt($("#actual_opponent_hp").html());
	var max_opponent_hp = parseInt($("#opponent_hp").html());

	if(opponent_hp === NaN){
		opponent_hp = 1;
	}
	var opponent_hp = (opponent_hp/max_opponent_hp)*100;
	$("#progress").animate({"width":user_hp+"%"}, 200);
	$("#progress_opponent").animate({"width":opponent_hp+"%"}, 200);
}

<|endoftext|>


<commit_before>/* Copyright (c) 2011 Richard Rodger */

var util   = require('util')
var http   = require('http')
var events = require('events')

var MARK = 'logentries: '

function LogEntriesTransport( opts, logger ) {
  var self = this

  var queue = null
  var connected = false
  var req = null

  function process() {

    while( 0 < queue.length ) {
      var entry = queue[0]

      var logline = opts.token + '"' + entry.join('" "') + '"\n';

      try {
        queue.shift()
        logger.emit('log',logline)
        req.write(logline)
      }
      catch(e) {
        logger.emit('error',e)
        queue.unshift(entry)
        connected = false
        break
      }
    }
  }

  function connect() {
    if( req ) {
      try {
        req.end()
      }
      catch( e ) {
        logger.emit('error',e)
      }
    }

    var options = {
      host: 'api.logentries.com',
      port: 10000,
      token: opts.token
    }

    logger.emit('connect',options)

    req = http.request(options, function(res) {
      if( 200 != res.statusCode ) {
        res.setEncoding('utf8');

        var err = {
          statusCode: res.statusCode,
          headers: res.headers
        }

        var body = []
        res.on('data',function(chunk){
          body.push(chunk)
        })

        res.on('end',function(){
          try {
            err.body = JSON.parse(body.join(''))
          }
          catch(e) {
            err.body = {msg:body.join('')}
          }
          logger.emit('error',err)
        })
      }
    });

    req.on('error', function(e) {
      logger.emit('error',e)
      connected = false
    });

    if( null != req ) {
      connected = true
      process()
    }
  }

  self.queue = function( q ) {
    queue = q
  }

  self.consume = function() {
    if( connected ) {
      process()
    }
    else {
      connect()
    }
  }

  self.end = function() {
    if( connected && req ) {
      try {
        req.end()
      }
      catch( e ) {
        logger.emit('error',e)
      }
      logger.emit('end')
    }
  }
}

/*
 *  opts:
 *    token:    required; Logentries Destination Token UUID
 *
 *    transport:  LogEntriesTransport; transport object
 *    levels:     syslog-style; custom log levels
 *    printerror: true; print errors to STDERR with console.error
 */
function Logger( opts ) {
  var self = this
  events.EventEmitter.call(self);

  opts = opts || {}

  opts.printerror = 'undefined' == typeof(opts.printerror) ? true : opts.printerror

  // register at least one listener for 'error' as logging failure should not bring down server
  self.on('error',function(err) {
    if( opts.printerror ) {
      console.error(err)
    }
  })

  self.levels = opts.levels || {
    debug     :0,
    info      :1,
    notice    :2,
    warning   :3,
    err       :4,
    crit      :5,
    alert     :6,
    emerg     :7,
  }

  var transport = opts.transport || new LogEntriesTransport(opts,self)
  var loglevel = -1
  var levelname
  var queue = []

  transport.queue(queue)

  for( level in self.levels ) {
    if( !({log:1,end:1,level:1,levels:1,on:1,once:1}[level]) ) {
      self[level] = function(level) {
        return function() {
          var args = Array.prototype.slice.call(arguments)
          args.unshift(level)
          self.log.apply(self,args)
        }
      }(level)
    }
  }

  self.log = function() {
    var args = Array.prototype.slice.call(arguments)
    var arglevel = args[0]
    var levelval = self.levels[arglevel]
    var timestamp =
      opts.timestamp === undefined || opts.timestamp === true ? true : false;

    if( undefined == levelval ) {
      self.emit('error','unknown log level: '+arglevel)
    }

    if( loglevel <= levelval  ) {

      var data = args[1]
      if( data && data.toISOString && data.getTimezoneOffset ) {
        args[1] = data.toISOString();
      }

      else if( 'object' == typeof( data ) || Array.isArray(data) ) {
        args[1] = JSON.stringify(data);
      }
      else {
        args[1] = ''+data;
      }

      if (timestamp) {
        t = new Date().toISOString();
        args.unshift(t);
      }

      //console.log('args: ', args);
      queue.push(args)
      transport.consume()
    }
  }

  self.end = function() {
    transport.end && transport.end()
  }

  self.level = function(level) {

    if( undefined != level ) {
      if( undefined != self.levels[level] ) {
        loglevel = self.levels[level]
        levelname = level

        if( self.winstonLogger ) {
          self.winstonLogger.level = levelname
        }
      }
      else {
        throw new Error('unknown log level: '+level)
      }
    }

    return levelname
  }

  self.winston = function(winston,opts) {
    for( var l in self.levels ) {
      delete self[l]
    }

    self.levels = winston.levels

    if( !winston.transports.LogentriesLogger )  {
      var LogentriesLogger = winston.transports.LogentriesLogger = function (options) {
        this.name = 'logentries';

        this.level = options.level || 'info'

        if( options.level ) {
          self.level(options.level)
        }

        self.winstonLogger = this
      }

      util.inherits(LogentriesLogger, winston.Transport)

      LogentriesLogger.prototype.log = function (level, msg, meta, callback) {
        var data = msg + (meta?' '+JSON.stringify(meta):'')
        self.log(level,data)
        callback(null, true);
      }
    }

    winston.add(LogentriesLogger,opts)
  }

}
util.inherits(Logger, events.EventEmitter);

exports.logger = function(opts) {
  return new Logger(opts)
}

<commit_msg>Modified logentries to use more minimal logging format<commit_after>/* Copyright (c) 2011 Richard Rodger */

var util   = require('util')
var http   = require('http')
var events = require('events')

var MARK = 'logentries: '

function LogEntriesTransport( opts, logger ) {
  var self = this

  var queue = null
  var connected = false
  var req = null

  function process() {

    while( 0 < queue.length ) {
      var entry = queue[0]

      var logline = opts.token;
      // logline += '"' + entry.join('" "') + '"\n';
      logline += entry[2] + '\n';

      try {
        queue.shift()
        logger.emit('log',logline)
        req.write(logline)
      }
      catch(e) {
        logger.emit('error',e)
        queue.unshift(entry)
        connected = false
        break
      }
    }
  }

  function connect() {
    if( req ) {
      try {
        req.end()
      }
      catch( e ) {
        logger.emit('error',e)
      }
    }

    var options = {
      host: 'api.logentries.com',
      port: 10000,
      token: opts.token
    }

    logger.emit('connect',options)

    req = http.request(options, function(res) {

      if( 200 != res.statusCode ) {
        res.setEncoding('utf8');

        var err = {
          statusCode: res.statusCode,
          headers: res.headers
        }

        var body = []
        res.on('data',function(chunk){
          body.push(chunk)
        })

        res.on('end',function(){
          try {
            err.body = JSON.parse(body.join(''))
          }
          catch(e) {
            err.body = {msg:body.join('')}
          }
          logger.emit('error',err)
        })
      }
    });

    req.on('error', function(e) {
      logger.emit('error',e)
      connected = false
    });

    if( null != req ) {
      connected = true
      process()
    }
  }

  self.queue = function( q ) {
    queue = q
  }

  self.consume = function() {
    if( connected ) {
      process()
    }
    else {
      connect()
    }
  }

  self.end = function() {
    if( connected && req ) {
      try {
        req.end()
      }
      catch( e ) {
        logger.emit('error',e)
      }
      logger.emit('end')
    }
  }
}

/*
 *  opts:
 *    token:    required; Logentries Destination Token UUID
 *
 *    transport:  LogEntriesTransport; transport object
 *    levels:     syslog-style; custom log levels
 *    printerror: true; print errors to STDERR with console.error
 */
function Logger( opts ) {
  var self = this
  events.EventEmitter.call(self);

  opts = opts || {}

  opts.printerror = 'undefined' == typeof(opts.printerror) ? true : opts.printerror

  // register at least one listener for 'error' as logging failure should not bring down server
  self.on('error',function(err) {
    if( opts.printerror ) {
      console.error(err)
    }
  })

  self.levels = opts.levels || {
    debug     :0,
    info      :1,
    notice    :2,
    warning   :3,
    err       :4,
    crit      :5,
    alert     :6,
    emerg     :7,
  }

  var transport = opts.transport || new LogEntriesTransport(opts,self)
  var loglevel = -1
  var levelname
  var queue = []

  transport.queue(queue)

  for( level in self.levels ) {
    if( !({log:1,end:1,level:1,levels:1,on:1,once:1}[level]) ) {
      self[level] = function(level) {
        return function() {
          var args = Array.prototype.slice.call(arguments)
          args.unshift(level)
          self.log.apply(self,args)
        }
      }(level)
    }
  }

  self.log = function() {
    var args = Array.prototype.slice.call(arguments)
    var arglevel = args[0]
    var levelval = self.levels[arglevel]
    var timestamp =
      opts.timestamp === undefined || opts.timestamp === true ? true : false;

    if( undefined == levelval ) {
      self.emit('error','unknown log level: '+arglevel)
    }

    if( loglevel <= levelval  ) {

      var data = args[1]
      if( data && data.toISOString && data.getTimezoneOffset ) {
        args[1] = data.toISOString();
      }

      else if( 'object' == typeof( data ) || Array.isArray(data) ) {
        args[1] = JSON.stringify(data);
      }
      else {
        args[1] = ''+data;
      }

      if (timestamp) {
        t = new Date().toISOString();
        args.unshift(t);
      }

      //console.log('args: ', args);
      queue.push(args)
      transport.consume()
    }
  }

  self.end = function() {
    transport.end && transport.end()
  }

  self.level = function(level) {

    if( undefined != level ) {
      if( undefined != self.levels[level] ) {
        loglevel = self.levels[level]
        levelname = level

        if( self.winstonLogger ) {
          self.winstonLogger.level = levelname
        }
      }
      else {
        throw new Error('unknown log level: '+level)
      }
    }

    return levelname
  }

  self.winston = function(winston,opts) {
    for( var l in self.levels ) {
      delete self[l]
    }

    self.levels = winston.levels

    if( !winston.transports.LogentriesLogger )  {
      var LogentriesLogger = winston.transports.LogentriesLogger = function (options) {
        this.name = 'logentries';

        this.level = options.level || 'info'

        if( options.level ) {
          self.level(options.level)
        }

        self.winstonLogger = this
      }

      util.inherits(LogentriesLogger, winston.Transport)

      LogentriesLogger.prototype.log = function (level, msg, meta, callback) {
        var data = msg + (meta?' '+JSON.stringify(meta):'')
        self.log(level,data)
        callback(null, true);
      }
    }

    winston.add(LogentriesLogger,opts)
  }

}
util.inherits(Logger, events.EventEmitter);

exports.logger = function(opts) {
  return new Logger(opts)
}

<|endoftext|>


<commit_before>/*  ============================================================================

 Copyright (C) 2006-2016 Talend Inc. - www.talend.com

 This source code is available under agreement available at
 https://github.com/Talend/data-prep/blob/master/LICENSE

 You should have received a copy of the agreement
 along with this program; if not, write to Talend SA
 9 rue Pages 92150 Suresnes, France

 ============================================================================*/

class SearchDocumentationService {

	constructor(SearchDocumentationRestService, TextFormatService) {
		'ngInject';

		this.searchDocumentationRestService = SearchDocumentationRestService;
		this.textFormatService = TextFormatService;
	}

	/**
	 * @ngdoc method
	 * @name search
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description search documentation with keyword
	 */
	search(keyword) {
		return this.searchDocumentationRestService.search(keyword)
			.then((response) => {
				return response.data.results.map(this._createDocElement);
			})
			.catch(() => []);
	}

	/**
	 * @ngdoc method
	 * @name searchAndHighlight
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description search documentation with keyword and highlight terms
	 */
	searchAndHighlight(keyword) {
		return this.search(keyword)
			.then((results) => {
				return results.map((item) => {
					this.textFormatService.highlight(item, 'name', keyword, 'highlighted');
					this.textFormatService.highlight(item, 'description', keyword, 'highlighted');
					return item;
				});
			});
	}

	/**
	 * @ngdoc method
	 * @name _createDocElement
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description Creates a document element following the Typeahead props
	 * @param {Array} topic the matched result
	 * @returns {object} The documentation elements
	 */
	_createDocElement(topic) {
		const doc = {
			inventoryType: 'documentation',
			description: topic.htmlExcerpt.replace(/(<[^>]*>)/g, '').replace('<', '<').replace('>', '>'),
			name: topic.htmlTitle.replace(/(<[^>]*>)/g, '').replace('<', '<').replace('>', '>'),
			url: topic.occurrences[0].readerUrl,
		};
		doc.tooltipName = doc.name;
		return doc;
	}
}

export default SearchDocumentationService;
<commit_msg>fix(TDP-4002): convert special html characters in doc search to readable (#669)<commit_after>/*  ============================================================================

 Copyright (C) 2006-2016 Talend Inc. - www.talend.com

 This source code is available under agreement available at
 https://github.com/Talend/data-prep/blob/master/LICENSE

 You should have received a copy of the agreement
 along with this program; if not, write to Talend SA
 9 rue Pages 92150 Suresnes, France

 ============================================================================*/

class SearchDocumentationService {

	constructor(SearchDocumentationRestService, TextFormatService) {
		'ngInject';

		this.searchDocumentationRestService = SearchDocumentationRestService;
		this.textFormatService = TextFormatService;
		this.domEl = document.createElement('p');
	}

	/**
	 * @ngdoc method
	 * @name search
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description search documentation with keyword
	 */
	search(keyword) {
		return this.searchDocumentationRestService.search(keyword)
			.then((response) => {
				return response.data.results.map(this._createDocElement.bind(this));
			})
			.catch(() => []);
	}

	/**
	 * @ngdoc method
	 * @name searchAndHighlight
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description search documentation with keyword and highlight terms
	 */
	searchAndHighlight(keyword) {
		return this.search(keyword)
			.then((results) => {
				return results.map((item) => {
					this.textFormatService.highlight(item, 'name', keyword, 'highlighted');
					this.textFormatService.highlight(item, 'description', keyword, 'highlighted');
					return item;
				});
			});
	}

	/**
	 * @ngdoc method
	 * @name _createDocElement
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description Creates a document element following the Typeahead props
	 * @param {Array} topic the matched result
	 * @returns {object} The documentation elements
	 */
	_createDocElement(topic) {
		const doc = {
			inventoryType: 'documentation',
			description: this._convertHtmlSpecialCharacters(topic.htmlExcerpt.replace(/(<[^>]*>)/g, '')),
			name: this._convertHtmlSpecialCharacters(topic.htmlTitle.replace(/(<[^>]*>)/g, '')),
			url: topic.occurrences[0].readerUrl,
		};
		doc.tooltipName = doc.name;
		return doc;
	}

	/**
	 * @ngdoc method
	 * @name _convertHtmlSpecialCharacters
	 * @methodOf data-prep.services.search.documentation:SearchDocumentationService
	 * @description converts special html characters into readable characters
	 * @param {String} The raw string
	 * @returns {String} readable string
	 */
	_convertHtmlSpecialCharacters(unreadableStr) {
		this.domEl.innerHTML = unreadableStr;
		return this.domEl.innerText;
	}
}

export default SearchDocumentationService;
<|endoftext|>


<commit_before>// Fluidbox
// Description: Replicating the seamless lightbox transition effect seen on Medium.com, with some improvements
// Version: 1.3.5
// Author: Terry Mun
// Author URI: http://terrymun.com

// --------------------------------------------------------
//  Dependency: Paul Irish's jQuery debounced resize event
// --------------------------------------------------------
(function($,sr){

	// debouncing function from John Hann
	// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
	var debounce = function (func, threshold, execAsap) {
		var timeout;

		return function debounced () {
			var obj = this, args = arguments;
			function delayed () {
				if (!execAsap)
				func.apply(obj, args);
				timeout = null;
			};

			if (timeout)
				clearTimeout(timeout);
			else if (execAsap)
				func.apply(obj, args);

			timeout = setTimeout(delayed, threshold || 100);
		};
	}
	// smartresize
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');

// -----------------------------
//  Fluidbox plugin starts here
// -----------------------------
(function ($) {

	$.fn.fluidbox = function (opts) {

		// Default settings
		var settings = $.extend(true, {
			viewportFill: 0.95,
			debounceResize: true,
			stackIndex: 1000,
			stackIndexDelta: 10,
			closeTrigger: [
				{
					selector: '.fluidbox-overlay',
					event: 'click'
				},
				{
					selector: 'document',
					event: 'keyup',
					keyCode: 27
				}
			]
		}, opts);

		// Ensure that the stackIndex does not become negative
		if(settings.stackIndex < settings.stackIndexDelta) settings.stackIndexDelta = settings.stackIndex;

		// Dynamically create overlay
		$fbOverlay = $('
', {
			'class': 'fluidbox-overlay',
			css: {
				'z-index': settings.stackIndex
			}
		});

		// Declare variables
		var $fb = this,
			$w = $(window),		// Shorthand for $(window)
			vpRatio,

			// Function:
			// 1. funcCloseFb()		- used to close any instance of opened Fluidbox
			// 2. funcPositionFb()	- used for dynamic positioning of any instance of opened Fluidbox
			// 3. funcCalcAll()		- used to run funcCalc() for every instance of targered Fluidbox thumbnail
			// 4. funcCalc()		- used to store dimensions of image, ghost element and wrapper element upon initialization or resize
			// 5. fbClickhandler()	- universal click handler for all Fluidbox items
			funcCloseFb = function () {
				$('.fluidbox-opened').trigger('click');
			},
			funcPositionFb = function ($activeFb) {
				// Get shorthand for more objects
				var $img    = $activeFb.find('img'),
					$ghost  = $activeFb.find('.fluidbox-ghost'),
					$wrap	= $activeFb.find('.fluidbox-wrap'),
					$data	= $activeFb.data(),
					fHeight = 0,
					fWidth	= 0;
                                $img.data().imgRatio = $data.natWidth/ $data.natHeight;

                                var newHeight, missingRatioNormal, missingRatio;

				// Check natural dimensions
				if(vpRatio > $img.data().imgRatio) {
					if($data.natHeight < $w.height()*settings.viewportFill) {
						fHeight = $data.natHeight;
					} else {
						fHeight = $w.height()*settings.viewportFill;
					}
					$data.imgScale = fHeight/$img.height();
                                        $data.imgScaleY = $data.imgScale;

                                        newHeight = $img.height() * $data.imgScaleY;
                                        missingRatioNormal = newHeight / $data.natHeight;
                                        missingRatio = $data.natWidth * missingRatioNormal / $img.width();

                                        $data.imgScaleX = missingRatio;
				} else {
					if($data.natWidth < $w.width()*settings.viewportFill) {
						fWidth = $data.natWidth;
					} else {
						fWidth = $w.width()*settings.viewportFill;
					}
					$data.imgScale = fWidth/$img.width();
                                        $data.imgScaleX = $data.imgScale;

                                        var newWidth = $img.width() * $data.imgScaleX;
                                        var missingRatioNormal = newWidth / $data.natWidth;
                                        var missingRatio = $data.natHeight * missingRatioNormal / $img.height();

                                        $data.imgScaleY = missingRatio;
				}

				// Calculation goes here
				var offsetY = $w.scrollTop()-$img.offset().top+0.5*($img.data('imgHeight')*($img.data('imgScale')-1))+0.5*($w.height()-$img.data('imgHeight')*$img.data('imgScale')),
					offsetX = 0.5*($img.data('imgWidth')*($img.data('imgScale')-1))+0.5*($w.width()-$img.data('imgWidth')*$img.data('imgScale'))-$img.offset().left,
                                        scale = parseInt($data.imgScaleX * 1000) / 1000 + ',' + parseInt($data.imgScaleY * 1000) / 1000;

				// Apply CSS transforms to ghost element
				// For offsetX and Y, we round to one decimal place
				// For scale, we round to three decimal places
				$ghost.css({
					'transform': 'translate('+parseInt(offsetX*10)/10+'px,'+parseInt(offsetY*10)/10+'px) scale('+ scale +')',
					top: $img.offset().top - $wrap.offset().top,
					left: $img.offset().left - $wrap.offset().left
				});
			},
			funcCalcAll = function() {
				$fb.each(function () {
					funcCalc($(this));
				});
			},
			funcCalc = function ($fbItem) {
				// Get viewport ratio
				vpRatio = $w.width() / $w.height();

				// Get image dimensions and aspect ratio
				if($fbItem.hasClass('fluidbox')) {
					var $img	= $fbItem.find('img'),
						$ghost	= $fbItem.find('.fluidbox-ghost'),
						$wrap	= $fbItem.find('.fluidbox-wrap'),
						data	= $img.data();

					function imageProp() {
						// Store image dimensions in jQuery object
						data.imgWidth	= $img.width();
						data.imgHeight	= $img.height();
						data.imgRatio	= $img.width()/$img.height();

						// Resize and position ghost element
						$ghost.css({
							width: $img.width(),
							height: $img.height(),
							top: $img.offset().top - $wrap.offset().top + parseInt($img.css('borderTopWidth')) + parseInt($img.css('paddingTop')),
							left: $img.offset().left - $wrap.offset().left + parseInt($img.css('borderLeftWidth')) + parseInt($img.css('paddingLeft'))
						});

						// Calculate scale based on orientation
						if(vpRatio > data.imgRatio) {
							data.imgScale = $w.height()*settings.viewportFill/$img.height();
						} else {
							data.imgScale = $w.width()*settings.viewportFill/$img.width();
						}
					}

					imageProp();

					// Rerun everything on imageload, to overcome issue in Firefox
					$img.load(imageProp);
				}
			},
			fbClickHandler = function(e) {

				// Check if the fluidbox element does have .fluidbox assigned to it
				if($(this).hasClass('fluidbox')) {

					// Variables
					var $activeFb	= $(this),
						$img		= $(this).find('img'),
						$ghost		= $(this).find('.fluidbox-ghost'),
						$wrap   	= $(this).find('.fluidbox-wrap'),
						timer   	= {};

					if($(this).data('fluidbox-state') === 0 || !$(this).data('fluidbox-state')) {
						// State: Closed
						// Action: Open fluidbox

						// Wait for ghost image to be loaded successfully first, then do the rest
						$('', {
							src: $img.attr('src')
						}).load(function () {
							// Preload ghost image
							$('', {
								src: $activeFb.attr('href')
							}).load(function() {
								// Store natural width and heights
								$activeFb
								.data('natWidth', $(this)[0].naturalWidth)
								.data('natHeight', $(this)[0].naturalHeight);

								// What are we doing here:
								// 1. Append overlay in fluidbox
								// 2. Toggle fluidbox state with data attribute
								// 3. Store original z-index with data attribute (so users can change z-index when they see fit in CSS file)
								// 4. Class toggle
								$activeFb
								.append($fbOverlay)
								.data('fluidbox-state', 1)
								.removeClass('fluidbox-closed')
								.addClass('fluidbox-opened');

								// Force timer to completion
								if(timer['close']) window.clearTimeout(timer['close']);

								// Set timer for opening
								timer['open'] = window.setTimeout(function() {
									// Show overlay
									$('.fluidbox-overlay').css({ opacity: 1 });
								}, 10);

								// Change wrapper z-index, so it is above everything else
								// Decrease all siblings z-index by 1 just in case
								$('.fluidbox-wrap').css({ zIndex: settings.stackIndex - settings.stackIndexDelta - 1 });
								$wrap.css({ 'z-index': settings.stackIndex + settings.stackIndexDelta });

								// Set thumbnail image source as background image first, preload later
								$ghost.css({
									'background-image': 'url('+$img.attr('src')+')',
									opacity: 1
								});

								// Hide original image
								$img.css({ opacity: 0 });

								$ghost.css({ 'background-image': 'url('+$activeFb.attr('href')+')' });

								// Position Fluidbox
								funcPositionFb($activeFb);
							});
						});

					} else {
						// State: Open
						// Action: Close fluidbox

						// Switch state
						$activeFb
						.data('fluidbox-state', 0)
						.removeClass('fluidbox-opened')
						.addClass('fluidbox-closed');

						// Set timer for closing
						if(timer['open']) window.clearTimeout(timer['open']);
						timer['close'] = window.setTimeout(function() {
							$('.fluidbox-overlay').remove();
							$wrap.css({ 'z-index': settings.stackIndex - settings.stackIndexDelta });
						}, 10);

						// Hide overlay
						$('.fluidbox-overlay').css({ opacity: 0 });

						// Reverse animation on wrapped elements, and restore stacking order
						// You might want to change this value if your transition timing is longer
						$ghost.css({
							'transform': 'translate(0,0) scale(1)',
							opacity: 0,
							top: $img.offset().top - $wrap.offset().top + parseInt($img.css('borderTopWidth')) + parseInt($img.css('paddingTop')),
							left: $img.offset().left - $wrap.offset().left + parseInt($img.css('borderLeftWidth')) + parseInt($img.css('paddingLeft'))
						});
						$img.css({ opacity: 1 });
					}

					e.preventDefault();
				}
			};

		// When should we close Fluidbox?
		if(settings.closeTrigger) {
			// Go through array
			$.each(settings.closeTrigger, function (i) {
				var trigger = settings.closeTrigger[i];

				// Attach events
				if(trigger.selector != 'window') {
					// If it is not 'window', we append click handler to $(document) object, allow it to bubble up
					// However, if thes selector is 'document', we use a different .on() syntax
					if(trigger.selector == 'document') {
						if(trigger.keyCode) {
							$(document).on(trigger.event, function (e) {
								if(e.keyCode == trigger.keyCode) funcCloseFb();
							});
						} else {
							$(document).on(trigger.event, funcCloseFb);
						}
					} else {
						$(document).on(trigger.event, settings.closeTrigger[i].selector, funcCloseFb);
					}
				} else {
					// If it is 'window', append click handler to $(window) object
					$w.on(trigger.event, funcCloseFb);
				}
			});
		}

		// Go through each individual object
		$fb.each(function (i) {

			// Check if Fluidbox:
			// 1. Is an anchor element ,
			// 2. Contains one and ONLY one child
			// 3. The only child is an image element,
			// 4. If the element is hidden
			if($(this).is('a') && $(this).children().length === 1 && $(this).children().is('img') && $(this).css('display') !== 'none' && $(this).parents().css('display') !=='none') {

				// Define wrap
				var $fbInnerWrap = $('
', {
					'class': 'fluidbox-wrap',
					css: {
						'z-index': settings.stackIndex - settings.stackIndexDelta
					}
				});

				// Add class
				var $fbItem = $(this);
				$fbItem
				.addClass('fluidbox')
				.wrapInner($fbInnerWrap)
				.find('img')
					.css({ opacity: 1 })
					.after('
')
					.each(function(){
						var $img = $(this);

						if ($img.width() > 0 && $img.height() > 0) {
							// if image is already loaded (from cache)
							funcCalc($fbItem);
							$fbItem.click(fbClickHandler);
						} else {
							// wait for image to load
							$img.load(function(){
								funcCalc($fbItem);
								$fbItem.click(fbClickHandler);
							});
						}
				});

			}
		});

		// Listen to window resize event
		// Check if user wants to debounce the resize event (it is debounced by default)
		var funcResize = function () {
			// Recalculate dimensions
			funcCalcAll();

			// Reposition Fluidbox, but only if one is found to be open
			var $activeFb = $('a.fluidbox.fluidbox-opened');
			if($activeFb.length > 0) funcPositionFb($activeFb);
		}

		if(settings.debounceResize) {
			$(window).smartresize(funcResize);
		} else {
			$(window).resize(funcResize);
		}

		// Return to allow chaining
		return $fb;
	};

})(jQuery);<commit_msg>Version name update<commit_after>// Fluidbox
// Description: Replicating the seamless lightbox transition effect seen on Medium.com, with some improvements
// Version: 1.4.0
// Author: Terry Mun
// Author URI: http://terrymun.com

// --------------------------------------------------------
//  Dependency: Paul Irish's jQuery debounced resize event
// --------------------------------------------------------
(function($,sr){

	// debouncing function from John Hann
	// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
	var debounce = function (func, threshold, execAsap) {
		var timeout;

		return function debounced () {
			var obj = this, args = arguments;
			function delayed () {
				if (!execAsap)
				func.apply(obj, args);
				timeout = null;
			};

			if (timeout)
				clearTimeout(timeout);
			else if (execAsap)
				func.apply(obj, args);

			timeout = setTimeout(delayed, threshold || 100);
		};
	}
	// smartresize
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');

// -----------------------------
//  Fluidbox plugin starts here
// -----------------------------
(function ($) {

	$.fn.fluidbox = function (opts) {

		// Default settings
		var settings = $.extend(true, {
			viewportFill: 0.95,
			debounceResize: true,
			stackIndex: 1000,
			stackIndexDelta: 10,
			closeTrigger: [
				{
					selector: '.fluidbox-overlay',
					event: 'click'
				},
				{
					selector: 'document',
					event: 'keyup',
					keyCode: 27
				}
			]
		}, opts);

		// Ensure that the stackIndex does not become negative
		if(settings.stackIndex < settings.stackIndexDelta) settings.stackIndexDelta = settings.stackIndex;

		// Dynamically create overlay
		$fbOverlay = $('
', {
			'class': 'fluidbox-overlay',
			css: {
				'z-index': settings.stackIndex
			}
		});

		// Declare variables
		var $fb = this,
			$w = $(window),		// Shorthand for $(window)
			vpRatio,

			// Function:
			// 1. funcCloseFb()		- used to close any instance of opened Fluidbox
			// 2. funcPositionFb()	- used for dynamic positioning of any instance of opened Fluidbox
			// 3. funcCalcAll()		- used to run funcCalc() for every instance of targered Fluidbox thumbnail
			// 4. funcCalc()		- used to store dimensions of image, ghost element and wrapper element upon initialization or resize
			// 5. fbClickhandler()	- universal click handler for all Fluidbox items
			funcCloseFb = function () {
				$('.fluidbox-opened').trigger('click');
			},
			funcPositionFb = function ($activeFb) {
				// Get shorthand for more objects
				var $img    = $activeFb.find('img'),
					$ghost  = $activeFb.find('.fluidbox-ghost'),
					$wrap	= $activeFb.find('.fluidbox-wrap'),
					$data	= $activeFb.data(),
					fHeight = 0,
					fWidth	= 0;
                                $img.data().imgRatio = $data.natWidth/ $data.natHeight;

                                var newHeight, missingRatioNormal, missingRatio;

				// Check natural dimensions
				if(vpRatio > $img.data().imgRatio) {
					if($data.natHeight < $w.height()*settings.viewportFill) {
						fHeight = $data.natHeight;
					} else {
						fHeight = $w.height()*settings.viewportFill;
					}
					$data.imgScale = fHeight/$img.height();
                                        $data.imgScaleY = $data.imgScale;

                                        newHeight = $img.height() * $data.imgScaleY;
                                        missingRatioNormal = newHeight / $data.natHeight;
                                        missingRatio = $data.natWidth * missingRatioNormal / $img.width();

                                        $data.imgScaleX = missingRatio;
				} else {
					if($data.natWidth < $w.width()*settings.viewportFill) {
						fWidth = $data.natWidth;
					} else {
						fWidth = $w.width()*settings.viewportFill;
					}
					$data.imgScale = fWidth/$img.width();
                                        $data.imgScaleX = $data.imgScale;

                                        var newWidth = $img.width() * $data.imgScaleX;
                                        var missingRatioNormal = newWidth / $data.natWidth;
                                        var missingRatio = $data.natHeight * missingRatioNormal / $img.height();

                                        $data.imgScaleY = missingRatio;
				}

				// Calculation goes here
				var offsetY = $w.scrollTop()-$img.offset().top+0.5*($img.data('imgHeight')*($img.data('imgScale')-1))+0.5*($w.height()-$img.data('imgHeight')*$img.data('imgScale')),
					offsetX = 0.5*($img.data('imgWidth')*($img.data('imgScale')-1))+0.5*($w.width()-$img.data('imgWidth')*$img.data('imgScale'))-$img.offset().left,
                                        scale = parseInt($data.imgScaleX * 1000) / 1000 + ',' + parseInt($data.imgScaleY * 1000) / 1000;

				// Apply CSS transforms to ghost element
				// For offsetX and Y, we round to one decimal place
				// For scale, we round to three decimal places
				$ghost.css({
					'transform': 'translate('+parseInt(offsetX*10)/10+'px,'+parseInt(offsetY*10)/10+'px) scale('+ scale +')',
					top: $img.offset().top - $wrap.offset().top,
					left: $img.offset().left - $wrap.offset().left
				});
			},
			funcCalcAll = function() {
				$fb.each(function () {
					funcCalc($(this));
				});
			},
			funcCalc = function ($fbItem) {
				// Get viewport ratio
				vpRatio = $w.width() / $w.height();

				// Get image dimensions and aspect ratio
				if($fbItem.hasClass('fluidbox')) {
					var $img	= $fbItem.find('img'),
						$ghost	= $fbItem.find('.fluidbox-ghost'),
						$wrap	= $fbItem.find('.fluidbox-wrap'),
						data	= $img.data();

					function imageProp() {
						// Store image dimensions in jQuery object
						data.imgWidth	= $img.width();
						data.imgHeight	= $img.height();
						data.imgRatio	= $img.width()/$img.height();

						// Resize and position ghost element
						$ghost.css({
							width: $img.width(),
							height: $img.height(),
							top: $img.offset().top - $wrap.offset().top + parseInt($img.css('borderTopWidth')) + parseInt($img.css('paddingTop')),
							left: $img.offset().left - $wrap.offset().left + parseInt($img.css('borderLeftWidth')) + parseInt($img.css('paddingLeft'))
						});

						// Calculate scale based on orientation
						if(vpRatio > data.imgRatio) {
							data.imgScale = $w.height()*settings.viewportFill/$img.height();
						} else {
							data.imgScale = $w.width()*settings.viewportFill/$img.width();
						}
					}

					imageProp();

					// Rerun everything on imageload, to overcome issue in Firefox
					$img.load(imageProp);
				}
			},
			fbClickHandler = function(e) {

				// Check if the fluidbox element does have .fluidbox assigned to it
				if($(this).hasClass('fluidbox')) {

					// Variables
					var $activeFb	= $(this),
						$img		= $(this).find('img'),
						$ghost		= $(this).find('.fluidbox-ghost'),
						$wrap   	= $(this).find('.fluidbox-wrap'),
						timer   	= {};

					if($(this).data('fluidbox-state') === 0 || !$(this).data('fluidbox-state')) {
						// State: Closed
						// Action: Open fluidbox

						// Wait for ghost image to be loaded successfully first, then do the rest
						$('', {
							src: $img.attr('src')
						}).load(function () {
							// Preload ghost image
							$('', {
								src: $activeFb.attr('href')
							}).load(function() {
								// Store natural width and heights
								$activeFb
								.data('natWidth', $(this)[0].naturalWidth)
								.data('natHeight', $(this)[0].naturalHeight);

								// What are we doing here:
								// 1. Append overlay in fluidbox
								// 2. Toggle fluidbox state with data attribute
								// 3. Store original z-index with data attribute (so users can change z-index when they see fit in CSS file)
								// 4. Class toggle
								$activeFb
								.append($fbOverlay)
								.data('fluidbox-state', 1)
								.removeClass('fluidbox-closed')
								.addClass('fluidbox-opened');

								// Force timer to completion
								if(timer['close']) window.clearTimeout(timer['close']);

								// Set timer for opening
								timer['open'] = window.setTimeout(function() {
									// Show overlay
									$('.fluidbox-overlay').css({ opacity: 1 });
								}, 10);

								// Change wrapper z-index, so it is above everything else
								// Decrease all siblings z-index by 1 just in case
								$('.fluidbox-wrap').css({ zIndex: settings.stackIndex - settings.stackIndexDelta - 1 });
								$wrap.css({ 'z-index': settings.stackIndex + settings.stackIndexDelta });

								// Set thumbnail image source as background image first, preload later
								$ghost.css({
									'background-image': 'url('+$img.attr('src')+')',
									opacity: 1
								});

								// Hide original image
								$img.css({ opacity: 0 });

								$ghost.css({ 'background-image': 'url('+$activeFb.attr('href')+')' });

								// Position Fluidbox
								funcPositionFb($activeFb);
							});
						});

					} else {
						// State: Open
						// Action: Close fluidbox

						// Switch state
						$activeFb
						.data('fluidbox-state', 0)
						.removeClass('fluidbox-opened')
						.addClass('fluidbox-closed');

						// Set timer for closing
						if(timer['open']) window.clearTimeout(timer['open']);
						timer['close'] = window.setTimeout(function() {
							$('.fluidbox-overlay').remove();
							$wrap.css({ 'z-index': settings.stackIndex - settings.stackIndexDelta });
						}, 10);

						// Hide overlay
						$('.fluidbox-overlay').css({ opacity: 0 });

						// Reverse animation on wrapped elements, and restore stacking order
						// You might want to change this value if your transition timing is longer
						$ghost.css({
							'transform': 'translate(0,0) scale(1)',
							opacity: 0,
							top: $img.offset().top - $wrap.offset().top + parseInt($img.css('borderTopWidth')) + parseInt($img.css('paddingTop')),
							left: $img.offset().left - $wrap.offset().left + parseInt($img.css('borderLeftWidth')) + parseInt($img.css('paddingLeft'))
						});
						$img.css({ opacity: 1 });
					}

					e.preventDefault();
				}
			};

		// When should we close Fluidbox?
		if(settings.closeTrigger) {
			// Go through array
			$.each(settings.closeTrigger, function (i) {
				var trigger = settings.closeTrigger[i];

				// Attach events
				if(trigger.selector != 'window') {
					// If it is not 'window', we append click handler to $(document) object, allow it to bubble up
					// However, if thes selector is 'document', we use a different .on() syntax
					if(trigger.selector == 'document') {
						if(trigger.keyCode) {
							$(document).on(trigger.event, function (e) {
								if(e.keyCode == trigger.keyCode) funcCloseFb();
							});
						} else {
							$(document).on(trigger.event, funcCloseFb);
						}
					} else {
						$(document).on(trigger.event, settings.closeTrigger[i].selector, funcCloseFb);
					}
				} else {
					// If it is 'window', append click handler to $(window) object
					$w.on(trigger.event, funcCloseFb);
				}
			});
		}

		// Go through each individual object
		$fb.each(function (i) {

			// Check if Fluidbox:
			// 1. Is an anchor element ,
			// 2. Contains one and ONLY one child
			// 3. The only child is an image element,
			// 4. If the element is hidden
			if($(this).is('a') && $(this).children().length === 1 && $(this).children().is('img') && $(this).css('display') !== 'none' && $(this).parents().css('display') !=='none') {

				// Define wrap
				var $fbInnerWrap = $('
', {
					'class': 'fluidbox-wrap',
					css: {
						'z-index': settings.stackIndex - settings.stackIndexDelta
					}
				});

				// Add class
				var $fbItem = $(this);
				$fbItem
				.addClass('fluidbox')
				.wrapInner($fbInnerWrap)
				.find('img')
					.css({ opacity: 1 })
					.after('
')
					.each(function(){
						var $img = $(this);

						if ($img.width() > 0 && $img.height() > 0) {
							// if image is already loaded (from cache)
							funcCalc($fbItem);
							$fbItem.click(fbClickHandler);
						} else {
							// wait for image to load
							$img.load(function(){
								funcCalc($fbItem);
								$fbItem.click(fbClickHandler);
							});
						}
				});

			}
		});

		// Listen to window resize event
		// Check if user wants to debounce the resize event (it is debounced by default)
		var funcResize = function () {
			// Recalculate dimensions
			funcCalcAll();

			// Reposition Fluidbox, but only if one is found to be open
			var $activeFb = $('a.fluidbox.fluidbox-opened');
			if($activeFb.length > 0) funcPositionFb($activeFb);
		}

		if(settings.debounceResize) {
			$(window).smartresize(funcResize);
		} else {
			$(window).resize(funcResize);
		}

		// Return to allow chaining
		return $fb;
	};

})(jQuery);<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var GitStatistics = require("../classes/gitStatistics.js");

function Updater() {
  this.updateData = function() {
    fs.readdir('./repos/',function(err, files) {
      if(err) throw err;
      files.forEach(function(file) {
        var repoPath = path.join('./repos/', file);
        if(fs.lstatSync(repoPath).isDirectory()) {
          var gitStatistics = new GitStatistics(repoPath);
          gitStatistics.updateRepo(function(){
          });
        }
      });
    });
  }
}

module.exports = Updater;<commit_msg>Refactoring - broke out method to get all repos<commit_after>var fs = require('fs');
var path = require('path');
var GitStatistics = require("../classes/gitStatistics.js");

function Updater() {
  this.updateData = function() {
    var repos = this.getAllRepos();
    repos.forEach(function(repo) {
      var gitStatistics = new GitStatistics(repo);
      gitStatistics.updateRepo(function() {});
    });
  }

  this.getAllRepos = function() {
    var repos = new Array();
    var files = fs.readdirSync('./repos/');
    files.forEach(function(file) {
      var repoPath = path.join('./repos/', file);
      if(fs.lstatSync(repoPath).isDirectory()) {
        repos.push(repoPath);
      }
    });

    return repos;
  }
}

module.exports = Updater;<|endoftext|>


<commit_before>$.fn.markdown = function (preview) {
  var textarea = $(this).get(0);
  var converter = new Showdown.converter;
  if (!preview) {
    preview = '#markdown_formatted'
  }

  var get_renderer = function(content) {
    var iframe = $('', {
      css: { width: '100%', height: "100%"}
    }).appendTo('#markdown_formatted')

    iframe = iframe[0]
    doc = iframe.document;
    if(iframe.contentDocument)
      doc = iframe.contentDocument; // For NS6
    else if(iframe.contentWindow)
      doc = iframe.contentWindow.document; // For IE5.5 and IE6

    // Put the content in the iframe
    doc.open();
    doc.writeln('

');
    doc.close();
    return doc.getElementById('formatted');
  }
  var renderer = get_renderer();

  var converter_callback = function(value) {
    renderer.innerHTML = converter.makeHtml(value);
  }

  var textarea = $(textarea).TextArea({
  	change: converter_callback
  });

  var toolbar = $.Toolbar(textarea, {
  	className: "markdown_toolbar"
  });

  var setup_toolbar = function(toolbar) {
    //buttons
    toolbar.addButton('Italics',function(){
        this.wrapSelection('*','*');
    },{
        id: 'markdown_italics_button'
    });

    toolbar.addButton('Bold',function(){
        this.wrapSelection('**','**');
    },{
        id: 'markdown_bold_button'
    });

		toolbar.addButton('Link',function(){
		    var selection = this.getSelection();
		    var response = prompt('Enter Link URL','');
		    if(response == null)
		        return;
		    this.replaceSelection('[' + (selection == '' ? 'Link Text' : selection) + '](' + (response == '' ? 'http://link_url/' : response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://') + ')');
		},{
		    id: 'markdown_link_button'
		});

    toolbar.addButton('Image',function(){
        var selection = this.getSelection();
        var response = prompt('Enter Image URL','');
        if(response == null)
            return;
        this.replaceSelection('![' + (selection == '' ? 'Image Alt Text' : selection) + '](' + (response == '' ? 'http://image_url/' : response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://') + ')');
    },{
        id: 'markdown_image_button'
    });

    toolbar.addButton('Heading',function(){
        var selection = this.getSelection() || 'Heading';
        if (selection == '') {
          selection = 'Heading';
        }

        for (var underscores = [], i = 0; i < Math.max(5,selection.length); i++) {
          underscores.push('-')
        }

        this.replaceSelection("\n" + selection + "\n" + underscores.join(''));
    },{
        id: 'markdown_heading_button'
    });

    toolbar.addButton('Unordered List',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? (line.match(/^\*{2,}/) ? line.replace(/^\*/,'') : line.replace(/^\*\s/,'')) : (line.match(/\*+\s/) ? '*' : '* ') + line;
        });
    },{
        id: 'markdown_unordered_list_button'
    });

    toolbar.addButton('Ordered List',function(event){
        var i = 0;
        this.collectFromEachSelectedLine(function(line){
            if(!line.match(/^\s+$/)){
                ++i;
                return event.shiftKey ? line.replace(/^\d+\.\s/,'') : (line.match(/\d+\.\s/) ? '' : i + '. ') + line;
            }
        });
    },{
        id: 'markdown_ordered_list_button'
    });

    toolbar.addButton('Block Quote',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? line.replace(/^\> /,'') : '> ' + line;
        });
    },{
        id: 'markdown_quote_button'
    });

    toolbar.addButton('Code Block',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? line.replace(/    /,'') : '    ' + line;
        });
    },{
        id: 'markdown_code_button'
    });

    toolbar.addButton('Help',function(){
        window.open('http://daringfireball.net/projects/markdown/dingus');
    },{
        id: 'markdown_help_button'
    });

  }

  setup_toolbar(toolbar)
}
<commit_msg>Fixed iframe append to preview container rather than hard coded element<commit_after>$.fn.markdown = function (preview) {
  var textarea = $(this).get(0);
  var converter = new Showdown.converter;
  if (!preview) {
    preview = '#markdown_formatted'
  }

  var get_renderer = function(content) {
    var iframe = $('', {
      css: { width: '100%', height: "100%"}
    }).appendTo(preview)

    iframe = iframe[0]
    doc = iframe.document;
    if(iframe.contentDocument)
      doc = iframe.contentDocument; // For NS6
    else if(iframe.contentWindow)
      doc = iframe.contentWindow.document; // For IE5.5 and IE6

    // Put the content in the iframe
    doc.open();
    doc.writeln('

');
    doc.close();
    return doc.getElementById('formatted');
  }
  var renderer = get_renderer();

  var converter_callback = function(value) {
    renderer.innerHTML = converter.makeHtml(value);
  }

  var textarea = $(textarea).TextArea({
  	change: converter_callback
  });

  var toolbar = $.Toolbar(textarea, {
  	className: "markdown_toolbar"
  });

  var setup_toolbar = function(toolbar) {
    //buttons
    toolbar.addButton('Italics',function(){
        this.wrapSelection('*','*');
    },{
        id: 'markdown_italics_button'
    });

    toolbar.addButton('Bold',function(){
        this.wrapSelection('**','**');
    },{
        id: 'markdown_bold_button'
    });

		toolbar.addButton('Link',function(){
		    var selection = this.getSelection();
		    var response = prompt('Enter Link URL','');
		    if(response == null)
		        return;
		    this.replaceSelection('[' + (selection == '' ? 'Link Text' : selection) + '](' + (response == '' ? 'http://link_url/' : response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://') + ')');
		},{
		    id: 'markdown_link_button'
		});

    toolbar.addButton('Image',function(){
        var selection = this.getSelection();
        var response = prompt('Enter Image URL','');
        if(response == null)
            return;
        this.replaceSelection('![' + (selection == '' ? 'Image Alt Text' : selection) + '](' + (response == '' ? 'http://image_url/' : response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://') + ')');
    },{
        id: 'markdown_image_button'
    });

    toolbar.addButton('Heading',function(){
        var selection = this.getSelection() || 'Heading';
        if (selection == '') {
          selection = 'Heading';
        }

        for (var underscores = [], i = 0; i < Math.max(5,selection.length); i++) {
          underscores.push('-')
        }

        this.replaceSelection("\n" + selection + "\n" + underscores.join(''));
    },{
        id: 'markdown_heading_button'
    });

    toolbar.addButton('Unordered List',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? (line.match(/^\*{2,}/) ? line.replace(/^\*/,'') : line.replace(/^\*\s/,'')) : (line.match(/\*+\s/) ? '*' : '* ') + line;
        });
    },{
        id: 'markdown_unordered_list_button'
    });

    toolbar.addButton('Ordered List',function(event){
        var i = 0;
        this.collectFromEachSelectedLine(function(line){
            if(!line.match(/^\s+$/)){
                ++i;
                return event.shiftKey ? line.replace(/^\d+\.\s/,'') : (line.match(/\d+\.\s/) ? '' : i + '. ') + line;
            }
        });
    },{
        id: 'markdown_ordered_list_button'
    });

    toolbar.addButton('Block Quote',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? line.replace(/^\> /,'') : '> ' + line;
        });
    },{
        id: 'markdown_quote_button'
    });

    toolbar.addButton('Code Block',function(event){
        this.collectFromEachSelectedLine(function(line){
            return event.shiftKey ? line.replace(/    /,'') : '    ' + line;
        });
    },{
        id: 'markdown_code_button'
    });

    toolbar.addButton('Help',function(){
        window.open('http://daringfireball.net/projects/markdown/dingus');
    },{
        id: 'markdown_help_button'
    });

  }

  setup_toolbar(toolbar)
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

'use strict';

const del = require('del');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const mergeStream = require('merge-stream');
const polymerBuild = require('polymer-build');

// Additional plugins can be used to optimize your source files after splitting.
// Before using each plugin, install with `npm i --save-dev <package-name>`
const uglify = require('gulp-uglify');
const gutil = require('gulp-util');
const cssSlam = require('css-slam').gulp;
const htmlMinifier = require('gulp-html-minifier');

const swPrecacheConfig = require('./sw-precache-config.js');
const polymerJson = require('./polymer.json');
const polymerProject = new polymerBuild.PolymerProject(polymerJson);
const buildDirectory = 'build';

/**
 * Waits for the given ReadableStream
 */
function waitFor(stream) {
  return new Promise((resolve, reject) => {
    stream.on('end', resolve);
    stream.on('error', reject);
  });
}

function build() {
  return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars

    // Lets create some inline code splitters in case you need them later in your build.
    let sourcesStreamSplitter = new polymerBuild.HtmlSplitter();
    let dependenciesStreamSplitter = new polymerBuild.HtmlSplitter();

    // Okay, so first thing we do is clear the build directory
    console.log(`Deleting ${buildDirectory} directory...`);
    del([buildDirectory])
      .then(() => {
        let htmlMinifyOptions = {collapseWhitespace: true, removeComments: true, conservativeCollapse: true};

        // Let's start by getting your source files. These are all the files
        // in your `src/` directory, or those that match your polymer.json
        // "sources"  property if you provided one.
        let sourcesStream = polymerProject.sources()

          // The `sourcesStreamSplitter` created above can be added here to
          // pull any inline styles and scripts out of their HTML files and
          // into seperate CSS and JS files in the build stream. Just be sure
          // to rejoin those files with the `.rejoin()` method when you're done.
          .pipe(sourcesStreamSplitter.split())

          // Uncomment these lines to add a few more example optimizations to your
          // source files, but these are not included by default. For installation, see
          // the require statements at the beginning.
          .pipe(gulpif(/\.js$/, uglify())) // Install gulp-uglify to use
          .on('error', err => {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
          })
          .pipe(cssSlam()) // Install css-slam to use
          .pipe(gulpif(/\.html$/, htmlMinifier(htmlMinifyOptions))) // Install gulp-html-minifier to use

          // Remember, you need to rejoin any split inline code when you're done.
          .pipe(sourcesStreamSplitter.rejoin());

        // Similarly, you can get your dependencies seperately and perform
        // any dependency-only optimizations here as well.
        let dependenciesStream = polymerProject.dependencies()
          .pipe(dependenciesStreamSplitter.split())
          // Add any dependency optimizations here.
          .pipe(gulpif(/\.js$/, uglify())) // Install gulp-uglify to use
          .on('error', err => {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
          })
          .pipe(cssSlam()) // Install css-slam to use
          .pipe(gulpif(/\.html$/, htmlMinifier(htmlMinifyOptions))) // Install gulp-html-minifier to use
          .pipe(dependenciesStreamSplitter.rejoin());

        // Okay, now let's merge your sources & dependencies together into a single build stream.
        let buildStream = mergeStream(sourcesStream, dependenciesStream)
          .once('data', () => {
            console.log('Analyzing build dependencies...');
          });

        // If you want bundling, pass the stream to polymerProject.bundler.
        // This will bundle dependencies into your fragments so you can lazy
        // load them.
        buildStream = buildStream.pipe(polymerProject.bundler());

        // Okay, time to pipe to the build directory
        buildStream = buildStream.pipe(gulp.dest(buildDirectory));

        // waitFor the buildStream to complete
        return waitFor(buildStream);
      })
      .then(() => {
        // Okay, now let's generate the Service Worker
        console.log('Generating the Service Worker...');
        return polymerBuild.addServiceWorker({
          project: polymerProject,
          buildRoot: buildDirectory,
          bundled: true,
          swPrecacheConfig: swPrecacheConfig
        });
      })
      .then(() => {
        // You did it!
        console.log('Build complete!');
        resolve();
      });
  });
}

gulp.task('build', build);<commit_msg>Fix missing CSS file in build (#1112)<commit_after>/**
 * @license
 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

'use strict';

const del = require('del');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const mergeStream = require('merge-stream');
const polymerBuild = require('polymer-build');

// Additional plugins can be used to optimize your source files after splitting.
// Before using each plugin, install with `npm i --save-dev <package-name>`
const uglify = require('gulp-uglify');
const gutil = require('gulp-util');
const cssSlam = require('css-slam').gulp;
const htmlMinifier = require('gulp-html-minifier');

const swPrecacheConfig = require('./sw-precache-config.js');
const polymerJson = require('./polymer.json');
const polymerProject = new polymerBuild.PolymerProject(polymerJson);
const buildDirectory = 'build';

/**
 * Waits for the given ReadableStream
 */
function waitFor(stream) {
  return new Promise((resolve, reject) => {
    stream.on('end', resolve);
    stream.on('error', reject);
  });
}

function build() {
  return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars

    // Lets create some inline code splitters in case you need them later in your build.
    let sourcesStreamSplitter = new polymerBuild.HtmlSplitter();
    let dependenciesStreamSplitter = new polymerBuild.HtmlSplitter();

    // Okay, so first thing we do is clear the build directory
    console.log(`Deleting ${buildDirectory} directory...`);
    del([buildDirectory])
      .then(() => {
        let htmlMinifyOptions = {collapseWhitespace: true, removeComments: true, conservativeCollapse: true};

        // Let's start by getting your source files. These are all the files
        // in your `src/` directory, or those that match your polymer.json
        // "sources"  property if you provided one.
        let sourcesStream = polymerProject.sources()

          // The `sourcesStreamSplitter` created above can be added here to
          // pull any inline styles and scripts out of their HTML files and
          // into seperate CSS and JS files in the build stream. Just be sure
          // to rejoin those files with the `.rejoin()` method when you're done.
          .pipe(sourcesStreamSplitter.split())

          // Uncomment these lines to add a few more example optimizations to your
          // source files, but these are not included by default. For installation, see
          // the require statements at the beginning.
          .pipe(gulpif(/\.js$/, uglify())) // Install gulp-uglify to use
          .on('error', err => {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
          })
          .pipe(cssSlam()) // Install css-slam to use
          .pipe(gulpif(/\.html$/, htmlMinifier(htmlMinifyOptions))) // Install gulp-html-minifier to use

          // Remember, you need to rejoin any split inline code when you're done.
          .pipe(sourcesStreamSplitter.rejoin());

        // Similarly, you can get your dependencies seperately and perform
        // any dependency-only optimizations here as well.
        let dependenciesStream = polymerProject.dependencies()
          .pipe(dependenciesStreamSplitter.split())
          // Add any dependency optimizations here.
          .pipe(gulpif(/\.js$/, uglify())) // Install gulp-uglify to use
          .on('error', err => {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
          })
          .pipe(cssSlam()) // Install css-slam to use
          .pipe(gulpif(/\.html$/, htmlMinifier(htmlMinifyOptions))) // Install gulp-html-minifier to use
          .pipe(dependenciesStreamSplitter.rejoin());

        // Okay, now let's merge your sources & dependencies together into a single build stream.
        let buildStream = mergeStream(sourcesStream, dependenciesStream)
          .once('data', () => {
            console.log('Analyzing build dependencies...');
          });

        // If you want bundling, pass the stream to polymerProject.bundler.
        // This will bundle dependencies into your fragments so you can lazy
        // load them.
        buildStream = buildStream.pipe(polymerProject.bundler());

        // Okay, time to pipe to the build directory
        buildStream = buildStream.pipe(gulp.dest(buildDirectory));

        // waitFor the buildStream to complete
        return waitFor(buildStream);
      })
      .then(() => {
        // Okay, now let's generate the Service Worker
        console.log('Generating the Service Worker...');
        return polymerBuild.addServiceWorker({
          project: polymerProject,
          buildRoot: buildDirectory,
          bundled: true,
          swPrecacheConfig: swPrecacheConfig
        });
      })
      .then(() => {
        return gulp.src('node_modules/codemirror/lib/codemirror.css',
          {base: '.'}).pipe(gulp.dest(buildDirectory));
      })
      .then(() => {
        // You did it!
        console.log('Build complete!');
        resolve();
      });
  });
}

gulp.task('build', build);
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');

/**
 * Model that represents a visualization (v3)
 *
 * Even though a table might be represented as a Visualization in some cases, please use TableModel if you want to work
 * with the table data instead of adding table-specific methods here.
 */

var ALL_PRIVACY_OPTIONS = ['PUBLIC', 'LINK', 'PRIVATE', 'PASSWORD'];

module.exports = Backbone.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');

    this._configModel = opts.configModel;
  },

  urlRoot: function () {
    var baseUrl = this._configModel.get('base_url');
    var version = this._configModel.urlVersion('visualization');
    return baseUrl + '/api/' + version + '/viz';
  },

  mapcapsURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v3/viz/' + this.id + '/mapcaps';
  },

  embedURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/builder/' + this.id + '/embed';
  },

  builderURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/builder/' + this.id + '/';
  },

  vizjsonURL: function () {
    var baseUrl = this._configModel.get('base_url');
    var version = this._configModel.urlVersion('vizjson', 'read', 'v2');
    return baseUrl + '/api/' + version + '/viz/' + this.id + '/viz.json';
  },

  isVisualization: function () {
    return this.get('type') === 'derived';
  },

  privacyOptions: function () {
    if (this.isVisualization()) {
      return ALL_PRIVACY_OPTIONS;
    } else {
      return _.reject(ALL_PRIVACY_OPTIONS, function (option) {
        return option === 'PASSWORD';
      });
    }
  }
});
<commit_msg>fixes #8519<commit_after>var _ = require('underscore');
var Backbone = require('backbone');

/**
 * Model that represents a visualization (v3)
 *
 * Even though a table might be represented as a Visualization in some cases, please use TableModel if you want to work
 * with the table data instead of adding table-specific methods here.
 */

var ALL_PRIVACY_OPTIONS = ['PUBLIC', 'LINK', 'PRIVATE', 'PASSWORD'];

module.exports = Backbone.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');

    this._configModel = opts.configModel;
  },

  urlRoot: function () {
    var baseUrl = this._configModel.get('base_url');
    var version = this._configModel.urlVersion('visualization');
    return baseUrl + '/api/' + version + '/viz';
  },

  mapcapsURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v3/viz/' + this.id + '/mapcaps';
  },

  embedURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/builder/' + this.id + '/embed';
  },

  builderURL: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/builder/' + this.id + '/';
  },

  vizjsonURL: function () {
    var baseUrl = this._configModel.get('base_url');
    var version = this._configModel.urlVersion('vizjson', 'read', 'v3');
    return baseUrl + '/api/' + version + '/viz/' + this.id + '/viz.json';
  },

  isVisualization: function () {
    return this.get('type') === 'derived';
  },

  privacyOptions: function () {
    if (this.isVisualization()) {
      return ALL_PRIVACY_OPTIONS;
    } else {
      return _.reject(ALL_PRIVACY_OPTIONS, function (option) {
        return option === 'PASSWORD';
      });
    }
  }
});
<|endoftext|>