<commit_before>jQuery(document).ready(function () {

    // set global Variables
    var mMeldung, mAddition, m_key;
    var mLostFound, mTrainNumber, mNumberPersons, mLift, mWheelchair, mEscort, mArrivalStation, mMaPhone, mLiftArrivelTime, mLiftEndedTime, mPoliceInfo, mHospitalInfo, mConcernSecurity;
    var mName, mAddress, mContact, mComment;

    if (localStorage.getItem("fe_user")) {
        // Set key for Meldung
        m_key = 'm_' + localStorage.getItem("fe_user");
    }

    function newMeldung(feUser,mString){

			//consoleLog('debug', "Create new Stoerungsmeldung / Start");

			var data, mDateTime, mPosition, mMeldung, url, request, jqxhr, uid, jmString, mPics, pData, mAddition, mComment;
			var m_key = 'm_' + localStorage.getItem("fe_user");

			mString = mString.replace(/\n/g,"\\n")
			jmString = JSON.parse(mString);

			mDateTime = jmString[0]["datetime"];
			mPosition = jmString[0]["position"];
			mMeldung = jmString[0].meldung;
			mPics = jmString[0].pics;
			mLostFound = jmString[0].lostfound;
                        mComment = jmString[0].comment;
			mTrainNumber = jmString[0].trainnumber;
			mNumberPersons = jmString[0].numberpersons;
			mLift = jmString[0].lift;
			mWheelchair = jmString[0].wheelchair;
			mEscort = jmString[0].escort;
			mArrivalStation = jmString[0].arrivalstation;
			mMaPhone = jmString[0].maphone;
			mLiftArrivelTime = jmString[0].liftarrivaltime;
			mLiftEndedTime = jmString[0].liftendedtime;
			mPoliceInfo = jmString[0].policeinfo;
			mHospitalInfo = jmString[0].hospitalinfo;
			mConcernSecurity = jmString[0].concernsecurity;
			mName = jmString[0].name;
			mAddress = jmString[0].address;
			mContact = jmString[0].contact;

			url = "http://active.mungos-services.at/index.php";

			data = {
					'id': 79,
					'no_cache': 1,
					'type': 97,
					'tx_mungosstoerung[action]': "create",
					'tx_mungosstoerung[feUser]': feUser,
					'tx_mungosstoerung[dateTime]': mDateTime,
					'tx_mungosstoerung[geoData]': mPosition,
					'tx_mungosstoerung[type]': mMeldung,
					'tx_mungosstoerung[images]': mPics,
					'tx_mungosstoerung[lostFound]': mLostFound,
					'tx_mungosstoerung[comment]': mComment,
					'tx_mungosstoerung[trainNumber]': mTrainNumber,
					'tx_mungosstoerung[numberPersons]': mNumberPersons,
					'tx_mungosstoerung[lift]': mLift,
					'tx_mungosstoerung[wheelchair]': mWheelchair,
					'tx_mungosstoerung[escort]': mEscort,
					'tx_mungosstoerung[arrivalStation]': mArrivalStation,
					'tx_mungosstoerung[maPhoneInfo]': mMaPhone,
					'tx_mungosstoerung[liftArrivelTime]': mLiftArrivelTime,
					'tx_mungosstoerung[liftEndedTime]': mLiftEndedTime,
					'tx_mungosstoerung[policeInfo]': mPoliceInfo,
					'tx_mungosstoerung[hospitalInfo]': mHospitalInfo,
					'tx_mungosstoerung[concernSecurity]': mConcernSecurity,
					'tx_mungosstoerung[name]': mName,
					'tx_mungosstoerung[address]': mAddress,
					'tx_mungosstoerung[contact]': mContact
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function(json) {
							//alert("Meldung erfolgreich");
							//consoleLog('debug', "Störungsmeldung gespeichert (uid:"+json.uid+")");
							//consoleLog('debug', JSON.stringify(data));
							localStorage.removeItem(m_key);
							localStorage.removeItem("pics");
							jQuery("input[type=text], textarea").val("");
							jQuery("input[type=checkbox]").attr('checked', false);
							jQuery("input[type=radio]").attr('checked', false);
							jQuery("#eingetroffeneStunde").val("");
							jQuery("#eingetroffeneMinute").val("");
							jQuery("#beendetStunde").val("");
							jQuery("#beendetMinute").val("");
					},
					error: function(xOptions, textStatus, error){
							//consoleLog('debug', "Störungsmeldung error");
							alert("Meldung fehlgeschlagen: " + textStatus + " " + error);
					}
			});

			return false;

    }

    jQuery(".saveMeldung").on('click', function () {

			if(jQuery(this).hasClass("meldung01")) {
					mMeldung = "Vandalismus";
			}else if(jQuery(this).hasClass("meldung02")) {
					mMeldung = "Lost & Found";
			}else if(jQuery(this).hasClass("meldung03")) {
					mMeldung = "Unangemeldete Ein-, Ausstieghilfe";
			}else if(jQuery(this).hasClass("meldung04")) {
					mMeldung = "Aufzugsbefreiung";
			}else if(jQuery(this).hasClass("meldung05")) {
					mMeldung = "Gewalt an Mitarbeiter";
			}else if(jQuery(this).hasClass("meldung06")) {
					mMeldung = "Einbruch / Diebstahl";
			}else if(jQuery(this).hasClass("meldung07")) {
					mMeldung = "Beschwerden / Anfragen";
			}else if(jQuery(this).hasClass("meldung08")) {
					mMeldung = "Randgruppen";
			}else if(jQuery(this).hasClass("meldung09")) {
					mMeldung = "Raucherstrafen";
			}else if(jQuery(this).hasClass("meldung10")) {
					mMeldung = "Verweise / Belehrung";
			}

			mLostFound = jQuery(".meRadio:checked").length > 0 ? jQuery(".meRadio:checked").val() : "";
			mTrainNumber = jQuery("#uEzn").val().length > 0 ? jQuery("#uEzn").val() : "";
			mNumberPersons = jQuery("#uEAz").val().length > 0 ? jQuery("#uEAz").val() : "";
			mArrivalStation = jQuery("#uEbh").val().length > 0 ? jQuery("#uEbh").val() : "";
			mLift = jQuery("#Hebelift").prop('checked') ? 1 : 0;
			mWheelchair = jQuery("#Bahnrollstuhl").prop('checked') ? 1 : 0;
			mEscort = jQuery("#Begleitung").prop('checked') ? 1 : 0;
			mMaPhone = jQuery("#maTel").prop('checked') ? 1 : 0;
			mLiftArrivelTime = jQuery("#eingetroffeneStunde").val().length > 0 && jQuery("#eingetroffeneMinute").val().length ?
					jQuery("#eingetroffeneStunde").val()+":"+jQuery("#eingetroffeneMinute").val() : "";
			mLiftEndedTime = jQuery("#beendetStunde").val().length > 0 && jQuery("#beendetMinute").val().length ?
					jQuery("#beendetStunde").val()+":"+jQuery("#beendetMinute").val() : "";
			mConcernSecurity = jQuery("#Konzernsicherheit").prop('checked') ? 1 : 0;
			mName = jQuery("#beschwerdeName").val().length > 0 ? jQuery("#beschwerdeName").val() : "";
			mAddress = jQuery("#beschwerdeAdresse").val().length > 0 ? jQuery("#beschwerdeAdresse").val() : "";
			mContact = jQuery("#beschwerdeKontakt").val().length > 0 ? jQuery("#beschwerdeKontakt").val() : "";
                        mComment = jQuery("#comment").val().length > 0 ? jQuery("#comment").val() : "";

			if(jQuery("#wachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#wachzimmer").val();
			}
			else if(jQuery("#gewaltWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#gewaltWachzimmer").val();
			}
			else if(jQuery("#gewaltWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#gewaltWachzimmer").val();
			}
			else if(jQuery("#einbruchWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#einbruchWachzimmer").val();
			}  else {
					mPoliceInfo = "";
			}

			if(jQuery("#gewaltKrankenhaus").val().length > 0){
					mHospitalInfo = jQuery("#gewaltKrankenhaus").val();
			/*}
			else if(jQuery("#einbruchKrankenhaus").val().length > 0){
					mHospitalInfo = jQuery("#einbruchKrankenhaus").val();*/
			}else {
					mHospitalInfo = "";
			}

			// opens the confirm dialog
			jQuery.mobile.changePage("#confirmDialog", {
					transition: "slidedown",
					changeHash: false
			});

			// writes the text of the current meldung in the confirm box
			jQuery(".confContent").find("h1").text("Möchten Sie die Meldung \""+mMeldung+"\" abschicken?");

    });

    jQuery(".mConfirm").on('click',function () {

			var mDateTime, mString, position, mPos, mPics;

			navigator.geolocation.getCurrentPosition(saveLocalMeldung, onGeoError);

			// set Meldungsstring in Localstorage
			function saveLocalMeldung(position){

				d = new Date();
				m = d.getMonth() + 1;

				mDateTime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();
				mPos = position.coords.latitude + "," + position.coords.longitude;
				mPics = localStorage.getItem("pics");

				mString = '[{   "datetime" : "' + mDateTime
						+ '", "position" : "' + mPos
						+ '", "meldung" : "' + mMeldung
						+ '", "pics" : "' + mPics
						+ '", "lostfound" : "' + mLostFound
            + '", "comment" : "' + mComment
						+ '", "trainnumber" : "' + mTrainNumber
						+ '", "numberpersons" : "' + mNumberPersons
						+ '", "lift" : "' + mLift
						+ '", "wheelchair" : "' + mWheelchair
						+ '", "escort" : "' + mEscort
						+ '", "arrivalstation" : "' + mArrivalStation
						+ '", "maphone" : "' + mMaPhone
						+ '", "liftarrivaltime" : "' + mLiftArrivelTime
						+ '", "liftendedtime" : "' + mLiftEndedTime
						+ '", "policeinfo" : "' + mPoliceInfo
						+ '", "hospitalinfo" : "' + mHospitalInfo
						+ '", "concernsecurity" : "' + mConcernSecurity
						+ '", "name" : "' + mName
						+ '", "address" : "' + mAddress
						+ '", "contact" : "' + mContact
						+ '" }]';

				localStorage.setItem(m_key, mString);

        saveMeldung();
      }

			function saveMeldung() {

				uploadFiles();

				// Set key for Meldung
				m_key = 'm_' + localStorage.getItem("fe_user");

				newMeldung(localStorage.getItem("fe_user"),localStorage.getItem(m_key));

				jQuery(".meForm").each(function(){
						jQuery(this).slideUp("fast").siblings("a.meldungButtonD").find("img").attr('src', 'img/meldungButtonPlus.png');
				});
			}

			function onGeoError(error) {

					var d = new Date();

					var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '';
			}

		});

		jQuery(".mBreak").on('click', function () {
			m_key = 'm_' + localStorage.getItem("fe_user");

							localStorage.removeItem(m_key);
							localStorage.removeItem("pics");
							jQuery("input[type=text], textarea").val("");
							jQuery("input[type=checkbox]").attr('checked', false);
							jQuery("input[type=radio]").attr('checked', false);
							jQuery("#eingetroffeneStunde").val("");
							jQuery("#eingetroffeneMinute").val("");
							jQuery("#beendetStunde").val("");
							jQuery("#beendetMinute").val("");

			jQuery(".meForm").slideUp("fast").siblings("a.meldungButtonD").find("img").attr('src', 'img/meldungButtonPlus.png');

		});

		jQuery(".showMeForm").on('click', function () {
			if (jQuery(this).next(".meForm").hasClass("active")){
					jQuery(this).next(".meForm").slideUp("fast").removeClass("active");
					jQuery(this).find("img.mbPlus").attr('src', 'img/meldungButtonPlus.png');
			}else {
					jQuery(".meForm").slideUp("fast").removeClass("active");
					jQuery(".showMeForm").find("img.mbPlus").attr('src', 'img/meldungButtonPlus.png')
					jQuery(this).next(".meForm").slideDown("fast").addClass("active");
					jQuery(this).find("img.mbPlus").attr('src', 'img/meldungButtonMinus.png');
			}
		});

});<commit_msg>Meldungen.js v1.2.5 - Fehler bei Meldung mit 3G-GEO<commit_after>jQuery(document).ready(function () {

    // set global Variables
    var mMeldung, mAddition, m_key;
    var mLostFound, mTrainNumber, mNumberPersons, mLift, mWheelchair, mEscort, mArrivalStation, mMaPhone, mLiftArrivelTime, mLiftEndedTime, mPoliceInfo, mHospitalInfo, mConcernSecurity;
    var mName, mAddress, mContact, mComment;
		var countGeoForMeldung = 0;
		var searchGeoDataForMeldung = false;

    if (localStorage.getItem("fe_user")) {
        // Set key for Meldung
        m_key = 'm_' + localStorage.getItem("fe_user");
    }

    function newMeldung(feUser,mString){

			//consoleLog('debug', "Create new Stoerungsmeldung / Start");

			var data, mDateTime, mPosition, mMeldung, url, request, jqxhr, uid, jmString, mPics, pData, mAddition, mComment;
			var m_key = 'm_' + localStorage.getItem("fe_user");

			mString = mString.replace(/\n/g,"\\n")
			jmString = JSON.parse(mString);

			mDateTime = jmString[0]["datetime"];
			mPosition = jmString[0]["position"];
			mMeldung = jmString[0].meldung;
			mPics = jmString[0].pics;
			mLostFound = jmString[0].lostfound;
                        mComment = jmString[0].comment;
			mTrainNumber = jmString[0].trainnumber;
			mNumberPersons = jmString[0].numberpersons;
			mLift = jmString[0].lift;
			mWheelchair = jmString[0].wheelchair;
			mEscort = jmString[0].escort;
			mArrivalStation = jmString[0].arrivalstation;
			mMaPhone = jmString[0].maphone;
			mLiftArrivelTime = jmString[0].liftarrivaltime;
			mLiftEndedTime = jmString[0].liftendedtime;
			mPoliceInfo = jmString[0].policeinfo;
			mHospitalInfo = jmString[0].hospitalinfo;
			mConcernSecurity = jmString[0].concernsecurity;
			mName = jmString[0].name;
			mAddress = jmString[0].address;
			mContact = jmString[0].contact;

			url = "http://active.mungos-services.at/index.php";

			data = {
					'id': 79,
					'no_cache': 1,
					'type': 97,
					'tx_mungosstoerung[action]': "create",
					'tx_mungosstoerung[feUser]': feUser,
					'tx_mungosstoerung[dateTime]': mDateTime,
					'tx_mungosstoerung[geoData]': mPosition,
					'tx_mungosstoerung[type]': mMeldung,
					'tx_mungosstoerung[images]': mPics,
					'tx_mungosstoerung[lostFound]': mLostFound,
					'tx_mungosstoerung[comment]': mComment,
					'tx_mungosstoerung[trainNumber]': mTrainNumber,
					'tx_mungosstoerung[numberPersons]': mNumberPersons,
					'tx_mungosstoerung[lift]': mLift,
					'tx_mungosstoerung[wheelchair]': mWheelchair,
					'tx_mungosstoerung[escort]': mEscort,
					'tx_mungosstoerung[arrivalStation]': mArrivalStation,
					'tx_mungosstoerung[maPhoneInfo]': mMaPhone,
					'tx_mungosstoerung[liftArrivelTime]': mLiftArrivelTime,
					'tx_mungosstoerung[liftEndedTime]': mLiftEndedTime,
					'tx_mungosstoerung[policeInfo]': mPoliceInfo,
					'tx_mungosstoerung[hospitalInfo]': mHospitalInfo,
					'tx_mungosstoerung[concernSecurity]': mConcernSecurity,
					'tx_mungosstoerung[name]': mName,
					'tx_mungosstoerung[address]': mAddress,
					'tx_mungosstoerung[contact]': mContact
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function(json) {
							//alert("Meldung erfolgreich");
							//consoleLog('debug', "Störungsmeldung gespeichert (uid:"+json.uid+")");
							//consoleLog('debug', JSON.stringify(data));
							localStorage.removeItem(m_key);
							localStorage.removeItem("pics");
							jQuery("input[type=text], textarea").val("");
							jQuery("input[type=checkbox]").attr('checked', false);
							jQuery("input[type=radio]").attr('checked', false);
							jQuery("#eingetroffeneStunde").val("");
							jQuery("#eingetroffeneMinute").val("");
							jQuery("#beendetStunde").val("");
							jQuery("#beendetMinute").val("");
					},
					error: function(xOptions, textStatus, error){
							//consoleLog('debug', "Störungsmeldung error");
							alert("Meldung fehlgeschlagen: " + textStatus + " " + error);
					}
			});

			return false;

    }

    jQuery(".saveMeldung").on('click', function () {

			if(jQuery(this).hasClass("meldung01")) {
					mMeldung = "Vandalismus";
			}else if(jQuery(this).hasClass("meldung02")) {
					mMeldung = "Lost & Found";
			}else if(jQuery(this).hasClass("meldung03")) {
					mMeldung = "Unangemeldete Ein-, Ausstieghilfe";
			}else if(jQuery(this).hasClass("meldung04")) {
					mMeldung = "Aufzugsbefreiung";
			}else if(jQuery(this).hasClass("meldung05")) {
					mMeldung = "Gewalt an Mitarbeiter";
			}else if(jQuery(this).hasClass("meldung06")) {
					mMeldung = "Einbruch / Diebstahl";
			}else if(jQuery(this).hasClass("meldung07")) {
					mMeldung = "Beschwerden / Anfragen";
			}else if(jQuery(this).hasClass("meldung08")) {
					mMeldung = "Randgruppen";
			}else if(jQuery(this).hasClass("meldung09")) {
					mMeldung = "Raucherstrafen";
			}else if(jQuery(this).hasClass("meldung10")) {
					mMeldung = "Verweise / Belehrung";
			}

			mLostFound = jQuery(".meRadio:checked").length > 0 ? jQuery(".meRadio:checked").val() : "";
			mTrainNumber = jQuery("#uEzn").val().length > 0 ? jQuery("#uEzn").val() : "";
			mNumberPersons = jQuery("#uEAz").val().length > 0 ? jQuery("#uEAz").val() : "";
			mArrivalStation = jQuery("#uEbh").val().length > 0 ? jQuery("#uEbh").val() : "";
			mLift = jQuery("#Hebelift").prop('checked') ? 1 : 0;
			mWheelchair = jQuery("#Bahnrollstuhl").prop('checked') ? 1 : 0;
			mEscort = jQuery("#Begleitung").prop('checked') ? 1 : 0;
			mMaPhone = jQuery("#maTel").prop('checked') ? 1 : 0;
			mLiftArrivelTime = jQuery("#eingetroffeneStunde").val().length > 0 && jQuery("#eingetroffeneMinute").val().length ?
					jQuery("#eingetroffeneStunde").val()+":"+jQuery("#eingetroffeneMinute").val() : "";
			mLiftEndedTime = jQuery("#beendetStunde").val().length > 0 && jQuery("#beendetMinute").val().length ?
					jQuery("#beendetStunde").val()+":"+jQuery("#beendetMinute").val() : "";
			mConcernSecurity = jQuery("#Konzernsicherheit").prop('checked') ? 1 : 0;
			mName = jQuery("#beschwerdeName").val().length > 0 ? jQuery("#beschwerdeName").val() : "";
			mAddress = jQuery("#beschwerdeAdresse").val().length > 0 ? jQuery("#beschwerdeAdresse").val() : "";
			mContact = jQuery("#beschwerdeKontakt").val().length > 0 ? jQuery("#beschwerdeKontakt").val() : "";
                        mComment = jQuery("#comment").val().length > 0 ? jQuery("#comment").val() : "";

			if(jQuery("#wachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#wachzimmer").val();
			}
			else if(jQuery("#gewaltWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#gewaltWachzimmer").val();
			}
			else if(jQuery("#gewaltWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#gewaltWachzimmer").val();
			}
			else if(jQuery("#einbruchWachzimmer").val().length > 0){
					mPoliceInfo = jQuery("#einbruchWachzimmer").val();
			}  else {
					mPoliceInfo = "";
			}

			if(jQuery("#gewaltKrankenhaus").val().length > 0){
					mHospitalInfo = jQuery("#gewaltKrankenhaus").val();
			/*}
			else if(jQuery("#einbruchKrankenhaus").val().length > 0){
					mHospitalInfo = jQuery("#einbruchKrankenhaus").val();*/
			}else {
					mHospitalInfo = "";
			}

			// opens the confirm dialog
			jQuery.mobile.changePage("#confirmDialog", {
					transition: "slidedown",
					changeHash: false
			});

			// writes the text of the current meldung in the confirm box
			jQuery(".confContent").find("h1").text("Möchten Sie die Meldung \""+mMeldung+"\" abschicken?");

    });

		// set Meldungsstring in Localstorage
		function saveLocalMeldung(position){

			var mDateTime, mString, position, mPos, mPics;

			d = new Date();
			m = d.getMonth() + 1;

			mDateTime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();
			mPos = position.coords.latitude + "," + position.coords.longitude;
			mPics = localStorage.getItem("pics");

			countGeoForMeldung = 0;
			searchGeoDataForMeldung = false;

			mString = '[{   "datetime" : "' + mDateTime
					+ '", "position" : "' + mPos
					+ '", "meldung" : "' + mMeldung
					+ '", "pics" : "' + mPics
					+ '", "lostfound" : "' + mLostFound
					+ '", "comment" : "' + mComment
					+ '", "trainnumber" : "' + mTrainNumber
					+ '", "numberpersons" : "' + mNumberPersons
					+ '", "lift" : "' + mLift
					+ '", "wheelchair" : "' + mWheelchair
					+ '", "escort" : "' + mEscort
					+ '", "arrivalstation" : "' + mArrivalStation
					+ '", "maphone" : "' + mMaPhone
					+ '", "liftarrivaltime" : "' + mLiftArrivelTime
					+ '", "liftendedtime" : "' + mLiftEndedTime
					+ '", "policeinfo" : "' + mPoliceInfo
					+ '", "hospitalinfo" : "' + mHospitalInfo
					+ '", "concernsecurity" : "' + mConcernSecurity
					+ '", "name" : "' + mName
					+ '", "address" : "' + mAddress
					+ '", "contact" : "' + mContact
					+ '" }]';

			localStorage.setItem(m_key, mString);

			saveMeldung();
		}

		function saveMeldung() {

			uploadFiles();

			// Set key for Meldung
			m_key = 'm_' + localStorage.getItem("fe_user");

			newMeldung(localStorage.getItem("fe_user"),localStorage.getItem(m_key));

			jQuery(".meForm").each(function(){
					jQuery(this).slideUp("fast").siblings("a.meldungButtonD").find("img").attr('src', 'img/meldungButtonPlus.png');
			});
		}

		function onGeoError(error) {
			countGeoForMeldung++;
			var d = new Date();
			var span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '';
			if (countGeoForMeldung <= 2) {
				getCurGeoDataForMeldung();
			}
		}

		function getCurGeoDataForMeldung() {
		// holt die aktuellen Geokoordinaten
			if (searchGeoDataForMeldung == false	) {
				searchGeoDataForMeldung = true;
				var options = {
					maximumAge: 5000, timeout: 60000, enableHighAccuracy: true
				};
				rWatchId = navigator.geolocation.getCurrentPosition(saveLocalMeldung, onGeoError, options);
			}
		}

    jQuery(".mConfirm").on('click',function () {
			getCurGeoDataForMeldung();

		});

		jQuery(".mBreak").on('click', function () {
			m_key = 'm_' + localStorage.getItem("fe_user");

							localStorage.removeItem(m_key);
							localStorage.removeItem("pics");
							jQuery("input[type=text], textarea").val("");
							jQuery("input[type=checkbox]").attr('checked', false);
							jQuery("input[type=radio]").attr('checked', false);
							jQuery("#eingetroffeneStunde").val("");
							jQuery("#eingetroffeneMinute").val("");
							jQuery("#beendetStunde").val("");
							jQuery("#beendetMinute").val("");

			jQuery(".meForm").slideUp("fast").siblings("a.meldungButtonD").find("img").attr('src', 'img/meldungButtonPlus.png');

		});

		jQuery(".showMeForm").on('click', function () {
			if (jQuery(this).next(".meForm").hasClass("active")){
					jQuery(this).next(".meForm").slideUp("fast").removeClass("active");
					jQuery(this).find("img.mbPlus").attr('src', 'img/meldungButtonPlus.png');
			}else {
					jQuery(".meForm").slideUp("fast").removeClass("active");
					jQuery(".showMeForm").find("img.mbPlus").attr('src', 'img/meldungButtonPlus.png')
					jQuery(this).next(".meForm").slideDown("fast").addClass("active");
					jQuery(this).find("img.mbPlus").attr('src', 'img/meldungButtonMinus.png');
			}
		});

});<|endoftext|>


<commit_before>'use strict';

var UTIL = require('util'),
    PATH = require('path'),
    Q = require('q'),
    _ = require('underscore'),
    QFS = require('q-fs'),

    BEM = require('..'),

    projectPath = PATH.resolve(__dirname, 'data/make/project'),
    referencePath = PATH.resolve(__dirname, 'data/make/reference-result'),
    buildPath = PATH.resolve(__dirname, '../test-make-temp');

/**
 * Mocha BDD interface.
 *
 * @name describe @function
 * @name it @function
 * @name before @function
 * @name after @function
 * @name beforeEach @function
 * @name afterEach @function
 */

describe('bem', function() {
    describe('make', function() {

        before(function(done){
            prepareProject()
                .done(done);
        });

        it('completes successfully', function(done) {
            this.timeout(0);

            BEM.api.make({root: buildPath, verbosity: 'error'})
                .then(done)
                .fail(done)
                .done();
        });

        it('creates proper artifacts', function(done) {
            return BEM.util.exec(
                    UTIL.format(
                        'find %s -type f -exec diff -q {} %s/{} \\; 2>&1',
                        '.',
                        PATH.relative(referencePath, buildPath)),
                    {cwd: referencePath},
                    true)
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('does not rebuild anything on next build with no changes made to the files', function(done) {
            this.timeout(0);

            collectTimestamps(buildPath)
                .then(function(timestamps) {
                    return BEM.api.make({root: buildPath, verbosity: 'error'})
                        .then(function() {
                            return collectTimestamps(buildPath);
                        })
                        .then(function(newTimestamps){
                            var mismatches = Object.keys(newTimestamps)
                                .filter(function(ts) {
                                    return newTimestamps[ts] !== timestamps[ts];
                                });

                            if (mismatches.length > 0) throw new Error('There are modified files:\n' + mismatches.join('\n'));

                            done();
                        });
                })
                .fail(done)
                .done();
        });

        it('rebuilds missing artifacts on consequent build', function(done) {
            this.timeout(0);

            Q.all(['pages/example/example.html',
             'pages/example/example.css',
             'pages/client/client.html',
             'pages/client/client.css'].map(function(file) {
                    return QFS.remove(PATH.join(buildPath, file));
                }))
                .then(function() {
                    return BEM.api.make({root: buildPath, verbosity: 'error'});
                })
                .then(function() {
                    return BEM.util.exec(
                            UTIL.format(
                                'find %s -type f -exec diff -q {} %s/{} \\; 2>&1',
                                '.',
                                PATH.relative(referencePath, buildPath)),
                            {cwd: referencePath},
                            true);
                })
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('clean removes build artifacts', function(done) {
            this.timeout(0);

            BEM.api.make({root: buildPath, verbosity: 'error', method: 'clean'})
                .then(function() {
                    return Q.all([
                        dirHasOnly(PATH.join(buildPath, 'pages/example'), ['example.bemjson.js']),
                        dirHasOnly(PATH.join(buildPath, 'pages/client'), ['client.bemjson.js'])
                    ])
                    .spread(function(example, client) {
                        if (!(example && client)) throw new Error('build artifacts exist');

                        done();
                    });
                })
                .fail(done)
                .done();
        });

        it('builds two targets', function(done) {
            this.timeout(0);

            prepareProject()
                .then(function(){
                    return BEM.api.make({
                        root: buildPath,
                        verbosity: 'error'
                        },
                        {
                            targets: ['pages/example/_example.css', 'pages/client/client.html']
                        });
                })
                .then(function(){
                    return Q.all([
                        dirHasOnly(
                            PATH.join(buildPath, 'pages/example'),
                            ['example.bemjson.js', '_example.css', 'example.bemdecl.js', 'example.css',
                             'example.deps.js']),
                        dirHasOnly(
                            PATH.join(buildPath, 'pages/client'),
                            ['client.bemjson.js', 'client.bemhtml.js', 'client.bemdecl.js',
                            'client.deps.js', 'client.html']),
                        dirHasOnly(
                            PATH.join(buildPath, '.bem/cache/pages/example'),
                            ['example.css.meta.js', 'example.deps.js.meta.js']
                        ),
                        dirHasOnly(
                            PATH.join(buildPath, '.bem/cache/pages/client'),
                            ['client.deps.js.meta.js', 'client.bemhtml.meta.js']
                        )
                    ])
                    .spread(function(example, client) {
                        if (!(example && client)) throw new Error('set of build artifacts differs from expected');
                    });
                })
                .then(function() {
                    return BEM.util.exec(
                            UTIL.format(
                                'diff -rq %s %s 2>&1 | grep -v ^O; true',
                                '.',
                                PATH.relative(referencePath, buildPath)),
                            {cwd: referencePath},
                            true);
                })
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('invalidates deps when bemdecl is modified', function(done) {
            this.timeout(0);

            return prepareProject()
                .then(function() {
                    BEM.api.make({root: buildPath, verbosity: 'error'})
                        .then(function() {
                            return BEM.util.exec(UTIL.format('cp %s %s',
                                PATH.resolve(__dirname, 'data/make/misc/changed.bemjson.js'),
                                PATH.resolve(buildPath, 'pages/example/example.bemjson.js')))

                                .then(function() {
                                    return BEM.api.make({root: buildPath, verbosity: 'error'},
                                        {
                                            targets: ['pages/example/example.deps.js']
                                        });
                                })
                                .then(function() {
                                    return Q.all([
                                            QFS.lastModified(PATH.join(buildPath, 'pages/example/example.bemjson.js')),
                                            QFS.lastModified(PATH.join(buildPath, 'pages/example/example.deps.js'))
                                        ])
                                        .spread(function(bemjson, deps) {
                                            if (deps >= bemjson) return;

                                            throw new Error('deps did not invalidate');
                                        });
                                });

                        })
                        .then(done)
                        .fail(done)
                        .done();

                });
        });

    });
});

function prepareProject() {
    return QFS.exists(buildPath)
        .then(function(exists) {
            return exists && BEM.util.exec(UTIL.format('rm -rf %s', buildPath));
        })
        .then(function() {
            return BEM.util.exec(UTIL.format('cp -r %s %s', projectPath, buildPath));
        });
}

function collectTimestamps(root) {
    var list = {};

    return QFS.listTree(root, function(path, stat) {
        return PATH.basename(path)[0] !== '.' &&
            Q.when(stat.isFile(), function(isFile) {
                if (isFile) {
                    return QFS.lastModified(path)
                        .then(function(modified) {
                            list[path] = modified;
                            return true;
                        });
                }

                return false;
            });
    })
    .then(function() {
        return list;
    });
}

function dirHasOnly(dir, files) {
    return BEM.util.getFilesAsync(dir)
        .then(function(dirFiles) {
            return dirFiles.length === files.length &&
                _.union(files, dirFiles).length === files.length;
        });
}
<commit_msg>tests: deps invalidation test uses assert to compare timestamps<commit_after>'use strict';

var assert = require('chai').assert,
    UTIL = require('util'),
    PATH = require('path'),
    Q = require('q'),
    _ = require('underscore'),
    QFS = require('q-fs'),

    BEM = require('..'),

    projectPath = PATH.resolve(__dirname, 'data/make/project'),
    referencePath = PATH.resolve(__dirname, 'data/make/reference-result'),
    buildPath = PATH.resolve(__dirname, '../test-make-temp');

/**
 * Mocha BDD interface.
 *
 * @name describe @function
 * @name it @function
 * @name before @function
 * @name after @function
 * @name beforeEach @function
 * @name afterEach @function
 */

describe('bem', function() {
    describe('make', function() {

        before(function(done){
            prepareProject()
                .done(done);
        });

        it('completes successfully', function(done) {
            this.timeout(0);

            BEM.api.make({root: buildPath, verbosity: 'error'})
                .then(done)
                .fail(done)
                .done();
        });

        it('creates proper artifacts', function(done) {
            return BEM.util.exec(
                    UTIL.format(
                        'find %s -type f -exec diff -q {} %s/{} \\; 2>&1',
                        '.',
                        PATH.relative(referencePath, buildPath)),
                    {cwd: referencePath},
                    true)
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('does not rebuild anything on next build with no changes made to the files', function(done) {
            this.timeout(0);

            collectTimestamps(buildPath)
                .then(function(timestamps) {
                    return BEM.api.make({root: buildPath, verbosity: 'error'})
                        .then(function() {
                            return collectTimestamps(buildPath);
                        })
                        .then(function(newTimestamps){
                            var mismatches = Object.keys(newTimestamps)
                                .filter(function(ts) {
                                    return newTimestamps[ts] !== timestamps[ts];
                                });

                            if (mismatches.length > 0) throw new Error('There are modified files:\n' + mismatches.join('\n'));

                            done();
                        });
                })
                .fail(done)
                .done();
        });

        it('rebuilds missing artifacts on consequent build', function(done) {
            this.timeout(0);

            Q.all(['pages/example/example.html',
             'pages/example/example.css',
             'pages/client/client.html',
             'pages/client/client.css'].map(function(file) {
                    return QFS.remove(PATH.join(buildPath, file));
                }))
                .then(function() {
                    return BEM.api.make({root: buildPath, verbosity: 'error'});
                })
                .then(function() {
                    return BEM.util.exec(
                            UTIL.format(
                                'find %s -type f -exec diff -q {} %s/{} \\; 2>&1',
                                '.',
                                PATH.relative(referencePath, buildPath)),
                            {cwd: referencePath},
                            true);
                })
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('clean removes build artifacts', function(done) {
            this.timeout(0);

            BEM.api.make({root: buildPath, verbosity: 'error', method: 'clean'})
                .then(function() {
                    return Q.all([
                        dirHasOnly(PATH.join(buildPath, 'pages/example'), ['example.bemjson.js']),
                        dirHasOnly(PATH.join(buildPath, 'pages/client'), ['client.bemjson.js'])
                    ])
                    .spread(function(example, client) {
                        if (!(example && client)) throw new Error('build artifacts exist');

                        done();
                    });
                })
                .fail(done)
                .done();
        });

        it('builds two targets', function(done) {
            this.timeout(0);

            prepareProject()
                .then(function(){
                    return BEM.api.make({
                        root: buildPath,
                        verbosity: 'error'
                        },
                        {
                            targets: ['pages/example/_example.css', 'pages/client/client.html']
                        });
                })
                .then(function(){
                    return Q.all([
                        dirHasOnly(
                            PATH.join(buildPath, 'pages/example'),
                            ['example.bemjson.js', '_example.css', 'example.bemdecl.js', 'example.css',
                             'example.deps.js']),
                        dirHasOnly(
                            PATH.join(buildPath, 'pages/client'),
                            ['client.bemjson.js', 'client.bemhtml.js', 'client.bemdecl.js',
                            'client.deps.js', 'client.html']),
                        dirHasOnly(
                            PATH.join(buildPath, '.bem/cache/pages/example'),
                            ['example.css.meta.js', 'example.deps.js.meta.js']
                        ),
                        dirHasOnly(
                            PATH.join(buildPath, '.bem/cache/pages/client'),
                            ['client.deps.js.meta.js', 'client.bemhtml.meta.js']
                        )
                    ])
                    .spread(function(example, client) {
                        if (!(example && client)) throw new Error('set of build artifacts differs from expected');
                    });
                })
                .then(function() {
                    return BEM.util.exec(
                            UTIL.format(
                                'diff -rq %s %s 2>&1 | grep -v ^O; true',
                                '.',
                                PATH.relative(referencePath, buildPath)),
                            {cwd: referencePath},
                            true);
                })
                .then(function(result) {
                    done(result && new Error(result));
                })
                .fail(done)
                .done();
        });

        it('invalidates deps when bemdecl is modified', function(done) {
            this.timeout(0);

            return prepareProject()
                .then(function() {
                    BEM.api.make({root: buildPath, verbosity: 'error'})
                        .then(function() {
                            return BEM.util.exec(UTIL.format('cp %s %s',
                                PATH.resolve(__dirname, 'data/make/misc/changed.bemjson.js'),
                                PATH.resolve(buildPath, 'pages/example/example.bemjson.js')))

                                .then(function() {
                                    return BEM.api.make({root: buildPath, verbosity: 'error'},
                                        {
                                            targets: ['pages/example/example.deps.js']
                                        });
                                })
                                .then(function() {
                                    return Q.all([
                                            QFS.lastModified(PATH.join(buildPath, 'pages/example/example.bemjson.js')),
                                            QFS.lastModified(PATH.join(buildPath, 'pages/example/example.deps.js'))
                                        ])
                                        .spread(function(bemjson, deps) {
                                            assert.operator(deps, '>=', bemjson);
                                        });
                                });

                        })
                        .then(done)
                        .fail(done)
                        .done();

                });
        });

    });
});

function prepareProject() {
    return QFS.exists(buildPath)
        .then(function(exists) {
            return exists && BEM.util.exec(UTIL.format('rm -rf %s', buildPath));
        })
        .then(function() {
            return BEM.util.exec(UTIL.format('cp -r %s %s', projectPath, buildPath));
        });
}

function collectTimestamps(root) {
    var list = {};

    return QFS.listTree(root, function(path, stat) {
        return PATH.basename(path)[0] !== '.' &&
            Q.when(stat.isFile(), function(isFile) {
                if (isFile) {
                    return QFS.lastModified(path)
                        .then(function(modified) {
                            list[path] = modified;
                            return true;
                        });
                }

                return false;
            });
    })
    .then(function() {
        return list;
    });
}

function dirHasOnly(dir, files) {
    return BEM.util.getFilesAsync(dir)
        .then(function(dirFiles) {
            return dirFiles.length === files.length &&
                _.union(files, dirFiles).length === files.length;
        });
}
<|endoftext|>


<commit_before>import { transform } from 'babel-core';

import pluginZent from '../src';

function compile(code, options) {
  return transform(code, {
    babelrc: false,
    presets: [
      [
        'env',
        {
          targets: {
            node: 4
          }
        }
      ]
    ],

    plugins: [
      [
        pluginZent,
        Object.assign(
          { moduleMappingFile: '../../zent/lib/module-mapping.json' },
          options
        )
      ]
    ]
  }).code;
}

describe('babel-plugin-zent', () => {
  it('throws on side-effect only import', () => {
    expect(() => compile("import 'zent'")).toThrowError(
      /Side-effect only import is allowed in zent/
    );
  });

  it('throws on namespace import', () => {
    expect(() => compile("import * as Zent from 'zent'")).toThrowError(
      /Namespace import is not allowd in zent/
    );
  });

  it('throws on default import', () => {
    const defaultImportErrorRegexp = /There is no default export in zent/;
    expect(() => compile("import Zent from 'zent'")).toThrowError(
      defaultImportErrorRegexp
    );
    expect(() => compile("import Zent, { Button } from 'zent'")).toThrowError(
      defaultImportErrorRegexp
    );
  });

  it('throws on require', () => {
    expect(() => compile("require('zent')")).toThrowError(
      /require\('zent'\) is not allowed/
    );
  });

  it('transforms component imports', () => {
    // eslint-disable-next-line
    const rules = require('../../zent/lib/module-mapping.json');

    Object.keys(rules).forEach(component => {
      const src = `import { ${component} } from 'zent'`;
      expect(
        compile(src).indexOf(`require('${rules[component].js}')`)
      ).not.toBe(-1);
    });

    // rename imports
    expect(
      compile("import { Button as Foobar } from 'zent'; console.log(Foobar)")
    ).toMatch(/console.log(.+\.default)/);
  });

  it('can add css imports', () => {
    expect(
      compile("import { Button } from 'zent'", { automaticStyleImport: true })
    ).toMatch(/require\('zent\/css\/button.css'\)/);

    expect(
      compile("import { Portal } from 'zent'", { automaticStyleImport: true })
    ).not.toMatch(/zent\/css\//);

    expect(
      compile("import { Pop, Button } from 'zent'", {
        automaticStyleImport: true
      })
    ).toMatch(
      /require\('zent\/css\/pop.css'\)[\s\S]*require\('zent\/css\/button.css'\)/im
    );
  });

  it('can add postcss imports', () => {
    expect(
      compile("import { Button } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).toMatch(/require\('zent\/assets\/button.pcss'\)/);

    expect(
      compile("import { Portal } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).not.toMatch(/zent\/assets\//);

    expect(
      compile("import { Pop, Button } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).toMatch(
      /require\('zent\/assets\/pop.pcss'\)[\s\S]*require\('zent\/assets\/button.pcss'\)/im
    );
  });
});
<commit_msg>Fix tests<commit_after>import { transform } from 'babel-core';

import pluginZent from '../src';

function compile(code, options) {
  return transform(code, {
    babelrc: false,
    presets: [
      [
        'env',
        {
          targets: {
            node: 4
          }
        }
      ]
    ],

    plugins: [
      [
        pluginZent,
        Object.assign(
          { moduleMappingFile: '../../zent/lib/module-mapping.json' },
          options
        )
      ]
    ]
  }).code;
}

describe('babel-plugin-zent', () => {
  it('throws on side-effect only import', () => {
    expect(() => compile("import 'zent'")).toThrowError(
      /Side-effect only import is allowed in zent/
    );
  });

  it('throws on namespace import', () => {
    expect(() => compile("import * as Zent from 'zent'")).toThrowError(
      /Namespace import is not allowd in zent/
    );
  });

  it('throws on default import', () => {
    const defaultImportErrorRegexp = /There is no default export in zent/;
    expect(() => compile("import Zent from 'zent'")).toThrowError(
      defaultImportErrorRegexp
    );
    expect(() => compile("import Zent, { Button } from 'zent'")).toThrowError(
      defaultImportErrorRegexp
    );
  });

  it('throws on require', () => {
    expect(() => compile("require('zent')")).toThrowError(
      /require\('zent'\) is not allowed/
    );
  });

  it('transforms component imports', () => {
    // eslint-disable-next-line
    const rules = require('../../zent/lib/module-mapping.json');

    Object.keys(rules).forEach(component => {
      const src = `import { ${component} } from 'zent'`;
      expect(
        compile(src).indexOf(`require('${rules[component].js}')`)
      ).not.toBe(-1);
    });

    // rename imports
    expect(
      compile("import { Button as Foobar } from 'zent'; console.log(Foobar)")
    ).toMatch(/console.log(.+\.default)/);
  });

  it('can add css imports', () => {
    expect(
      compile("import { Button } from 'zent'", { automaticStyleImport: true })
    ).toMatch(/require\('zent\/css\/button.css'\)/);

    expect(
      compile("import { Portal } from 'zent'", { automaticStyleImport: true })
    ).toMatch(/require\('zent\/css\/base.css'\)/);

    expect(
      compile("import { Pop, Button } from 'zent'", {
        automaticStyleImport: true
      })
    ).toMatch(
      /require\('zent\/css\/button.css'\)[\s\S]*require\('zent\/css\/pop.css'\)/im
    );
  });

  it('can add postcss imports', () => {
    expect(
      compile("import { Button } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).toMatch(/require\('zent\/assets\/button.pcss'\)/);

    expect(
      compile("import { Portal } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).toMatch(/require\('zent\/assets\/base.pcss'\)/);

    expect(
      compile("import { Pop, Button } from 'zent'", {
        automaticStyleImport: true,
        useRawStyle: true
      })
    ).toMatch(
      /require\('zent\/assets\/button.pcss'\)[\s\S]*require\('zent\/assets\/pop.pcss'\)/im
    );
  });
});
<|endoftext|>


<commit_before>/*global config*/
import { fromJS } from 'immutable';
import {has, findWhere} from 'underscore';
import humanizeDuration from 'humanize-duration';
import $ from 'jquery';
import Q from 'q';
import Resource from './ResourceProvider';

class RepoBuildPollingProvider {

  constructor(params) {
    this.shouldPoll = true;
    this.params = params;
    this.repositoryId = undefined;

    this.repoBuildPromise = new Resource({url: `${config.apiRoot}/branches/builds/${params.repoBuildId}/modules`});
    this.repoIdPromise = new Resource({ url: `${config.apiRoot}/branches/state`}).get();
  }

  _findRepositoryId(builds) {
    const repoBuild = findWhere(builds.map((build) => build.gitInfo), {
      host: this.params.host,
      organization: this.params.org,
      repository: this.params.repo,
      branch: this.params.branch
    });

    this.repositoryId = repoBuild ? repoBuild.repositoryId : null;
  }

  poll(cb) {
    if (!this.shouldPoll) {
      return;
    }

    // load module builds from repoBuildId
    let promises = [this.repoBuildPromise.get()];

    // On first fetch, find repositoryId based on params so we can load the starred state
    if (!this.repositoryId) {
      promises.push(this.repoIdPromise);
    }

    Q.spread(promises, (moduleBuilds, allBuilds) => {

      if (allBuilds) {
        this._findRepositoryId(allBuilds);
      }

      cb(false, {
        moduleBuilds: fromJS(moduleBuilds),
        repositoryId: this.repositoryId
      });

      setTimeout(() => {
        this.poll.call(this, cb);
      }, config.buildsRefresh);

    })
    .fail((xhr) => {
      cb(xhr, null);
    });

  }

  disconnect() {
    this.shouldPoll = false;
  }

}

export default RepoBuildPollingProvider;
<commit_msg>don't poll repo build if we are in a terminal state<commit_after>/*global config*/
import { fromJS } from 'immutable';
import {has, findWhere, some, contains} from 'underscore';
import humanizeDuration from 'humanize-duration';
import $ from 'jquery';
import Q from 'q';
import Resource from './ResourceProvider';
import ActiveBuildStates from '../constants/ActiveBuildStates';

class RepoBuildPollingProvider {

  constructor(params) {
    this.shouldPoll = true;
    this.params = params;
    this.repositoryId = undefined;

    this.repoBuildPromise = new Resource({url: `${config.apiRoot}/branches/builds/${params.repoBuildId}/modules`});
    this.repoIdPromise = new Resource({ url: `${config.apiRoot}/branches/state`}).get();
  }

  _findRepositoryId(builds) {
    const repoBuild = findWhere(builds.map((build) => build.gitInfo), {
      host: this.params.host,
      organization: this.params.org,
      repository: this.params.repo,
      branch: this.params.branch
    });

    this.repositoryId = repoBuild ? repoBuild.repositoryId : null;
  }

  poll(cb) {
    if (!this.shouldPoll) {
      return;
    }

    // load module builds from repoBuildId
    let promises = [this.repoBuildPromise.get()];

    // On first fetch, find repositoryId based on params so we can load the starred state
    if (!this.repositoryId) {
      promises.push(this.repoIdPromise);
    }

    Q.spread(promises, (moduleBuilds, allBuilds) => {

      if (allBuilds) {
        this._findRepositoryId(allBuilds);
      }

      cb(false, {
        moduleBuilds: fromJS(moduleBuilds),
        repositoryId: this.repositoryId
      });

      // check if we need to keep polling
      const moduleBuildStates = moduleBuilds.map((build) => build.state)

      const shouldPoll = some(moduleBuildStates, (state) => {
        return contains(ActiveBuildStates, state);
      });

      if (!shouldPoll) {
        return;
      }

      setTimeout(() => {
        this.poll.call(this, cb);
      }, config.buildsRefresh);

    })
    .fail((xhr) => {
      cb(xhr, null);
    });

  }

  disconnect() {
    this.shouldPoll = false;
  }

}

export default RepoBuildPollingProvider;
<|endoftext|>


<commit_before>var knownWords = {
	"text" : ["&0", 1],

	// algebra, calc, geom
	"neg" : ["-", 0],
	"pow" : ["%0", 1],
	"sub" : ["%0", 1],
	"div" : ["/", 0],
	"dot" : ["⋅", 0],
	"cross" : ["×", 0],
	"perp" : ["⊥", 0],
	"norm" : ["|%0|", 1],
	"parallel" : ["∥", 0],
	"vec" : ["&0⃗", 1],
	"hat" : ["&0̂", 1], // there is an invisible character in here to make the combining mark
	"der" : ["d", 0],
	"frac" : ["%0%1", 2],
	"eqnum" : ["%0", 1],
	"sqrt" : ["√%0", 1],
	"myinf" : ["¤", 0],
	"indexed" : ["%2%0%1", 3],
	"paren2" : ["(%0)", 1],
	"bracket2" : ["[%0]", 1],
	"half" : ["½", 0],

	// functions
	"sin" : ["sin(%0)", 1],
	"sin2" : ["sin2(%0)", 1],
	"cos" : ["cos(%0)", 1],
	"cos2" : ["cos2(%0)", 1],
	"tan" : ["tan(%0)", 1],
	"tan2" : ["tan2(%0)", 1],
	"real" : ["real(%0)", 1],
	"im" : ["im(%0)", 1],

	// matrices
	"mat31" : ["

%0

%1

%2

", 3],

	// comparisons
	"ge" : ["≥", 0],
	"le" : ["≤", 0],
	"ne" : ["≠", 0],
	"prop" : ["∝", 0],
	"abouteq" : ["≈", 0],

	// logic/sets
	"implies" : ["→", 0],
	"and" : ["∧", 0],
	"or" : ["∨", 0],
	"not" : ["¬", 0],
	"union" : ["∪", 0],
	"intersection" : ["∩", 0],
	"empty" : ["∅", 0],
	"entails" : ["⊦", 0],
	"forall" : ["∀", 0],
	"exists" : ["∃", 0],
	"naturals" : ["ℕ", 0],
	"reals" : ["ℜ", 0],
	"complexes" : ["ℂ", 0],
	"subset" : ["⊂", 0],
	"superset" : ["⊃", 0],
	"isin" : ["∈", 0],

	// calculus
	"part" : ["∂", 0],
	"nabla" : ["∇", 0],
	"wedge" : ["∧", 0],
	"int" : ["∫ %0 d%1", 2],
	"int1" : ["∫%0 %1 d%2", 3],
	"int2" : ["∫%1%0 %2 d%3", 4],

	// quantum
	"hbar" : ["ħ", 0],
	"bra" : ["⟨%0|", 1],
	"ket" : ["|%0⟩", 1],
	"braket" : ["⟨%0 | %1⟩", 2],
	"dagger" : ["†", 0],

	// greek symbols
	"alpha" : ["α", 0],
	"beta" : ["β", 0],
	"gamma" : ["γ", 0],
	"delta" : ["δ", 0],
	"epsilon" : ["ε", 0],
	"zeta" : ["ζ", 0],
	"eta" : ["η", 0],
	"theta" : ["θ", 0],
	"iota" : ["ι", 0],
	"kappa" : ["κ", 0],
	"lambda" : ["λ", 0],
	"mu" : ["μ", 0],
	"nu" : ["ν", 0],
	"xi" : ["ξ", 0],
	"omicron" : ["ο", 0],
	"pi" : ["π", 0],
	"rho" : ["ρ", 0],
	"sigma" : ["σ", 0],
	"tau" : ["τ", 0],
	"upsilon" : ["υ", 0],
	"phi" : ["φ", 0],
	"chi" : ["χ", 0],
	"psi" : ["ψ", 0],
	"omega" : ["ω", 0],
	"Alpha" : ["Α", 0],
	"Beta" : ["Β", 0],
	"Gamma" : ["Γ", 0],
	"Delta" : ["Δ", 0],
	"Epsilon" : ["Ε", 0],
	"Zeta" : ["Ζ", 0],
	"Eta" : ["Η", 0],
	"Theta" : ["Θ", 0],
	"Iota" : ["Ι", 0],
	"Kappa" : ["Κ", 0],
	"Lambda" : ["Λ", 0],
	"Mu" : ["Μ", 0],
	"Nu" : ["Ν", 0],
	"Xi" : ["Ξ", 0],
	"Omicron" : ["Ο", 0],
	"Pi" : ["Π", 0],
	"Rho" : ["Ρ", 0],
	"Sigma" : ["Σ", 0],
	"Tau" : ["Τ", 0],
	"Upsilon" : ["Υ", 0],
	"Phi" : ["Φ", 0],
	"Chi" : ["Χ", 0],
	"Psi" : ["Ψ", 0],
	"Omega" : ["Ω", 0],
	"AlphaOp" : ["Α", 0],
	"BetaOp" : ["Β", 0],
	"GammaOp" : ["Γ", 0],
	"DeltaOp" : ["Δ", 0],
	"EpsilonOp" : ["Ε", 0],
	"ZetaOp" : ["Ζ", 0],
	"EtaOp" : ["Η", 0],
	"ThetaOp" : ["Θ", 0],
	"IotaOp" : ["Ι", 0],
	"KappaOp" : ["Κ", 0],
	"LambdaOp" : ["Λ", 0],
	"MuOp" : ["Μ", 0],
	"NuOp" : ["Ν", 0],
	"XiOp" : ["Ξ", 0],
	"OmicronOp" : ["Ο", 0],
	"PiOp" : ["Π", 0],
	"RhoOp" : ["Ρ", 0],
	"SigmaOp" : ["Σ", 0],
	"TauOp" : ["Τ", 0],
	"UpsilonOp" : ["Υ", 0],
	"PhiOp" : ["Φ", 0],
	"ChiOp" : ["Χ", 0],
	"PsiOp" : ["Ψ", 0],
	"OmegaOp" : ["Ω", 0]
}

function passWhiteSpace(content, i) {
	while(i < content.length) {
		var c = content[i];
		if(c != " " && c != "\t" && c != "\n" && c != "\r") {
			break;
		}
		i++;
	}
	return [i];
}

function getWord(content, i) {
	var word = "";
	while(i < content.length) {
		var code = content[i].charCodeAt(0);
		if(97 <= code && code <= 122) {} // a-z
		else if(65 <= code && code <= 90) {} // A-Z
		else if(48 <= code && code <= 57) {} // 0-9
		else {
			break;
		}
		word += content[i];
		i++;
	}
	return [word, i];
}

function getParam(content, i) {
	var nesting = 0;
	var param = "";
	if(content[i] != "{") {
		return ["", i];
	}
	while(i < content.length) {
		var c = content[i];
		if(c == "{") {
			nesting++;
		}
		else if(c == "}") {
			nesting--;
			if(nesting == 0) {
				i++;
				break;
			}
		}
		if((c != "{") || (c == "{" && nesting > 1)) {
			param += c;
		}
		i++;
	}
	return [param, i];
}

function parseParams(content, i, replacement, numParams) {
	for(var j = 0; j < numParams; j++) {
		var param = "";
		if(numParams == 1 && content[i] != "{") {
			[param, i] = getWord(content, i);
		}
		else {
			[param, i] = getParam(content, i);
		}
		var paramContent = parseMathContent(param);
		replacement = replacement.replace("%" + j, paramContent);
		replacement = replacement.replace("&" + j, param);
	}
	return [replacement, i];
}

function parseMathContent(content) {
	var i = 0;
	var word;
	var newContent = "";
	while(i < content.length) {
		var c = content[i];
		if(c == "/") {
			i++;

			// Get the word.
			[word, i] = getWord(content, i);
			if(word.length == 0) {
				newContent += c;
				continue;
			}
			if(word.length == 1) {
				i -= 1;
				continue;
			}
			else if(!(word in knownWords)) {
				newContent += "/" + word;
				i += word.length;
				continue;
			}

			// Parse the params.
			var [replacement, numParams] = knownWords[word];
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, replacement, numParams);
			newContent += parsedParams;
		}
		else if(c == "{") {
			i++;
			while(i < content.length) {
				var c = content[i];
				if (c == "}") {
					break;
				}
				newContent += c;
				i++;
			}
		}
		else if("0123456789()[]+-*=,.|".includes(c)) {
			newContent += c;
			i++;
		}
		else if(c == "^") {
			i++;
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, "%0", 1);
			newContent += parsedParams;
		}
		else if(c == "_") {
			i++;
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, "%0", 1);
			newContent += parsedParams;
		}
		else if(c == " ") {
			newContent += c;
			i++;
		}
		else {
			newContent += "" + c + "";
			i++;
		}
	}
	return newContent;
}<commit_msg>More math adjustments<commit_after>var knownWords = {
	"text" : ["&0", 1],

	// algebra, calc, geom
	"neg" : ["-", 0],
	"pow" : ["%0", 1],
	"sub" : ["%0", 1],
	"div" : ["/", 0],
	"dot" : ["⋅", 0],
	"cross" : ["×", 0],
	"perp" : ["⊥", 0],
	"norm" : ["|%0|", 1],
	"parallel" : ["∥", 0],
	"vec" : ["&0⃗", 1],
	"hat" : ["&0̂", 1], // there is an invisible character in here to make the combining mark
	"der" : ["d", 0],
	"frac" : ["%0%1", 2],
	"eqnum" : ["%0", 1],
	"sqrt" : ["√%0", 1],
	"inf" : ["∞", 0],
	"myinf" : ["¤", 0],
	"indexed" : ["%2%0%1", 3],
	"paren2" : ["(%0)", 1],
	"bracket2" : ["[%0]", 1],
	"half" : ["½", 0],

	// functions
	"if" : ["if", 0],
	"else" : ["else", 0],
	"sin" : ["sin(%0)", 1],
	"sin2" : ["sin2(%0)", 1],
	"cos" : ["cos(%0)", 1],
	"cos2" : ["cos2(%0)", 1],
	"tan" : ["tan(%0)", 1],
	"tan2" : ["tan2(%0)", 1],
	"real" : ["real(%0)", 1],
	"im" : ["im(%0)", 1],

	// matrices
	"mat31" : ["

%0

%1

%2

", 3],
	"mat41" : ["

%0

%1

%2

%3

", 4],
	"mat44" : ["

%0	%1	%2	%3

%4	%5	%6	%7

%8	%9	%10	%11

%12	%13	%14	%15

", 16],

	// comparisons
	"ge" : ["≥", 0],
	"le" : ["≤", 0],
	"ne" : ["≠", 0],
	"prop" : ["∝", 0],
	"abouteq" : ["≈", 0],

	// logic/sets
	"implies" : ["→", 0],
	"and" : ["∧", 0],
	"or" : ["∨", 0],
	"not" : ["¬", 0],
	"union" : ["∪", 0],
	"intersection" : ["∩", 0],
	"empty" : ["∅", 0],
	"entails" : ["⊦", 0],
	"forall" : ["∀", 0],
	"exists" : ["∃", 0],
	"naturals" : ["ℕ", 0],
	"reals" : ["ℜ", 0],
	"complexes" : ["ℂ", 0],
	"subset" : ["⊂", 0],
	"superset" : ["⊃", 0],
	"isin" : ["∈", 0],

	// calculus
	"part" : ["∂", 0],
	"nabla" : ["∇", 0],
	"wedge" : ["∧", 0],
	"int" : ["∫ %0 d%1", 2],
	"int1" : ["∫%0 %1 d%2", 3],
	"int2" : ["∫%1%0 %2 d%3", 4],

	// quantum
	"hbar" : ["ħ", 0],
	"bra" : ["⟨%0|", 1],
	"ket" : ["|%0⟩", 1],
	"braket" : ["⟨%0 | %1⟩", 2],
	"dagger" : ["†", 0],

	// greek symbols
	"alpha" : ["α", 0],
	"beta" : ["β", 0],
	"gamma" : ["γ", 0],
	"delta" : ["δ", 0],
	"epsilon" : ["ε", 0],
	"zeta" : ["ζ", 0],
	"eta" : ["η", 0],
	"theta" : ["θ", 0],
	"iota" : ["ι", 0],
	"kappa" : ["κ", 0],
	"lambda" : ["λ", 0],
	"mu" : ["μ", 0],
	"nu" : ["ν", 0],
	"xi" : ["ξ", 0],
	"omicron" : ["ο", 0],
	"pi" : ["π", 0],
	"rho" : ["ρ", 0],
	"sigma" : ["σ", 0],
	"tau" : ["τ", 0],
	"upsilon" : ["υ", 0],
	"phi" : ["φ", 0],
	"chi" : ["χ", 0],
	"psi" : ["ψ", 0],
	"omega" : ["ω", 0],
	"Alpha" : ["Α", 0],
	"Beta" : ["Β", 0],
	"Gamma" : ["Γ", 0],
	"Delta" : ["Δ", 0],
	"Epsilon" : ["Ε", 0],
	"Zeta" : ["Ζ", 0],
	"Eta" : ["Η", 0],
	"Theta" : ["Θ", 0],
	"Iota" : ["Ι", 0],
	"Kappa" : ["Κ", 0],
	"Lambda" : ["Λ", 0],
	"Mu" : ["Μ", 0],
	"Nu" : ["Ν", 0],
	"Xi" : ["Ξ", 0],
	"Omicron" : ["Ο", 0],
	"Pi" : ["Π", 0],
	"Rho" : ["Ρ", 0],
	"Sigma" : ["Σ", 0],
	"Tau" : ["Τ", 0],
	"Upsilon" : ["Υ", 0],
	"Phi" : ["Φ", 0],
	"Chi" : ["Χ", 0],
	"Psi" : ["Ψ", 0],
	"Omega" : ["Ω", 0],
	"AlphaOp" : ["Α", 0],
	"BetaOp" : ["Β", 0],
	"GammaOp" : ["Γ", 0],
	"DeltaOp" : ["Δ", 0],
	"EpsilonOp" : ["Ε", 0],
	"ZetaOp" : ["Ζ", 0],
	"EtaOp" : ["Η", 0],
	"ThetaOp" : ["Θ", 0],
	"IotaOp" : ["Ι", 0],
	"KappaOp" : ["Κ", 0],
	"LambdaOp" : ["Λ", 0],
	"MuOp" : ["Μ", 0],
	"NuOp" : ["Ν", 0],
	"XiOp" : ["Ξ", 0],
	"OmicronOp" : ["Ο", 0],
	"PiOp" : ["Π", 0],
	"RhoOp" : ["Ρ", 0],
	"SigmaOp" : ["Σ", 0],
	"TauOp" : ["Τ", 0],
	"UpsilonOp" : ["Υ", 0],
	"PhiOp" : ["Φ", 0],
	"ChiOp" : ["Χ", 0],
	"PsiOp" : ["Ψ", 0],
	"OmegaOp" : ["Ω", 0]
}

function passWhiteSpace(content, i) {
	while(i < content.length) {
		var c = content[i];
		if(c != " " && c != "\t" && c != "\n" && c != "\r") {
			break;
		}
		i++;
	}
	return [i];
}

function getWord(content, i) {
	var word = "";
	while(i < content.length) {
		var code = content[i].charCodeAt(0);
		if(97 <= code && code <= 122) {} // a-z
		else if(65 <= code && code <= 90) {} // A-Z
		else if(48 <= code && code <= 57) {} // 0-9
		else {
			break;
		}
		word += content[i];
		i++;
	}
	return [word, i];
}

function getParam(content, i) {
	var nesting = 0;
	var param = "";
	if(content[i] != "{") {
		return ["", i];
	}
	while(i < content.length) {
		var c = content[i];
		if(c == "{") {
			nesting++;
		}
		else if(c == "}") {
			nesting--;
			if(nesting == 0) {
				i++;
				break;
			}
		}
		if((c != "{") || (c == "{" && nesting > 1)) {
			param += c;
		}
		i++;
	}
	return [param, i];
}

function parseParams(content, i, replacement, numParams) {
	for(var j = 0; j < numParams; j++) {
		var param = "";
		if(numParams == 1 && content[i] != "{") {
			[param, i] = getWord(content, i);
		}
		else {
			[param, i] = getParam(content, i);
		}
		var paramContent = parseMathContent(param);
		replacement = replacement.replace("%" + j, paramContent);
		replacement = replacement.replace("&" + j, param);
	}
	return [replacement, i];
}

function parseMathContent(content) {
	var i = 0;
	var word;
	var newContent = "";
	while(i < content.length) {
		var c = content[i];
		if(c == "/") {
			i++;

			// Get the word.
			[word, i] = getWord(content, i);
			if(word.length == 0) {
				newContent += c;
				continue;
			}
			if(word.length == 1) {
				i -= 1;
				continue;
			}
			else if(!(word in knownWords)) {
				newContent += "/" + word;
				i += word.length;
				continue;
			}

			// Parse the params.
			var [replacement, numParams] = knownWords[word];
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, replacement, numParams);
			newContent += parsedParams;
		}
		else if(c == "{") {
			i++;
			while(i < content.length) {
				var c = content[i];
				if (c == "}") {
					break;
				}
				newContent += c;
				i++;
			}
		}
		else if("0123456789()[]+-*=,.|".includes(c)) {
			newContent += c;
			i++;
		}
		else if(c == "^") {
			i++;
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, "%0", 1);
			newContent += parsedParams;
		}
		else if(c == "_") {
			i++;
			var parsedParams = "";
			[parsedParams, i] = parseParams(content, i, "%0", 1);
			newContent += parsedParams;
		}
		else if(c == " ") {
			newContent += c;
			i++;
		}
		else {
			newContent += "" + c + "";
			i++;
		}
	}
	return newContent;
}<|endoftext|>


<commit_before>util = require('util');

function SkipListNode(value) {
    // Setting the value and initializing the direction pointers
    this.v = value;
    this.l = null;
    this.r = null;
    this.u = null;
    this.d = null;
}

function SkipList(coinflipper) {
    // Left Sentinel & Right Sentinels
    this.ls = new SkipListNode(null);
    this.rs = new SkipListNode(null);

    // Setting up their pointers
    this.ls.r = this.rs;
    this.rs.l = this.ls;

    // Is this the left sentinel?
    this.ls.lm = true;

    // Is this the right sentinel?
    this.rs.rm = true;

    // Setting the top-left pointer
    this.root = this.ls;

    // For those who are conscious about their PRNGs! :D
    this.coinflipper = coinflipper || function () { return Math.round(Math.random()); };

    // The max height we have TODO Check if this is needed
    this.h = 0;
}

SkipList.prototype =  {
    _promote_sentinels: function () {
        new_ls = new SkipListNode(null);
        new_rs = new SkipListNode(null);

        // They are sentinels
        new_ls.lm = true;
        new_rs.rm = true;

        // Set the pointers
        new_ls.d = this.ls;
        new_rs.d = this.rs;
        this.ls.u = new_ls;
        this.rs.u = new_rs;
        new_ls.r = new_rs;
        new_rs.l = new_ls;

        // Update the sentinels
        this.ls = new_ls;
        this.rs = new_rs;

        // Set the new root
        this.root = this.ls;

        // Increase the total height
        this.h = this.h + 1;
    },

    insert_before: function (before, value) {
        // Are we messing with the left sentinel?
        if (before.lm) {
            return;
        }

        // Get the neighbors
        l = before.l;
        r = before;

        // Create a new node
        new_node = new SkipListNode(value);
        n = new_node;

        // Set the pointers of its left and right neighbors
        l.r = n;
        r.l = n;
        n.l = l;
        n.r = r;

        current_height = 0;
        old_node = n;

        while (this.coinflipper()) {
            //console.log("Heads");

            current_height = current_height + 1;
            if (current_height > this.h) {
                //console.log("Height increased");
                this._promote_sentinels();
                //console.log(util.format('%d', this.h));
            }

            // Move left till you have an up pointer
            while (l.u === null) {
                l = l.l;
            }
            // Now actually move up
            l = l.u;

            // Move right till you have an up pointer
            while (r.u === null) {
                r = r.r;
            }
            // Now actually move up
            r = r.u;

            if (current_height > 0) {
                n = new SkipListNode(value);
            }

            // Setting up pointers with the neighbors
            l.r = n;
            r.l = n;
            n.l = l;
            n.r = r;

            // Chaining up with the old node
            old_node.u = n;
            n.d = old_node;

            // For chaining up with the node at the next level
            old_node = n;
        }

        return new_node;
    },

    delete_node: function(n) {
        // We love our sentinels!
        if (n.lm === true || n.rm === true) {
            return;
        }

        // Only nodes at the ground level can be deleted (for sanity sake)
        if (n.d != null) {
            return;
        }

        while (1) {
            // Have we met Ted? :P
            n.l.r = n.r;
            n.r.l = n.l;
            if (n.u != null) {
                upper_node = n.u;
                // TODO Verify if this deletes
                delete n;
                n = upper_node;
            }
            else {
                delete n;
                break;
            }
        }
    },

    _print_by_level: function () {
        level = this.root;
        while (level) {
            //console.log(util.format('%d', level.lm));
            level_node = level.r;
            //console.log(util.format('%d', level_node.rm));
            process.stdout.write('L ');
            while (level_node.rm != true) {
                process.stdout.write(util.format('%d ', level_node.v));
                level_node = level_node.r;
            }
            process.stdout.write('R');
            process.stdout.write('\n');
            level = level.d;
        }
        process.stdout.write('\n');
    }
};

exports.SkipListNode = SkipListNode;
exports.SkipList = SkipList;

s = new SkipList();
a = s.insert_before(s.rs, 5);
b = s.insert_before(a, 3);
c = s.insert_before(a, 4);
s._print_by_level();
s.delete_node(b);
s._print_by_level();
<commit_msg>Wrote a finder function for sorted skip lists<commit_after>util = require('util');

function sorted_list_finder_function(node, value) {
    if (node.v === value) {
        if (node.d === null) {
            return "Found";
        }
        return "Down";
    }

    if (node.v > value) {
       return "Down";
    }

    if (node.v < value) {
        if(node.r === null || node.r.rm === true || node.r.v > value) {
            return "Down";
        }
        return "Right";
    }
}

function SkipListNode(value) {
    // Setting the value and initializing the direction pointers
    this.v = value;
    this.l = null;
    this.r = null;
    this.u = null;
    this.d = null;
}

function SkipList(coinflipper) {
    // Left Sentinel & Right Sentinels
    this.ls = new SkipListNode(null);
    this.rs = new SkipListNode(null);

    // Setting up their pointers
    this.ls.r = this.rs;
    this.rs.l = this.ls;

    // Is this the left sentinel?
    this.ls.lm = true;

    // Is this the right sentinel?
    this.rs.rm = true;

    // Setting the top-left pointer
    this.root = this.ls;

    // For those who are conscious about their PRNGs! :D
    this.coinflipper = coinflipper || function () { return Math.round(Math.random()); };

    // The max height we have TODO Check if this is needed
    this.h = 0;
}

SkipList.prototype =  {
    _promote_sentinels: function () {
        new_ls = new SkipListNode(null);
        new_rs = new SkipListNode(null);

        // They are sentinels
        new_ls.lm = true;
        new_rs.rm = true;

        // Set the pointers
        new_ls.d = this.ls;
        new_rs.d = this.rs;
        this.ls.u = new_ls;
        this.rs.u = new_rs;
        new_ls.r = new_rs;
        new_rs.l = new_ls;

        // Update the sentinels
        this.ls = new_ls;
        this.rs = new_rs;

        // Set the new root
        this.root = this.ls;

        // Increase the total height
        this.h = this.h + 1;
    },

    insert_before: function (before, value) {
        // Are we messing with the left sentinel?
        if (before.lm) {
            return;
        }

        // Get the neighbors
        l = before.l;
        r = before;

        // Create a new node
        new_node = new SkipListNode(value);
        n = new_node;

        // Set the pointers of its left and right neighbors
        l.r = n;
        r.l = n;
        n.l = l;
        n.r = r;

        current_height = 0;
        old_node = n;

        while (this.coinflipper()) {
            //console.log("Heads");

            current_height = current_height + 1;
            if (current_height > this.h) {
                //console.log("Height increased");
                this._promote_sentinels();
                //console.log(util.format('%d', this.h));
            }

            // Move left till you have an up pointer
            while (l.u === null) {
                l = l.l;
            }
            // Now actually move up
            l = l.u;

            // Move right till you have an up pointer
            while (r.u === null) {
                r = r.r;
            }
            // Now actually move up
            r = r.u;

            if (current_height > 0) {
                n = new SkipListNode(value);
            }

            // Setting up pointers with the neighbors
            l.r = n;
            r.l = n;
            n.l = l;
            n.r = r;

            // Chaining up with the old node
            old_node.u = n;
            n.d = old_node;

            // For chaining up with the node at the next level
            old_node = n;
        }

        return new_node;
    },

    delete_node: function(n) {
        // We love our sentinels!
        if (n.lm === true || n.rm === true) {
            return;
        }

        // Only nodes at the ground level can be deleted (for sanity sake)
        if (n.d !== null) {
            return;
        }

        while (1) {
            // Have we met Ted? :P
            n.l.r = n.r;
            n.r.l = n.l;
            if (n.u !== null) {
                upper_node = n.u;
                // TODO Verify if GC is needed.
                n = upper_node;
            }
            else {
                delete n;
                break;
            }
        }
    },

    find: function () {
    },

    _print_by_level: function () {
        level = this.root;
        while (level) {
            //console.log(util.format('%d', level.lm));
            level_node = level.r;
            //console.log(util.format('%d', level_node.rm));
            process.stdout.write('L ');
            while (level_node.rm !== true) {
                process.stdout.write(util.format('%d ', level_node.v));
                level_node = level_node.r;
            }
            process.stdout.write('R');
            process.stdout.write('\n');
            level = level.d;
        }
        process.stdout.write('\n');
    }
};

exports.SkipListNode = SkipListNode;
exports.SkipList = SkipList;

s = new SkipList();
a = s.insert_before(s.rs, 5);
b = s.insert_before(a, 3);
c = s.insert_before(a, 4);
s._print_by_level();
s.delete_node(b);
s._print_by_level();
<|endoftext|>


<commit_before>/**
*			jBility
*	jBility is a free set of accessibility functions that uses JQuery.
*	By: Uriel Cairê Balan Calvi
*	Available on: https://github.com/urielcaire/jBility
*/
jQuery(document).ready(function( $ ){
	/*===================================================================
	*	jBility uses JsCookie to manager cookies.
	*	JsCookie is available on: https://github.com/urielcaire/jscookie
	*====================================================================*/
	function createCookie(name, value, days){
		var expires = "";
		if(days){
			var time = new Date();
			time.setTime(time.getTime()+(days*24*60*60*1000));
		}
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function getCookie(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return "";
	}

	function deleteCookie(name) {
		createCookie(name,"",-1);
	}

	function checkCookie(name){
		var check = getCookie(name);
		if(check != "")
			return true;
		return false;
	}

	/*======================================
	*		jBility functions
	*======================================*/
	function addConstrast(){
        console.log('addConstrast');
        $('*').addClass('pagina-acessivel');
        $('.acess-container').addClass('f-transparent');
        $('#botao').addClass('f-transparent');
        $('#acess-icons').addClass('f-transparent');
        $('.acess-icon').addClass('f-transparent');
        $('img').addClass('f-transparent');
    }

    function removeConstrast(){
        console.log('removeConstrast');
        $('*').removeClass('pagina-acessivel');
        $('.acess-container').removeClass('f-transparent');
        $('#botao').removeClass('f-transparent');
        $('#acess-icons').removeClass('f-transparent');
        $('.acess-icon').removeClass('f-transparent');
        $('img').removeClass('f-transparent');
    }

   	if(checkCookie('ccontrast')){
    	addConstrast();
   	}

   	$('#contrast').click(function(){
    	var ck = checkCookie('ccontrast');
        if(ck){
        	deleteCookie('ccontrast');
            removeConstrast();
        }else{
            createCookie('ccontrast', 'cookieContrast');
            addConstrast();
        }
   	});

	var $cElements = $("body").find("*");
	var fonts = [];

	function getFontSize() {
		for (var i = 0; i < $cElements.length; i++) {
	    	fonts.push(parseFloat($cElements.eq(i).css('font-size')));
	  	}
	}
	getFontSize();
	$("#increaseFont").on('click', function() {
		for (var i = 0; i < $cElements.length; i++) {
	    	++fonts[i];
	    	$cElements.eq(i).css('font-size', fonts[i]);
	  	}
	});

	$("#decreaseFont").on('click', function() {
		for (var i = 0; i < $cElements.length; i++) {
			--fonts[i];
			$cElements.eq(i).css('font-size', fonts[i]);
		}
	});

	$('#jbbutton').click(function(){
        $('#acess-icons').toggle(150);
    });

});<commit_msg>Add class 'f-transparent' to 'jbbutton' when contrast is active<commit_after>/**
*			jBility
*	jBility is a free set of accessibility functions that uses JQuery.
*	By: Uriel Cairê Balan Calvi
*	Available on: https://github.com/urielcaire/jBility
*/
jQuery(document).ready(function( $ ){
	/*===================================================================
	*	jBility uses JsCookie to manager cookies.
	*	JsCookie is available on: https://github.com/urielcaire/jscookie
	*====================================================================*/
	function createCookie(name, value, days){
		var expires = "";
		if(days){
			var time = new Date();
			time.setTime(time.getTime()+(days*24*60*60*1000));
		}
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function getCookie(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return "";
	}

	function deleteCookie(name) {
		createCookie(name,"",-1);
	}

	function checkCookie(name){
		var check = getCookie(name);
		if(check != "")
			return true;
		return false;
	}

	/*======================================
	*		jBility functions
	*======================================*/
	function addConstrast(){
        console.log('addConstrast');
        $('*').addClass('pagina-acessivel');
        $('.acess-container').addClass('f-transparent');
        $('#botao').addClass('f-transparent');
        $('#acess-icons').addClass('f-transparent');
        $('.acess-icon').addClass('f-transparent');
        $('img').addClass('f-transparent');
        $('#jbbutton').addClass('f-transparent');
    }

    function removeConstrast(){
        console.log('removeConstrast');
        $('*').removeClass('pagina-acessivel');
        $('.acess-container').removeClass('f-transparent');
        $('#botao').removeClass('f-transparent');
        $('#acess-icons').removeClass('f-transparent');
        $('.acess-icon').removeClass('f-transparent');
        $('img').removeClass('f-transparent');
        $('#jbbutton').removeClass('f-transparent');
    }

   	if(checkCookie('ccontrast')){
    	addConstrast();
   	}

   	$('#contrast').click(function(){
    	var ck = checkCookie('ccontrast');
        if(ck){
        	deleteCookie('ccontrast');
            removeConstrast();
        }else{
            createCookie('ccontrast', 'cookieContrast');
            addConstrast();
        }
   	});

	var $cElements = $("body").find("*");
	var fonts = [];

	function getFontSize() {
		for (var i = 0; i < $cElements.length; i++) {
	    	fonts.push(parseFloat($cElements.eq(i).css('font-size')));
	  	}
	}
	getFontSize();
	$("#increaseFont").on('click', function() {
		for (var i = 0; i < $cElements.length; i++) {
	    	++fonts[i];
	    	$cElements.eq(i).css('font-size', fonts[i]);
	  	}
	});

	$("#decreaseFont").on('click', function() {
		for (var i = 0; i < $cElements.length; i++) {
			--fonts[i];
			$cElements.eq(i).css('font-size', fonts[i]);
		}
	});

	$('#jbbutton').click(function(){
        $('#acess-icons').toggle(150);
    });

});<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var sounds   = require("./sounds");
var identify = require("./identify");

/**
* Builds chords derived from the input scale, using superimposed thirds.
* @param scale  A scale object that will be used as reference.
* @param depth
* @param option 0: returns a Harmony object, 1: returns an array of strings.
*/
var harmonize = function(scale, depth, option){
    if (depth < 1 || typeof depth !== "number")
        throw new Error("depth must be a number > 0");
    if (option < 0 || option > 1)
        throw new Error("option must be number 0 or 1");
    var mode = option || 0;
    if (mode === 0) return harmonize0(scale, depth, [], scale.getNotes(), scale.getSize());
    if (mode === 1) return harmonize1(scale, depth, [], scale.getNotes(), scale.getSize());
};

// Helper for harmonize(), returns a Harmony object.
var harmonize0 = function(scale, depth, chordArray, notes, scaleSize){
    for (var i = 0; i < scaleSize; i++){                 // For every note in the scale:
        var aNoteArray = [];                             // Build a note array (a chord):
        for(var j = 0, k = 0; j < depth; j++, k += 2)    // With that note plus a number -
            aNoteArray[j] = notes[(k + i) % scaleSize];  // of superimposed thirds (depth).
        chordArray.push(new sounds.Chord(aNoteArray));   // Add that chord to chordList.
    }
    return new sounds.Harmony(chordArray);               // Return an Harmony object
};

// Helper for harmonize(), returns an array of strings with the names of the chords, if applicable.
// !!! can be more efficient, it doesn't need to call harmonize0 or deal with objects.
var harmonize1 = function(scale, depth, chordArray, notes, scaleSize){
    var chords      = harmonize0(scale, depth, chordArray, notes, scaleSize).getChords();
    var chlength    = chords.length;
    var returnArray = [];
    for (var i = 0; i < chlength; i++)
        returnArray.push(identify.chord(chords[i])[0]);
    return returnArray;
};

// Node exports:
exports.harmonize = harmonize;<commit_msg>jslint pimpin<commit_after>/** @module harmony */
/*jslint node: true */
"use strict";

var sounds   = require("./sounds");
var identify = require("./identify");

// Helper for harmonize(), returns a Harmony object.
var harmonize0 = function (depth, chordArray, notes, scaleSize) {
    var i, j, k,
        aNoteArray;
    for (i = 0; i < scaleSize; i += 1) {                 // For every note in the scale:
        aNoteArray = [];                                 // Build a note array (a chord):
        for (j = 0, k = 0; j < depth; j += 1, k += 2) {  // With that note plus a number -
            aNoteArray[j] = notes[(k + i) % scaleSize];  // of superimposed thirds (depth).
        }
        chordArray.push(new sounds.Chord(aNoteArray));   // Add that chord to chordList.
    }
    return new sounds.Harmony(chordArray);               // Return an Harmony object
};

// Helper for harmonize(), returns an array of strings with the names of the chords, if applicable.
// !!! can be more efficient, it doesn't need to call harmonize0 or deal with objects.
var harmonize1 = function (depth, chordArray, notes, scaleSize) {
    var i,
        chords      = harmonize0(depth, chordArray, notes, scaleSize).getChords(),
        chlength    = chords.length,
        returnArray = [];
    for (i = 0; i < chlength; i += 1) {
        returnArray.push(identify.chord(chords[i])[0]);
    }
    return returnArray;
};

/**
* Builds chords derived from the input scale, using superimposed thirds.
* @param scale  A scale object that will be used as reference.
* @param depth
* @param option 0: returns a Harmony object, 1: returns an array of strings.
*/
var harmonize = function (scale, depth, option) {
    if (depth < 1 || typeof depth !== "number") {
        throw new Error("depth must be a number > 0");
    }
    if (option < 0 || option > 1) {
        throw new Error("option must be number 0 or 1");
    }
    var mode = option || 0;
    if (mode === 0) {
        return harmonize0(depth, [], scale.getNotes(), scale.getSize());
    }
    if (mode === 1) {
        return harmonize1(depth, [], scale.getNotes(), scale.getSize());
    }
};

// Node exports:
exports.harmonize = harmonize;<|endoftext|>