<commit_before>$(function(){
	window.viewport = {
		width  : $(window).width(),
		height : $(window).height()
	};
	window.pageNavigatorTouch = {
		start		: {},
		end			: {},
		startTimer	: null
	};
	//$("#pagenavigator").on("touchstart", touchDownHandle)
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.addEventListener("touchstart",touchDownHandle,false);
	$("body").on("scroll",function(e){
		e.preventDefault();
	});
	//document.addEventListener("touchstart",touchDownHandle,false);
	window.transitionEnd = whichTransitionEvent(document.getElementById('pagenavigator'));
	loadCards();
	//disable_scroll()
	setScroll();
});
function setScroll(){
$(document).bind("touchmove",function(e){
   e.preventDefault();
 });

$('.scrollable').bind("touchmove",function(e){
  if ($('.scrollable')[0].scrollHeight > $('.scrollable')[0].clientHeight) {
    e.stopPropagation();
  } else {
    e.preventDefault();
  }
});
}

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
 // e.returnValue = false;
}

function theMouseWheel(e) {
  preventDefault(e);
}

function disable_scroll() {
  if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', theMouseWheel, false);
	 // window.addEventListener('touchstart', theMouseWheel, false);
	  window.addEventListener('touchmove', theMouseWheel, false);
	 // window.addEventListener('touchend', theMouseWheel, false);
	  window.addEventListener('mousemove', theMouseWheel, false);
  }
  window.onmousewheel = document.onmousewheel = theMouseWheel;
}

function whichTransitionEvent(el){
    var t;
    var transitions = {
      'transition':'transitionend',
      'OTransition':'oTransitionEnd',
      'MozTransition':'transitionend',
      'WebkitTransition':'webkitTransitionEnd'
    }

    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

function touchDownHandle(event){
	event.stopPropagation();
	event.preventDefault();

	//document.removeEventListener("touchstart",touchDownHandle);

	//console.log("touch start :" + event.touches[0].pageX);
	pageNavigatorTouch.startTimer = Date.now();
	$("#pagenavigator").removeClass("slide-animation");
	//pageNavigatorTouch.start = event.originalEvent.touches[0];
	//$("#pagenavigator").on("touchmove", touchMoveHandle);
	//$("#pagenavigator").one("touchend", touchUpHandle);

	pageNavigatorTouch.start = jQuery.extend({}, event.touches[0]);
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.addEventListener("touchmove",touchMoveHandle,false);
	pagenavigator.addEventListener("touchend",touchUpHandle,false);
};

function touchMoveHandle(event){
	event.stopPropagation();
	event.preventDefault();
	//console.log("touch move");
	//pageNavigatorTouch.end = event.originalEvent.touches[0];
	pageNavigatorTouch.end = event.touches[0];
	movePercent = ((pageNavigatorTouch.end.pageX - pageNavigatorTouch.start.pageX) / viewport.width) * 100;
	//console.log("distance : " +pageNavigatorTouch.start.pageX);
	////console.log("=> movePercent : ", movePercent);
	$("#pagenavigator").css({
		"-webkit-transform": "translate3d("+ (movePercent/3) +"% ,0 ,0)",
		"transform": "translate3d("+ (movePercent/3) +"% ,0 ,0)"
		//left : -100 + movePercent +"%"
	});
};

function touchUpHandle(event){
	event.stopPropagation();
	event.preventDefault();
	//console.log("touch end")
	//$("#pagenavigator").off("touchmove", touchMoveHandle);
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.removeEventListener("touchmove",touchMoveHandle);
	pagenavigator.removeEventListener("touchend",touchUpHandle);

	var distance = (pageNavigatorTouch.end.pageX - pageNavigatorTouch.start.pageX);
	//console.log("distance : " + distance);
	movePercent = (distance / viewport.width) * 100;
	//swipe or slide
	isSwipe = ((Date.now() - pageNavigatorTouch.startTimer) < 250) && (Math.abs(distance) > 75) ? true : false;
	////console.log("=> movePercent : ", movePercent);
	$("#pagenavigator").addClass("slide-animation");
	if (Math.abs(movePercent) < 40){
		if(isSwipe){
			preformPageSlide(movePercent);
		}else{
			pageSlideReset();
		}
	} else {
		preformPageSlide(movePercent);
	};

	//$("#pagenavigator").off("touchmove", touchMoveHandle);
	//document.addEventListener("touchstart",touchDownHandle,false);
};

function preformPageSlide(movePercent){
	//console.log("pageSlide");
	if(movePercent < 0){
		pageSlideLeft();
	} else {
		pageSlideRight();
	}
};

function pageSlideReset(){
	$("#pagenavigator").css({
		"transform": "translate3d(0,0,0)",
		"-webkit-transform": "translate3d(0,0,0)",
		"-moz-transform": "translate3d(0,0,0)",
		"-ms-transform": "translate3d(0,0,0)",
		"-o-transform": "translate3d(0,0,0)"
	});
}
function pageSlideLeft(){
	////console.log('slideLeft');
/*	(document.getElementById('pagenavigator')).addEventListener(window.transitionEnd, function(event){
		////console.log("addeventlistener transition ended");
		var nextCard = $("#nextCardHolder div").data("cardInfo");
		showCard(nextCard);
	}, false);*/

	$("#pagenavigator").css({
		"transform": "translate3d(-33.3%,0,0)",
		"-webkit-transform": "translate3d(-33.3%,0,0)",
		"-moz-transform": "translate3d(-33.3%,0,0)",
		"-ms-transform": "translate3d(-33.3%,0,0)",
		"-o-transform": "translate3d(-33.3%,0,0)"
	}).one(window.transitionEnd, function(event){
		event.stopPropagation();
		event.preventDefault();
		//console.log("transition ended");
		var nextCard = $("#nextCardHolder div").data("cardInfo");
		showCard(nextCard);
	});
	//console.log('slideLeft: end');
}
function pageSlideRight(){
	//console.log('slideRight');
	$("#pagenavigator").one(window.transitionEnd, function(event){
		event.stopPropagation();
		event.preventDefault();
		//console.log("transition ended");
		var previousCard = $("#previousCardHolder div").data("cardInfo");
		showCard(previousCard);
	}).css({
		"transform": "translate3d(33.3%,0,0)",
		"-webkit-transform": "translate3d(33.3%,0,0)",
		"-moz-transform": "translate3d(33.3%,0,0)",
		"-ms-transform": "translate3d(33.3%,0,0)",
		"-o-transform": "translate3d(33.3%,0,0)"
	});
}
function loadCards(){
	$.getJSON("data/data.json",function(data){
		//console.log("success loading data")
		try{
			//console.log(data.kaarten.length + "cards loaded");
			cards = data.kaarten;
			//setupNavigation();
			processCardData();
		} catch(err){
			//console.error(err);
		}
		//app.setupNavigation();
	})
	.fail(function() {
		console.error( "error loading data" );
	})
}

function showCard(cardInfo){
	//console.log("showCard");
	var mainCardIndex		= cards.indexOf(cardInfo),
		nextCardIndex 		= mainCardIndex+1 > cards.length ? -1 : mainCardIndex+1,
		previousCardIndex 	= mainCardIndex-1;

	$("#pagenavigator").removeClass("slide-animation"); //disable animation
	////console.log("showCards : ", previousIndex, mainIndex, nextIndex);
	$("#menu .pure-menu-selected").removeClass("pure-menu-selected");

	$('[href="#'+cardInfo.id+'"]').parent().addClass("pure-menu-selected");

	switch (cardInfo){
		case $("#nextCardHolder").data("cardInfo"):		//next card is selected
				$("#preloader").append($("#previous div"));	//store in carddeck
				$("#previousCardHolder").append($("#mainCardHolder div"));
				$("#mainCardHolder").append($("#nextCardHolder div"));
				pageSlideReset();
				$("#nextCardHolder").append($("#"+cards[nextCardIndex].id));
			break;
		case $("#previousCardHolder").data("cardInfo"):	// previous card is selected
				$("#preloader").append($("#nextCardHolder div"));	//store in carddeck
				$("#nextCardHolder").append($("#mainCardHolder div"));
				$("#mainCardHolder").append($("#previousCardHolder div"));
				pageSlideReset();
				$("#previousCardHolder").append($("#"+cards[nextCardIndex].id));
			break;
		default:							// no card selected
				$("#preloader").append($("#nextCardHolder div, #mainCardHolder div, #previousCardHolder div"));	//store in carddeck
				$("#mainCardHolder").append($("#"+cards[mainCardIndex].id));
				pageSlideReset();
				try{
					$("#previousCardHolder").append($("#"+cards[previousCardIndex].id));
				} catch(err) {
				}
				try{
					$("#nextCardHolder").append($("#"+cards[nextCardIndex].id));
				} catch(err) {
				}

			break;
	}

}

function processCardData(){
	//console.log('processCardData')
	var prevCardId = "", nextCardId = "";
	$.each(cards, function(index, value){
		if(index != cards.length-1){
			nextCardId = cards[index+1].naam;
		} else {
			nextCardId = "";
		}
		//addCardPage(value, {prev : prevCardId, next : nextCardId});
		addCardlinkToNavigation(value);
		prevCardId = value.naam;
	});
	//setTimeout( function(){$.mobile.changePage( "#"+cards[0].naam );}, 2500);
	showCard(cards[0]);
};
function addCardlinkToNavigation(card){
	//console.log('addCardlinkToNavigation')

	$( "
"+card.titel+"
" ).appendTo( "#cardsnavigation ul" ).on("click", loadCard);
	$("
").appendTo("#preloader");
	$("#"+card.id).data("cardInfo",card);

};

function loadCard(event){
	event.preventDefault();
	event.stopPropagation();
	//console.log('click', event);
	showCard($($(event.target).attr('href')).data("cardInfo"));
}

<commit_msg>alpha 1<commit_after>$(function(){
	window.viewport = {
		width  : $(window).width(),
		height : $(window).height()
	};
	window.pageNavigatorTouch = {
		start		: {},
		end			: {},
		startTimer	: null
	};
	//$("#pagenavigator").on("touchstart", touchDownHandle)
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.addEventListener("touchstart",touchDownHandle,false);
	$("body").on("scroll",function(e){
		e.preventDefault();
	});
	//document.addEventListener("touchstart",touchDownHandle,false);
	window.transitionEnd = whichTransitionEvent(document.getElementById('pagenavigator'));
	loadCards();
	//disable_scroll()
	setScroll();
});
function setScroll(){
$(document).bind("touchmove, mousemove",function(e){
   e.preventDefault();
 });

$('.scrollable').bind("touchmove, mousemove",function(e){
  if ($('.scrollable')[0].scrollHeight > $('.scrollable')[0].clientHeight) {
    e.stopPropagation();
  } else {
    e.preventDefault();
  }
});
}

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
 // e.returnValue = false;
}

function theMouseWheel(e) {
  preventDefault(e);
}

function disable_scroll() {
  if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', theMouseWheel, false);
	 // window.addEventListener('touchstart', theMouseWheel, false);
	  window.addEventListener('touchmove', theMouseWheel, false);
	 // window.addEventListener('touchend', theMouseWheel, false);
	  window.addEventListener('mousemove', theMouseWheel, false);
  }
  window.onmousewheel = document.onmousewheel = theMouseWheel;
}

function whichTransitionEvent(el){
    var t;
    var transitions = {
      'transition':'transitionend',
      'OTransition':'oTransitionEnd',
      'MozTransition':'transitionend',
      'WebkitTransition':'webkitTransitionEnd'
    }

    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

function touchDownHandle(event){
	event.stopPropagation();
	event.preventDefault();

	//document.removeEventListener("touchstart",touchDownHandle);

	//console.log("touch start :" + event.touches[0].pageX);
	pageNavigatorTouch.startTimer = Date.now();
	$("#pagenavigator").removeClass("slide-animation");
	//pageNavigatorTouch.start = event.originalEvent.touches[0];
	//$("#pagenavigator").on("touchmove", touchMoveHandle);
	//$("#pagenavigator").one("touchend", touchUpHandle);

	pageNavigatorTouch.start = jQuery.extend({}, event.touches[0]);
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.addEventListener("touchmove",touchMoveHandle,false);
	pagenavigator.addEventListener("touchend",touchUpHandle,false);
};

function touchMoveHandle(event){
	event.stopPropagation();
	event.preventDefault();
	//console.log("touch move");
	//pageNavigatorTouch.end = event.originalEvent.touches[0];
	pageNavigatorTouch.end = event.touches[0];
	movePercent = ((pageNavigatorTouch.end.pageX - pageNavigatorTouch.start.pageX) / viewport.width) * 100;
	//console.log("distance : " +pageNavigatorTouch.start.pageX);
	////console.log("=> movePercent : ", movePercent);
	$("#pagenavigator").css({
		"-webkit-transform": "translate3d("+ (movePercent/3) +"% ,0 ,0)",
		"transform": "translate3d("+ (movePercent/3) +"% ,0 ,0)"
		//left : -100 + movePercent +"%"
	});
};

function touchUpHandle(event){
	event.stopPropagation();
	event.preventDefault();
	//console.log("touch end")
	//$("#pagenavigator").off("touchmove", touchMoveHandle);
	var pagenavigator = document.getElementById("pagenavigator");
	pagenavigator.removeEventListener("touchmove",touchMoveHandle);
	pagenavigator.removeEventListener("touchend",touchUpHandle);

	var distance = (pageNavigatorTouch.end.pageX - pageNavigatorTouch.start.pageX);
	//console.log("distance : " + distance);
	movePercent = (distance / viewport.width) * 100;
	//swipe or slide
	isSwipe = ((Date.now() - pageNavigatorTouch.startTimer) < 250) && (Math.abs(distance) > 75) ? true : false;
	////console.log("=> movePercent : ", movePercent);
	$("#pagenavigator").addClass("slide-animation");
	if (Math.abs(movePercent) < 40){
		if(isSwipe){
			preformPageSlide(movePercent);
		}else{
			pageSlideReset();
		}
	} else {
		preformPageSlide(movePercent);
	};

	//$("#pagenavigator").off("touchmove", touchMoveHandle);
	//document.addEventListener("touchstart",touchDownHandle,false);
};

function preformPageSlide(movePercent){
	//console.log("pageSlide");
	if(movePercent < 0){
		pageSlideLeft();
	} else {
		pageSlideRight();
	}
};

function pageSlideReset(){
	$("#pagenavigator").css({
		"transform": "translate3d(0,0,0)",
		"-webkit-transform": "translate3d(0,0,0)",
		"-moz-transform": "translate3d(0,0,0)",
		"-ms-transform": "translate3d(0,0,0)",
		"-o-transform": "translate3d(0,0,0)"
	});
}
function pageSlideLeft(){
	////console.log('slideLeft');
/*	(document.getElementById('pagenavigator')).addEventListener(window.transitionEnd, function(event){
		////console.log("addeventlistener transition ended");
		var nextCard = $("#nextCardHolder div").data("cardInfo");
		showCard(nextCard);
	}, false);*/

	$("#pagenavigator").css({
		"transform": "translate3d(-33.3%,0,0)",
		"-webkit-transform": "translate3d(-33.3%,0,0)",
		"-moz-transform": "translate3d(-33.3%,0,0)",
		"-ms-transform": "translate3d(-33.3%,0,0)",
		"-o-transform": "translate3d(-33.3%,0,0)"
	}).one(window.transitionEnd, function(event){
		event.stopPropagation();
		event.preventDefault();
		//console.log("transition ended");
		var nextCard = $("#nextCardHolder div").data("cardInfo");
		showCard(nextCard);
	});
	//console.log('slideLeft: end');
}
function pageSlideRight(){
	//console.log('slideRight');
	$("#pagenavigator").one(window.transitionEnd, function(event){
		event.stopPropagation();
		event.preventDefault();
		//console.log("transition ended");
		var previousCard = $("#previousCardHolder div").data("cardInfo");
		showCard(previousCard);
	}).css({
		"transform": "translate3d(33.3%,0,0)",
		"-webkit-transform": "translate3d(33.3%,0,0)",
		"-moz-transform": "translate3d(33.3%,0,0)",
		"-ms-transform": "translate3d(33.3%,0,0)",
		"-o-transform": "translate3d(33.3%,0,0)"
	});
}
function loadCards(){
	$.getJSON("data/data.json",function(data){
		//console.log("success loading data")
		try{
			//console.log(data.kaarten.length + "cards loaded");
			cards = data.kaarten;
			//setupNavigation();
			processCardData();
		} catch(err){
			//console.error(err);
		}
		//app.setupNavigation();
	})
	.fail(function() {
		console.error( "error loading data" );
	})
}

function showCard(cardInfo){
	//console.log("showCard");
	var mainCardIndex		= cards.indexOf(cardInfo),
		nextCardIndex 		= mainCardIndex+1 > cards.length ? -1 : mainCardIndex+1,
		previousCardIndex 	= mainCardIndex-1;

	$("#pagenavigator").removeClass("slide-animation"); //disable animation
	////console.log("showCards : ", previousIndex, mainIndex, nextIndex);
	$("#menu .pure-menu-selected").removeClass("pure-menu-selected");

	$('[href="#'+cardInfo.id+'"]').parent().addClass("pure-menu-selected");

	switch (cardInfo){
		case $("#nextCardHolder").data("cardInfo"):		//next card is selected
				$("#preloader").append($("#previous div"));	//store in carddeck
				$("#previousCardHolder").append($("#mainCardHolder div"));
				$("#mainCardHolder").append($("#nextCardHolder div"));
				pageSlideReset();
				$("#nextCardHolder").append($("#"+cards[nextCardIndex].id));
			break;
		case $("#previousCardHolder").data("cardInfo"):	// previous card is selected
				$("#preloader").append($("#nextCardHolder div"));	//store in carddeck
				$("#nextCardHolder").append($("#mainCardHolder div"));
				$("#mainCardHolder").append($("#previousCardHolder div"));
				pageSlideReset();
				$("#previousCardHolder").append($("#"+cards[nextCardIndex].id));
			break;
		default:							// no card selected
				$("#preloader").append($("#nextCardHolder div, #mainCardHolder div, #previousCardHolder div"));	//store in carddeck
				$("#mainCardHolder").append($("#"+cards[mainCardIndex].id));
				pageSlideReset();
				try{
					$("#previousCardHolder").append($("#"+cards[previousCardIndex].id));
				} catch(err) {
				}
				try{
					$("#nextCardHolder").append($("#"+cards[nextCardIndex].id));
				} catch(err) {
				}

			break;
	}

}

function processCardData(){
	//console.log('processCardData')
	var prevCardId = "", nextCardId = "";
	$.each(cards, function(index, value){
		if(index != cards.length-1){
			nextCardId = cards[index+1].naam;
		} else {
			nextCardId = "";
		}
		//addCardPage(value, {prev : prevCardId, next : nextCardId});
		addCardlinkToNavigation(value);
		prevCardId = value.naam;
	});
	//setTimeout( function(){$.mobile.changePage( "#"+cards[0].naam );}, 2500);
	showCard(cards[0]);
};
function addCardlinkToNavigation(card){
	//console.log('addCardlinkToNavigation')

	$( "
"+card.titel+"
" ).appendTo( "#cardsnavigation ul" ).on("click", loadCard);
	$("
").appendTo("#preloader");
	$("#"+card.id).data("cardInfo",card);

};

function loadCard(event){
	event.preventDefault();
	event.stopPropagation();
	//console.log('click', event);
	showCard($($(event.target).attr('href')).data("cardInfo"));
}

<|endoftext|>


<commit_before>osm.validators = {

  sources: [{
    "name": "Адресный и роутинговый валидатор Zkir",
    "url": "http://osm.alno.name/validators/zkir?minlat={minlat}&minlon={minlon}&maxlat={maxlat}&maxlon={maxlon}",
    "types": {
      "city_without_population": {"text": "Город без населения"},
      "city_without_place_polygon": {"text": "Город без полигональной границы"},
      "city_without_place_node": {"text": "Город без точечного центра"},
      "routing_subgraph": {"text": "Изолированный подграф"},
      "routing_subgraph_trunk": {"text": "Изолированный подграф на уровне trunk"},
      "routing_subgraph_primary": {"text": "Изолированный подграф на уровне primary"},
      "routing_subgraph_secondary": {"text": "Изолированный подграф на уровне secondary"},
      "routing_subgraph_tertiary": {"text": "Изолированный подграф на уровне tertiary"},
      "duplicate_point": {"text": "Точка-дубликат"},
      "building_not_in_place": {"text": "Здание за пределами населенного пункта"},
      "address_without_street": {"text": "Адрес без улицы"},
      "address_street_not_found": {"text": "Адресная улица не найдена"},
      "address_street_not_in_place": {"text": "Улица из адреса не связана с городом"},
      "address_by_territory": {"text": "Здание нумеруется по территории"},
      "address_street_not_routed": {"text": "Не-рутинговая улица"},
      "street_not_in_place": {"text": "Улица за пределами города"}
    },
    "jsonp": true,
    "offset_limit": true
  }],

  errors: [{
    name: "Роутинг",
    children: [{
      name: "Изолированный подграф",
      type: "routing_subgraph"
    },{
      name: "Изолированный подграф trunk",
      type: "routing_subgraph_trunk"
    },{
      name: "Изолированный подграф primary",
      type: "routing_subgraph_primary"
    },{
      name: "Изолированный подграф secondary",
      type: "routing_subgraph_secondary"
    },{
      name: "Изолированный подграф tertiary",
      type: "routing_subgraph_tertiary"
    }]
  },{
    name: "Адресация",
    children: [{
      name: "Города",
      children: [{
        name: "Без населения",
        type: "city_without_population"
      },{
        name: "Без границы",
        type: "city_without_place_polygon"
      },{
        name: "Без центра",
        type: "city_without_place_node"
      }]
    },{
      name: "Улицы",
      children: [{
        name: "За пределами города",
        type: "street_not_in_place"
      }]
    },{
      name: "Здания",
      children: [{
        name: "За пределами города",
        type: "building_not_in_place"
      },{
        name: "Без улицы",
        type: "address_without_street"
      },{
        name: "Улица не найдена",
        type: "address_street_not_found"
      },{
        name: "Улица не связана с городом",
        type: "address_street_not_in_place"
      },{
        name: "Здание нумеруется по территории",
        type: "address_by_territory"
      },{
        name: "Улица не является рутинговой",
        type: "address_street_not_routed"
      }]
    },{
      name: "Другие",
      children: [{
        name: "Точка-дубликат",
        type: "duplicate_point"
      }]
    }]
  }],

  i18n: {
    objects: 'Объекты',
    params: 'Параметры',
    edit_in_potlatch: 'Редактировать в Potlatch',
    edit_in_josm: 'Редактировать в JOSM'
  },

  initialize: function() {
    console.log(this.sources)
    this.layer = new OsmJs.Validators.LeafletLayer({sources: this.sources, i18n: this.i18n});

    $('#validationerrors').validatorErrorsControl(this.layer, {errors: this.errors});
  },

  enable: function() {
    osm.leftpan.toggle(3);
    osm.map.addLayer(this.layer);
  },

  disable: function() {
    osm.leftpan.toggle(1);
    osm.map.addLayer(this.layer);
  }

}
<commit_msg>Validators fixes<commit_after>osm.validators = {

  sources: [{
    "name": "Адресный и роутинговый валидатор Zkir",
    "url": "http://osm.alno.name/validators/zkir?minlat={minlat}&minlon={minlon}&maxlat={maxlat}&maxlon={maxlon}",
    "types": {
      "city_without_population": {"text": "Город без населения"},
      "city_without_place_polygon": {"text": "Город без полигональной границы"},
      "city_without_place_node": {"text": "Город без точечного центра"},
      "routing_subgraph": {"text": "Изолированный подграф"},
      "routing_subgraph_trunk": {"text": "Изолированный подграф на уровне trunk"},
      "routing_subgraph_primary": {"text": "Изолированный подграф на уровне primary"},
      "routing_subgraph_secondary": {"text": "Изолированный подграф на уровне secondary"},
      "routing_subgraph_tertiary": {"text": "Изолированный подграф на уровне tertiary"},
      "duplicate_point": {"text": "Точка-дубликат"},
      "building_not_in_place": {"text": "Здание за пределами населенного пункта"},
      "address_without_street": {"text": "Адрес без улицы"},
      "address_street_not_found": {"text": "Адресная улица не найдена"},
      "address_street_not_in_place": {"text": "Улица из адреса не связана с городом"},
      "address_by_territory": {"text": "Здание нумеруется по территории"},
      "address_street_not_routed": {"text": "Не-рутинговая улица"},
      "street_not_in_place": {"text": "Улица за пределами города"}
    },
    "jsonp": true,
    "offset_limit": true
  }],

  errors: [{
    name: "Роутинг",
    children: [{
      name: "Изолированный подграф",
      type: "routing_subgraph"
    },{
      name: "Изолированный подграф trunk",
      type: "routing_subgraph_trunk"
    },{
      name: "Изолированный подграф primary",
      type: "routing_subgraph_primary"
    },{
      name: "Изолированный подграф secondary",
      type: "routing_subgraph_secondary"
    },{
      name: "Изолированный подграф tertiary",
      type: "routing_subgraph_tertiary"
    }]
  },{
    name: "Адресация",
    children: [{
      name: "Города",
      children: [{
        name: "Без населения",
        type: "city_without_population"
      },{
        name: "Без границы",
        type: "city_without_place_polygon"
      },{
        name: "Без центра",
        type: "city_without_place_node"
      }]
    },{
      name: "Улицы",
      children: [{
        name: "За пределами города",
        type: "street_not_in_place"
      }]
    },{
      name: "Здания",
      children: [{
        name: "За пределами города",
        type: "building_not_in_place"
      },{
        name: "Без улицы",
        type: "address_without_street"
      },{
        name: "Улица не найдена",
        type: "address_street_not_found"
      },{
        name: "Улица не связана с городом",
        type: "address_street_not_in_place"
      },{
        name: "Здание нумеруется по территории",
        type: "address_by_territory"
      },{
        name: "Улица не является рутинговой",
        type: "address_street_not_routed"
      }]
    },{
      name: "Другие",
      children: [{
        name: "Точка-дубликат",
        type: "duplicate_point"
      }]
    }]
  }],

  i18n: {
    objects: 'Объекты',
    params: 'Параметры',
    edit_in_potlatch: 'Редактировать в Potlatch',
    edit_in_josm: 'Редактировать в JOSM'
  },

  initialize: function() {
    this.layer = new OsmJs.Validators.LeafletLayer({sources: this.sources, i18n: this.i18n});

    $('#validationerrors').validatorErrorsControl(this.layer, {errors: this.errors});
  },

  enable: function() {
    osm.leftpan.toggle(3);
    osm.map.addLayer(this.layer);
  },

  disable: function() {
    osm.map.removeLayer(this.layer);
  }

}
<|endoftext|>


<commit_before>// JavaScript Document

/*
 * FileSender www.filesender.org
 *
 * Copyright (c) 2009-2012, AARNet, Belnet, HEAnet, SURFnet, UNINETT
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * *	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * *	Neither the name of AARNet, Belnet, HEAnet, SURFnet and UNINETT nor the
 * 	names of its contributors may be used to endorse or promote products
 * 	derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Manage files
filesender.ui.files = {
    // File selection (browse / drop) handler
    add: function(files) {
        for(var i=0; i<files.length; i++) {
            var info = files[i].name + ' : ' + filesender.ui.formatBytes(files[i].size);

            var node = $('
').appendTo(filesender.ui.nodes.files.list);

            $('').text(info).attr({title: info}).appendTo(node);

            $('').attr({
                title: lang.tr('click_to_delete_file')
            }).on('click', function() {
                var index = $(this).parent().attr('index');
                if(typeof index != 'undefined' && index.match(/^[0-9]+$/))
                    filesender.ui.transfer.removeFile(index);

                $(this).parent().remove();

                if(!filesender.ui.nodes.files.list.find('div').length)
                    filesender.ui.nodes.files.clear.button('disable');
            }).appendTo(node);

            $('
').append('
').appendTo(node);

            var added = filesender.ui.transfer.addFile(files[i], function(error, data) {
                node.addClass('invalid');
                node.addClass(error);
                $('').prependTo(node.find('.info'))
                node.attr({
                    title: lang.tr('invalid_file').replace({reason: lang.tr(error)})
                });
                node.find('.info').removeAttr('title');
            });

            filesender.ui.nodes.files.clear.button('enable');
            filesender.ui.evalUploadEnabled();

            if(added === false) continue;

            var size = 0;
            for(var j=0; j<filesender.ui.transfer.files.length; j++)
                size += filesender.ui.transfer.files[j].size;

            filesender.ui.nodes.stats.html(
                lang.tr('number_of_files') + ': ' + filesender.ui.transfer.files.length + '/' + filesender.config.max_html5_uploads + '
' +
                lang.tr('size') + ': ' + filesender.ui.formatBytes(size) + '/' + filesender.ui.formatBytes(filesender.config.max_html5_upload_size)
            );

            node.attr('index', added);
        }
    },

    // Update progress bar, run in transfer context
    progress: function(file, complete) {
        var size = 0;
        var uploaded = 0;
        for(var i=0; i<this.files.length; i++) {
            size += this.files[i].size;
            uploaded += this.files[i].uploaded;
        }

        var time = (new Date()).getTime() - this.time;
        var speed = uploaded / (time / 1000);

        filesender.ui.nodes.stats.html(
            lang.tr('uploaded') + ': ' + filesender.ui.formatBytes(uploaded) + '/' + filesender.ui.formatBytes(size) + '
' +
            lang.tr('average_speed') + ': ' + filesender.ui.formatBytes(speed) + '/s'
        );

        var id = file.name + ':' + file.size;
        var bar = filesender.ui.nodes.files.list.find('[file="' + id + '"] .progressbar div');
        if(!bar.length) return;

        var pct = complete ? 100 : (100 * file.uploaded / file.size).toFixed(2);
        pct = Math.min(pct, 100);

        bar.show();
        bar.text(pct + '%').css('width', pct + '%');
    },

    // Clear the file box
    clear: function() {
        filesender.ui.transfer.files = [];

        filesender.ui.nodes.files.input.val('');

        filesender.ui.nodes.files.list.find('div').remove();

        filesender.ui.nodes.files.clear.button('disable');

        filesender.ui.evalUploadEnabled();
    },
};

// Manage recipients
filesender.ui.recipients = {
    // Add recipient to list
    add: function(email) {
        if(email.match(/[,;\s]/)) { // Multiple values
            email = email.split(/[,;\s]/);
            var invalid = [];
            for(var i=0; i<email.length; i++) {
                var s = email[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
                if(!s) cintinue;
                if(!this.add(s))
                    invalid.push(s);
            }
            return invalid.join(', ');
        }

        var added = true;
        filesender.ui.transfer.addRecipient(email, function(error, data) {
            added = false;
        });
        if(!added) return email;

        var node = $('
').attr('email', email).appendTo(filesender.ui.nodes.recipients.list);
        $('').attr('title', email).text(email).appendTo(node);
        $('').attr({
            title: lang.tr('click_to_delete_recipient')
        }).on('click', function() {
            var email = $(this).parent().attr('email');
            if(email)
                filesender.ui.transfer.removeRecipient(email);

            $(this).parent().remove();
        }).appendTo(node);

        filesender.ui.nodes.recipients.list.show();

        filesender.ui.evalUploadEnabled();

        return '';
    },

    // Add recipients from input
    addFromInput: function(input) {
        input = $(input);

        var marker = input.data('error_marker');

        var invalid = this.add(input.val());

        if(invalid) {
            input.val(invalid);
            input.addClass('invalid');
            if(!marker) {
                marker = $('').attr({
                    title: lang.tr('invalid_recipient')
                }).insertBefore(input);
                input.data('error_marker', marker);
            }
        }else{
            input.val('');
            input.removeClass('invalid');
            if(marker) marker.remove();
        }
    },

    // Remove email from list
    remove: function(email) {
        if(email.match(/[,;\s]/)) { // Multiple values
            email = email.split(/[,;\s]/);
            for(var i=0; i<email.length; i++) {
                var s = email[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
                if(s) this.remove(s);
            }
            return;
        }

        filesender.ui.transfer.removeRecipient(email);

        filesender.ui.nodes.recipients.list.find('[email="' + email + '"]').remove();

        if(!filesender.ui.nodes.recipients.list.find('[email]').length)
            filesender.ui.nodes.recipients.list.hide();

        filesender.ui.evalUploadEnabled();
    },

    // Clear the recipients list
    clear: function() {
        filesender.ui.transfer.recipients = [];

        filesender.ui.nodes.recipients.input.val('');

        filesender.ui.nodes.recipients.list.find('div').remove();

        filesender.ui.evalUploadEnabled();
    },
};

filesender.ui.evalUploadEnabled = function() {
    var ok = true;

    if(!filesender.ui.transfer.files.length) ok = false;
    if(!filesender.ui.transfer.recipients.length) ok = false;

    if(filesender.ui.nodes.aup.length)
        if(!filesender.ui.nodes.aup.is(':checked')) ok = false;

    filesender.ui.nodes.uploadbtn.button(ok ? 'enable' : 'disable');
    return ok;
};

filesender.ui.startUpload = function() {
    this.transfer.expires = filesender.ui.nodes.expires.datepicker('getDate').getTime() / 1000;

    this.transfer.subject = filesender.ui.nodes.subject.val();
    this.transfer.message = filesender.ui.nodes.message.val();

    for(var o in filesender.ui.nodes.options)
        if(filesender.ui.nodes.options[o].is(':checked'))
            this.transfer.options.push(o);

    this.transfer.onprogress = filesender.ui.files.progress;

    this.transfer.oncomplete = function(time) {
        filesender.ui.files.clear();
        filesender.ui.recipients.clear();
        filesender.ui.nodes.subject.val('');
        filesender.ui.nodes.message.val('');
        filesender.ui.nodes.expires.datepicker('setDate', (new Date()).getTime() + 24*3600*1000 * filesender.config.default_daysvalid);

        alert('Done !');

        // TODO popup (view uploaded / upload other)
    };

    this.transfer.onerror = function(code, details) {
        alert('There was an error during upload : ' + code);
    };

    this.transfer.start();
};

$(function() {
    var form = $('#upload_form');
    if(!form.length) return;

    // Transfer
    filesender.ui.transfer = new filesender.transfer();

    // Register frequently used nodes
    filesender.ui.nodes = {
        files: {
            input: form.find(':file'),
            list: form.find('.files'),
            select: form.find('.files_actions .select_files'),
            clear: form.find('.files_actions .clear_all'),
        },
        recipients: {
            input: form.find('input[name="to"]'),
            list: form.find('.recipients'),
        },
        subject: form.find('input[name="subject"]'),
        message: form.find('textarea[name="message"]'),
        aup: form.find('input[name="aup"]'),
        expires: form.find('input[name="expires"]'),
        options: {},
        uploadbtn: form.find('.upload_button a'),
        stats: form.find('.files_actions .stats')
    };
    form.find('.basic_options input, .advanced_options input').each(function() {
        var i = $(this);
        filesender.ui.nodes.options[i.attr('name')] = i;
    });

    // Bind file list clear button
    filesender.ui.nodes.files.clear.on('click', function() {
        if($(this).button('option', 'disabled')) return;

        filesender.ui.files.clear();
        return false;
    }).button().button('disable');

    // Bind file list select button
    filesender.ui.nodes.files.select.on('click', function() {
        filesender.ui.nodes.files.input.click();
        return false;
    }).button();

    // Bind file drag drop events
    $('body').on('dragover', function (e) {
        e.preventDefault();
        e.stopPropagation();
    }).on('dragenter', function (e) {
        e.preventDefault();
        e.stopPropagation();
    }).on('drop', function (e) {
        if(!e.originalEvent.dataTransfer) return;
        if(!e.originalEvent.dataTransfer.files.length) return;

        e.preventDefault();
        e.stopPropagation();

        filesender.ui.files.add(e.originalEvent.dataTransfer.files);
    });

    filesender.ui.nodes.recipients.input.on('keydown', function(e) {
        if(e.keyCode != 13) return;

        // enter is pressed
        e.preventDefault();
        e.stopPropagation();

        filesender.ui.recipients.addFromInput($(this));
    }).on('blur', function(e) {
        e.preventDefault();
        e.stopPropagation();

        filesender.ui.recipients.addFromInput($(this));
    });

    // Bind file list select button
    filesender.ui.nodes.files.input.on('change', function() {
        // multiple files selected
        // loop through all files and show their values
        if (document.readyState != 'complete' && document.readyState != 'interactive') {
            return;
        }

        if(typeof this.files == 'undefined') return;

        filesender.ui.files.add(this.files);
    });

    // Handle "back" browser action
    var files = filesender.ui.nodes.files.input[0].files;
    if(files && files.length) filesender.ui.files.add(files);

    // Setup date picker
    $.datepicker.setDefaults({
        closeText: lang.tr('DP_closeText').out(),
        prevText: lang.tr('DP_prevText').out(),
        nextText: lang.tr('DP_nextText').out(),
        currentText: lang.tr('DP_currentText').out(),

        monthNames: lang.tr('DP_monthNames').values(),
        monthNamesShort: lang.tr('DP_monthNamesShort').values(),
        dayNames: lang.tr('DP_dayNames').values(),
        dayNamesShort: lang.tr('DP_dayNamesShort').values(),
        dayNamesMin: lang.tr('DP_dayNamesMin').values(),

        weekHeader: lang.tr('DP_weekHeader').out(),
        dateFormat: lang.tr('DP_dateFormat').out(),

        firstDay: parseInt(lang.tr('DP_firstDay').out()),
        isRTL: lang.tr('DP_isRTL').out().match(/true/),
        showMonthAfterYear: lang.tr('DP_showMonthAfterYear').out().match(/true/),

        yearSuffix: lang.tr('DP_yearSuffix').out()
    });

    // Bind picker
    var maxdate = new Date((new Date()).getTime() + 24*3600*1000 * filesender.config.default_daysvalid);
    filesender.ui.nodes.expires.datepicker({
        minDate: new Date(),
        maxDate: maxdate,
    });
    filesender.ui.nodes.expires.datepicker('setDate', maxdate);

    // Make options label toggle checkboxes
    form.find('.basic_options label, .advanced_options label').on('click', function() {
        var checkbox = $(this).closest('.fieldcontainer').find(':checkbox');
        checkbox.prop('checked', !checkbox.prop('checked'));
    }).css('cursor', 'pointer');

    // Bind advanced options display toggle
    form.find('.toggle_advanced_options').on('click', function() {
        $('.advanced_options').slideToggle();
        return false;
    });

    // Bind aup display toggle
    form.find('label[for="aup"]').on('click', function() {
        $(this).closest('.fieldcontainer').find('.terms').slideToggle();
        return false;
    });

    // Bind aup display toggle
    filesender.ui.nodes.uploadbtn.on('click', function() {
        filesender.ui.startUpload();
        return false;
    }).button().button('disable');

    filesender.ui.nodes.aup.on('change', function() {
        filesender.ui.evalUploadEnabled();
    });

    // special fix for esc key on firefox stopping xhr
    window.addEventListener('keydown', function(e) {
        (e.keyCode == 27 && e.preventDefault())
    });
});
<commit_msg>Ask for confirmation on page leaving if upload is in progress.<commit_after>// JavaScript Document

/*
 * FileSender www.filesender.org
 *
 * Copyright (c) 2009-2012, AARNet, Belnet, HEAnet, SURFnet, UNINETT
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * *	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * *	Neither the name of AARNet, Belnet, HEAnet, SURFnet and UNINETT nor the
 * 	names of its contributors may be used to endorse or promote products
 * 	derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Manage files
filesender.ui.files = {
    // File selection (browse / drop) handler
    add: function(files) {
        for(var i=0; i<files.length; i++) {
            var info = files[i].name + ' : ' + filesender.ui.formatBytes(files[i].size);

            var node = $('
').appendTo(filesender.ui.nodes.files.list);

            $('').text(info).attr({title: info}).appendTo(node);

            $('').attr({
                title: lang.tr('click_to_delete_file')
            }).on('click', function() {
                var index = $(this).parent().attr('index');
                if(typeof index != 'undefined' && index.match(/^[0-9]+$/))
                    filesender.ui.transfer.removeFile(index);

                $(this).parent().remove();

                if(!filesender.ui.nodes.files.list.find('div').length)
                    filesender.ui.nodes.files.clear.button('disable');
            }).appendTo(node);

            $('
').append('
').appendTo(node);

            var added = filesender.ui.transfer.addFile(files[i], function(error, data) {
                node.addClass('invalid');
                node.addClass(error);
                $('').prependTo(node.find('.info'))
                node.attr({
                    title: lang.tr('invalid_file').replace({reason: lang.tr(error)})
                });
                node.find('.info').removeAttr('title');
            });

            filesender.ui.nodes.files.clear.button('enable');
            filesender.ui.evalUploadEnabled();

            if(added === false) continue;

            var size = 0;
            for(var j=0; j<filesender.ui.transfer.files.length; j++)
                size += filesender.ui.transfer.files[j].size;

            filesender.ui.nodes.stats.html(
                lang.tr('number_of_files') + ': ' + filesender.ui.transfer.files.length + '/' + filesender.config.max_html5_uploads + '
' +
                lang.tr('size') + ': ' + filesender.ui.formatBytes(size) + '/' + filesender.ui.formatBytes(filesender.config.max_html5_upload_size)
            );

            node.attr('index', added);
        }
    },

    // Update progress bar, run in transfer context
    progress: function(file, complete) {
        var size = 0;
        var uploaded = 0;
        for(var i=0; i<this.files.length; i++) {
            size += this.files[i].size;
            uploaded += this.files[i].uploaded;
        }

        var time = (new Date()).getTime() - this.time;
        var speed = uploaded / (time / 1000);

        filesender.ui.nodes.stats.html(
            lang.tr('uploaded') + ': ' + filesender.ui.formatBytes(uploaded) + '/' + filesender.ui.formatBytes(size) + '
' +
            lang.tr('average_speed') + ': ' + filesender.ui.formatBytes(speed) + '/s'
        );

        var id = file.name + ':' + file.size;
        var bar = filesender.ui.nodes.files.list.find('[file="' + id + '"] .progressbar div');
        if(!bar.length) return;

        var pct = complete ? 100 : (100 * file.uploaded / file.size).toFixed(2);
        pct = Math.min(pct, 100);

        bar.show();
        bar.text(pct + '%').css('width', pct + '%');
    },

    // Clear the file box
    clear: function() {
        filesender.ui.transfer.files = [];

        filesender.ui.nodes.files.input.val('');

        filesender.ui.nodes.files.list.find('div').remove();

        filesender.ui.nodes.files.clear.button('disable');

        filesender.ui.evalUploadEnabled();
    },
};

// Manage recipients
filesender.ui.recipients = {
    // Add recipient to list
    add: function(email) {
        if(email.match(/[,;\s]/)) { // Multiple values
            email = email.split(/[,;\s]/);
            var invalid = [];
            for(var i=0; i<email.length; i++) {
                var s = email[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
                if(!s) cintinue;
                if(!this.add(s))
                    invalid.push(s);
            }
            return invalid.join(', ');
        }

        var added = true;
        filesender.ui.transfer.addRecipient(email, function(error, data) {
            added = false;
        });
        if(!added) return email;

        var node = $('
').attr('email', email).appendTo(filesender.ui.nodes.recipients.list);
        $('').attr('title', email).text(email).appendTo(node);
        $('').attr({
            title: lang.tr('click_to_delete_recipient')
        }).on('click', function() {
            var email = $(this).parent().attr('email');
            if(email)
                filesender.ui.transfer.removeRecipient(email);

            $(this).parent().remove();
        }).appendTo(node);

        filesender.ui.nodes.recipients.list.show();

        filesender.ui.evalUploadEnabled();

        return '';
    },

    // Add recipients from input
    addFromInput: function(input) {
        input = $(input);

        var marker = input.data('error_marker');

        var invalid = this.add(input.val());

        if(invalid) {
            input.val(invalid);
            input.addClass('invalid');
            if(!marker) {
                marker = $('').attr({
                    title: lang.tr('invalid_recipient')
                }).insertBefore(input);
                input.data('error_marker', marker);
            }
        }else{
            input.val('');
            input.removeClass('invalid');
            if(marker) marker.remove();
        }
    },

    // Remove email from list
    remove: function(email) {
        if(email.match(/[,;\s]/)) { // Multiple values
            email = email.split(/[,;\s]/);
            for(var i=0; i<email.length; i++) {
                var s = email[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
                if(s) this.remove(s);
            }
            return;
        }

        filesender.ui.transfer.removeRecipient(email);

        filesender.ui.nodes.recipients.list.find('[email="' + email + '"]').remove();

        if(!filesender.ui.nodes.recipients.list.find('[email]').length)
            filesender.ui.nodes.recipients.list.hide();

        filesender.ui.evalUploadEnabled();
    },

    // Clear the recipients list
    clear: function() {
        filesender.ui.transfer.recipients = [];

        filesender.ui.nodes.recipients.input.val('');

        filesender.ui.nodes.recipients.list.find('div').remove();

        filesender.ui.evalUploadEnabled();
    },
};

filesender.ui.evalUploadEnabled = function() {
    var ok = true;

    if(!filesender.ui.transfer.files.length) ok = false;
    if(!filesender.ui.transfer.recipients.length) ok = false;

    if(filesender.ui.nodes.aup.length)
        if(!filesender.ui.nodes.aup.is(':checked')) ok = false;

    filesender.ui.nodes.uploadbtn.button(ok ? 'enable' : 'disable');
    return ok;
};

filesender.ui.startUpload = function() {
    this.transfer.expires = filesender.ui.nodes.expires.datepicker('getDate').getTime() / 1000;

    this.transfer.subject = filesender.ui.nodes.subject.val();
    this.transfer.message = filesender.ui.nodes.message.val();

    for(var o in filesender.ui.nodes.options)
        if(filesender.ui.nodes.options[o].is(':checked'))
            this.transfer.options.push(o);

    this.transfer.onprogress = filesender.ui.files.progress;

    this.transfer.oncomplete = function(time) {
        filesender.ui.files.clear();
        filesender.ui.recipients.clear();
        filesender.ui.nodes.subject.val('');
        filesender.ui.nodes.message.val('');
        filesender.ui.nodes.expires.datepicker('setDate', (new Date()).getTime() + 24*3600*1000 * filesender.config.default_daysvalid);

        alert('Done !');

        // TODO popup (view uploaded / upload other)
    };

    this.transfer.onerror = function(code, details) {
        alert('There was an error during upload : ' + code);
    };

    this.transfer.start();
};

$(function() {
    var form = $('#upload_form');
    if(!form.length) return;

    // Transfer
    filesender.ui.transfer = new filesender.transfer();

    // Register frequently used nodes
    filesender.ui.nodes = {
        files: {
            input: form.find(':file'),
            list: form.find('.files'),
            select: form.find('.files_actions .select_files'),
            clear: form.find('.files_actions .clear_all'),
        },
        recipients: {
            input: form.find('input[name="to"]'),
            list: form.find('.recipients'),
        },
        subject: form.find('input[name="subject"]'),
        message: form.find('textarea[name="message"]'),
        aup: form.find('input[name="aup"]'),
        expires: form.find('input[name="expires"]'),
        options: {},
        uploadbtn: form.find('.upload_button a'),
        stats: form.find('.files_actions .stats')
    };
    form.find('.basic_options input, .advanced_options input').each(function() {
        var i = $(this);
        filesender.ui.nodes.options[i.attr('name')] = i;
    });

    // Bind file list clear button
    filesender.ui.nodes.files.clear.on('click', function() {
        if($(this).button('option', 'disabled')) return;

        filesender.ui.files.clear();
        return false;
    }).button().button('disable');

    // Bind file list select button
    filesender.ui.nodes.files.select.on('click', function() {
        filesender.ui.nodes.files.input.click();
        return false;
    }).button();

    // Bind file drag drop events
    $('body').on('dragover', function (e) {
        e.preventDefault();
        e.stopPropagation();
    }).on('dragenter', function (e) {
        e.preventDefault();
        e.stopPropagation();
    }).on('drop', function (e) {
        if(!e.originalEvent.dataTransfer) return;
        if(!e.originalEvent.dataTransfer.files.length) return;

        e.preventDefault();
        e.stopPropagation();

        filesender.ui.files.add(e.originalEvent.dataTransfer.files);
    });

    filesender.ui.nodes.recipients.input.on('keydown', function(e) {
        if(e.keyCode != 13) return;

        // enter is pressed
        e.preventDefault();
        e.stopPropagation();

        filesender.ui.recipients.addFromInput($(this));
    }).on('blur', function(e) {
        e.preventDefault();
        e.stopPropagation();

        filesender.ui.recipients.addFromInput($(this));
    });

    // Bind file list select button
    filesender.ui.nodes.files.input.on('change', function() {
        // multiple files selected
        // loop through all files and show their values
        if (document.readyState != 'complete' && document.readyState != 'interactive') {
            return;
        }

        if(typeof this.files == 'undefined') return;

        filesender.ui.files.add(this.files);
    });

    // Handle "back" browser action
    var files = filesender.ui.nodes.files.input[0].files;
    if(files && files.length) filesender.ui.files.add(files);

    // Setup date picker
    $.datepicker.setDefaults({
        closeText: lang.tr('DP_closeText').out(),
        prevText: lang.tr('DP_prevText').out(),
        nextText: lang.tr('DP_nextText').out(),
        currentText: lang.tr('DP_currentText').out(),

        monthNames: lang.tr('DP_monthNames').values(),
        monthNamesShort: lang.tr('DP_monthNamesShort').values(),
        dayNames: lang.tr('DP_dayNames').values(),
        dayNamesShort: lang.tr('DP_dayNamesShort').values(),
        dayNamesMin: lang.tr('DP_dayNamesMin').values(),

        weekHeader: lang.tr('DP_weekHeader').out(),
        dateFormat: lang.tr('DP_dateFormat').out(),

        firstDay: parseInt(lang.tr('DP_firstDay').out()),
        isRTL: lang.tr('DP_isRTL').out().match(/true/),
        showMonthAfterYear: lang.tr('DP_showMonthAfterYear').out().match(/true/),

        yearSuffix: lang.tr('DP_yearSuffix').out()
    });

    // Bind picker
    var maxdate = new Date((new Date()).getTime() + 24*3600*1000 * filesender.config.default_daysvalid);
    filesender.ui.nodes.expires.datepicker({
        minDate: new Date(),
        maxDate: maxdate,
    });
    filesender.ui.nodes.expires.datepicker('setDate', maxdate);

    // Make options label toggle checkboxes
    form.find('.basic_options label, .advanced_options label').on('click', function() {
        var checkbox = $(this).closest('.fieldcontainer').find(':checkbox');
        checkbox.prop('checked', !checkbox.prop('checked'));
    }).css('cursor', 'pointer');

    // Bind advanced options display toggle
    form.find('.toggle_advanced_options').on('click', function() {
        $('.advanced_options').slideToggle();
        return false;
    });

    // Bind aup display toggle
    form.find('label[for="aup"]').on('click', function() {
        $(this).closest('.fieldcontainer').find('.terms').slideToggle();
        return false;
    });

    // Bind aup display toggle
    filesender.ui.nodes.uploadbtn.on('click', function() {
        filesender.ui.startUpload();
        return false;
    }).button().button('disable');

    filesender.ui.nodes.aup.on('change', function() {
        filesender.ui.evalUploadEnabled();
    });

    // special fix for esc key on firefox stopping xhr
    window.addEventListener('keydown', function(e) {
        (e.keyCode == 27 && e.preventDefault())
    });

    // Set message to display if the user changes pages / close tab / close browser
    window.onbeforeunload = function() {
        if(!filesender.ui.transfer.status.match(/^(new|done|stopped)$/))
            return true; // Ask for leaving confirmation
    };
});
<|endoftext|>


<commit_before>Polymer
({
  is: "editor-viewport",

  // member variables
  properties:
  {
    width: { type: Number, value: 0 },
    height: { type: Number, value: 0 },
    renderer: { type: Object, value: new THREE.WebGLRenderer() },
    scene: { type: Object, value: new THREE.Scene() },
    camera: { type: Object, value: new THREE.PerspectiveCamera() },
    mesh: { type: Object, value: new THREE.Mesh() }
  },

  // public methods
  init: function()
  {
    this.width = this.offsetWidth;
    this.height = this.offsetHeight;

    this.init_renderer(this.width, this.height);
    this.init_camera(60.0, this.width / this.height, 0.1, 1000.0);
    this.init_scene();
  },

  init_renderer: function(width, height)
  {
    this.renderer.setSize(width, height);

    this.appendChild(this.renderer.domElement);
  },

  init_camera: function(fov, aspect, near, far, position)
  {
    this.camera.fov = fov;
    this.camera.aspect = aspect;
    this.camera.near = near;
    this.camera.far = far;
    this.camera.updateProjectionMatrix();

    this.camera.position.copy(new THREE.Vector3(0.0, 0.0, 10.0));
  },

  init_scene: function()
  {
    var geometry = new THREE.BoxGeometry(3.0, 3.0, 3.0);
    var material = new THREE.MeshBasicMaterial({ color: 0xffffff });
    this.mesh.geometry = geometry;
    this.mesh.material = material;

    this.scene.add(this.mesh);
  },

  update: function()
  {
    this.mesh.rotation.y += 0.025;
  },

  resize: function()
  {
    this.width = this.offsetWidth;
    this.height = this.offsetHeight;
    this.renderer.setSize(this.width, this.height);
    this.camera.aspect = this.width / this.height;
    this.camera.updateProjectionMatrix();
  },

  // fires when the element is inserted into the document
  attached: function()
  {
    this.init();

    // mandatory weirdness
    var scope = this;

    function render()
    {
      requestAnimationFrame(render);
      scope.renderer.render(scope.scene, scope.camera);
      scope.update();
    }
    render();

    function resize() { scope.resize(); }
    window.addEventListener("resize", resize);
  }
});
<commit_msg>Give the viewport a state toggle.<commit_after>Polymer
({
  is: "editor-viewport",

  // member variables
  properties:
  {
    width: { type: Number, value: 0 },
    height: { type: Number, value: 0 },
    renderer: { type: Object, value: new THREE.WebGLRenderer() },
    scene: { type: Object, value: new THREE.Scene() },
    camera: { type: Object, value: new THREE.PerspectiveCamera() },
    mesh: { type: Object, value: new THREE.Mesh() },
    isAnimated: { type: Boolean, value: true }
  },

  // listeners
  listeners:
  {
    tap: "tapHandler"
  },

  // handlers
  tapHandler: function()
  {
    this.toggleAnimation();
  },

  // public methods
  init: function()
  {
    this.width = this.offsetWidth;
    this.height = this.offsetHeight;

    this.init_renderer(this.width, this.height);
    this.init_camera(60.0, this.width / this.height, 0.1, 1000.0);
    this.init_scene();
  },

  init_renderer: function(width, height)
  {
    this.renderer.setSize(width, height);

    this.appendChild(this.renderer.domElement);
  },

  init_camera: function(fov, aspect, near, far, position)
  {
    this.camera.fov = fov;
    this.camera.aspect = aspect;
    this.camera.near = near;
    this.camera.far = far;
    this.camera.updateProjectionMatrix();

    this.camera.position.copy(new THREE.Vector3(0.0, 0.0, 10.0));
  },

  init_scene: function()
  {
    var geometry = new THREE.BoxGeometry(3.0, 3.0, 3.0);
    var material = new THREE.MeshBasicMaterial({ color: 0xffffff });
    this.mesh.geometry = geometry;
    this.mesh.material = material;

    this.scene.add(this.mesh);
  },

  update: function()
  {
    if (this.isAnimated) { this.mesh.rotation.y += 0.025; }
  },

  toggleAnimation: function()
  {
    this.isAnimated = !this.isAnimated;
  },

  resize: function()
  {
    this.width = this.offsetWidth;
    this.height = this.offsetHeight;
    this.renderer.setSize(this.width, this.height);
    this.camera.aspect = this.width / this.height;
    this.camera.updateProjectionMatrix();
  },

  // fires when the element is inserted into the document
  attached: function()
  {
    this.init();

    // mandatory weirdness
    var scope = this;

    function render()
    {
      requestAnimationFrame(render);
      scope.renderer.render(scope.scene, scope.camera);
      scope.update();
    }
    render();

    function resize() { scope.resize(); }
    window.addEventListener("resize", resize);
  }
});
<|endoftext|>


<commit_before>/**
 * Created by natefang on 1/14/16.
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import moment from 'moment'
if (process.env.BROWSER) {
	require("./style/mobile.css");
	require("./style/topic.css");
}

class Topic extends Component {
    constructor(props) {
        super(props);
        this.state = {
            topic: {
                strategies:[],
                owner:{
                    nickname :""
                },
                cover: "",
                score: 0,
                tryCount :0,
                description:""
            }};
    }
    componentWillMount (){
	    //var id = document.URL.split("/").slice(-1)[0];
        fetch('http://www.iyuanzi.net/topics/'+ this.props.params.id + '?version=v2')
            .then((response) => response.json())
            .then((data) => {
                this.setState({topic: data});
                console.log(this.state)
                var title = data.title || '元子育儿';
                var image = data.cover || 'http://share.iyuanzi.net/favicon.ico';
                var description = title;
                const oMeta = document.createElement('meta');
                oMeta.setAttribute('property', 'og:title');
                oMeta.setAttribute('content', title);
                document.getElementsByTagName('head')[0].appendChild(oMeta);
                const oMetaimage = document.createElement('meta');
                oMetaimage.setAttribute('property', 'og:image');
                oMetaimage.setAttribute('content', image);
                document.getElementsByTagName('head')[0].appendChild(oMetaimage);
                const oMetadesc = document.createElement('meta');
                oMetadesc.setAttribute('property', 'og:description');
                oMetadesc.setAttribute('content', description);
                document.getElementsByTagName('head')[0].appendChild(oMetadesc);
            })
            .catch((ex) => {
                console.log('fetch failed', ex);
            });
    }

    render() {
        return (

                {
                    <Topics topic = {this.state.topic}/>
                }

        );
    }
}

class Topics extends Component {
    render () {
        return (

{this.props.topic.title}

 来自: {this.props.topic.owner.nickname}

{this.props.topic.content}

                <StrategiesCollections strategies={this.props.topic.strategies}/>

        );
    }
}

class StrategiesCollections extends  Component {
    render () {
        return (

                {
                    this.props.strategies.length ?

                            妙招
                            ({this.props.strategies.length})

                            {
                                this.props.strategies.map(function(item) {
                                    return (<StrategyItem key={item.strategyId} {...item}></StrategyItem>);
                                })
                            }

 : null

                }

        );
    }
}

class StrategyItem extends Component {
    render () {
        return (

{this.props.title}

by {this.props.owner.nickname}

{ this.props.tryCount+"人参与 / " + this.props.score+"分" }

        );
    }
}

export default Topic;

<commit_msg>哎，不说了<commit_after>/**
 * Created by natefang on 1/14/16.
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import { Link } from 'react-router';
import moment from 'moment'
if (process.env.BROWSER) {
	require("./style/mobile.css");
	require("./style/topic.css");
}

class Topic extends Component {
    constructor(props) {
        super(props);
        this.state = {
            topic: {
                strategies:[],
                owner:{
                    nickname :""
                },
                cover: "",
                score: 0,
                tryCount :0,
                description:""
            }};
    }
    componentWillMount (){
	    //var id = document.URL.split("/").slice(-1)[0];
        fetch('http://www.iyuanzi.net/topics/'+ this.props.params.id + '?version=v2')
            .then((response) => response.json())
            .then((data) => {
                this.setState({topic: data});
                console.log(this.state)
                var title = data.title || '元子育儿';
                var image = data.cover || 'http://share.iyuanzi.net/favicon.ico';
                var description = title;
                const oMeta = document.createElement('meta');
                oMeta.setAttribute('property', 'og:title');
                oMeta.setAttribute('content', title);
                document.getElementsByTagName('head')[0].appendChild(oMeta);
                const oMetaimage = document.createElement('meta');
                oMetaimage.setAttribute('property', 'og:image');
                oMetaimage.setAttribute('content', image);
                document.getElementsByTagName('head')[0].appendChild(oMetaimage);
                const oMetadesc = document.createElement('meta');
                oMetadesc.setAttribute('property', 'og:description');
                oMetadesc.setAttribute('content', description);
                document.getElementsByTagName('head')[0].appendChild(oMetadesc);
            })
            .catch((ex) => {
                console.log('fetch failed', ex);
            });
    }

    render() {
        return (

                {
                    <Topics topic = {this.state.topic}/>
                }

        );
    }
}

class Topics extends Component {
    render () {
        return (

{this.props.topic.title}

 来自: {this.props.topic.owner.nickname}

{this.props.topic.content}

                <StrategiesCollections strategies={this.props.topic.strategies}/>

        );
    }
}

class StrategiesCollections extends  Component {
    render () {
        return (

                {
                    this.props.strategies.length ?

                            妙招
                            ({this.props.strategies.length})

                            {
                                this.props.strategies.map(function(item) {
                                    return (<StrategyItem key={item.strategyId} {...item}></StrategyItem>);
                                })
                            }

 : null

                }

        );
    }
}

class StrategyItem extends Component {
    render () {
        return (
            <Link to= {"/strategies/" + this.props.strategyId + "/view"} >

{this.props.title}

by {this.props.owner.nickname}

{ this.props.tryCount+"人参与 / " + this.props.score+"分" }

            </Link>
        );
    }
}

export default Topic;

<|endoftext|>


<commit_before>/**
 * @file betFlip command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

let recentUsers = [];

exports.exec = async (Bastion, message, args) => {
  try {
    let cooldown = 60;

    if (!recentUsers.includes(message.author.id)) {
      if (!args.money || args.money < 1 || !/^(heads|tails)$/i.test(args.outcome)) {
        /**
        * The command was ran with invalid parameters.
        * @fires commandUsage
        */
        return Bastion.emit('commandUsage', message, this.help);
      }

      args.money = parseInt(args.money);

      let minAmount = 5;
      if (args.money < minAmount) {
        /**
        * Error condition is encountered.
        * @fires error
        */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'invalidInput'), Bastion.strings.error(message.guild.language, 'minBet', true, minAmount), message.channel);
      }

      let outcomes = [
        'Heads',
        'Tails'
      ];
      let outcome = outcomes[Math.floor(Math.random() * outcomes.length)];

      let user = await Bastion.db.get(`SELECT bastionCurrencies FROM profiles WHERE userID=${message.author.id}`);
      user.bastionCurrencies = parseInt(user.bastionCurrencies);

      if (args.money > user.bastionCurrencies) {
        /**
        * Error condition is encountered.
        * @fires error
        */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'insufficientBalance'), Bastion.strings.error(message.guild.language, 'insufficientBalance', true, user.bastionCurrencies), message.channel);
      }

      recentUsers.push(message.author.id);

      let result;
      if (outcome.toLowerCase() === args.outcome.toLowerCase()) {
        let prize = args.money < 50 ? args.money + outcomes.length : args.money < 100 ? args.money : args.money * 1.5;
        result = `Congratulations! You won the bet.\nYou won **${prize}** Bastion Currencies.`;

        /**
        * User's account is debited with Bastion Currencies
        * @fires userDebit
        */
        Bastion.emit('userDebit', message.author, prize);
      }
      else {
        result = 'Sorry, you lost the bet. Better luck next time.';

        /**
        * User's account is credited with Bastion Currencies
        * @fires userCredit
        */
        Bastion.emit('userCredit', message.author, args.money);
      }

      await message.channel.send({
        embed: {
          color: Bastion.colors.BLUE,
          title: `Flipped ${outcome}`,
          description: result
        }
      });

      setTimeout(() => {
        recentUsers.splice(recentUsers.indexOf(message.author.id), 1);
      }, cooldown * 1000);
    }
    else {
      /**
      * Error condition is encountered.
      * @fires error
      */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'cooldown'), Bastion.strings.error(message.guild.language, 'gamblingCooldown', true, message.author, cooldown), message.channel);
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [ 'bf' ],
  enabled: true,
  argsDefinitions: [
    { name: 'outcome', type: String, alias: 'o', defaultOption: true },
    { name: 'money', type: Number, alias: 'm' }
  ]
};

exports.help = {
  name: 'betFlip',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'betflip < heads/tails > <-m amount>',
  example: [ 'betflip heads -m 100' ]
};
<commit_msg>Implemented new DB in betFlip command<commit_after>/**
 * @file betFlip command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

let recentUsers = [];

exports.exec = async (Bastion, message, args) => {
  try {
    let cooldown = 60;

    if (!recentUsers.includes(message.author.id)) {
      if (!args.money || args.money < 1 || !/^(heads|tails)$/i.test(args.outcome)) {
        /**
        * The command was ran with invalid parameters.
        * @fires commandUsage
        */
        return Bastion.emit('commandUsage', message, this.help);
      }

      args.money = parseInt(args.money);

      let minAmount = 5;
      if (args.money < minAmount) {
        /**
        * Error condition is encountered.
        * @fires error
        */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'invalidInput'), Bastion.strings.error(message.guild.language, 'minBet', true, minAmount), message.channel);
      }

      let outcomes = [
        'Heads',
        'Tails'
      ];
      let outcome = outcomes[Math.floor(Math.random() * outcomes.length)];

      let guildMemberModel = await message.client.database.models.guildMember.findOne({
        attributes: [ 'bastionCurrencies' ],
        where: {
          userID: message.author.id
        }
      });

      guildMemberModel.dataValues.bastionCurrencies = parseInt(guildMemberModel.dataValues.bastionCurrencies);

      if (args.money > guildMemberModel.dataValues.bastionCurrencies) {
        /**
        * Error condition is encountered.
        * @fires error
        */
        return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'insufficientBalance'), Bastion.strings.error(message.guild.language, 'insufficientBalance', true, guildMemberModel.dataValues.bastionCurrencies), message.channel);
      }

      recentUsers.push(message.author.id);

      let result;
      if (outcome.toLowerCase() === args.outcome.toLowerCase()) {
        let prize = args.money < 50 ? args.money + outcomes.length : args.money < 100 ? args.money : args.money * 1.5;
        result = `Congratulations! You won the bet.\nYou won **${prize}** Bastion Currencies.`;

        /**
        * User's account is debited with Bastion Currencies
        * @fires userDebit
        */
        Bastion.emit('userDebit', message.author, prize);
      }
      else {
        result = 'Sorry, you lost the bet. Better luck next time.';

        /**
        * User's account is credited with Bastion Currencies
        * @fires userCredit
        */
        Bastion.emit('userCredit', message.author, args.money);
      }

      await message.channel.send({
        embed: {
          color: Bastion.colors.BLUE,
          title: `Flipped ${outcome}`,
          description: result
        }
      });

      setTimeout(() => {
        recentUsers.splice(recentUsers.indexOf(message.author.id), 1);
      }, cooldown * 1000);
    }
    else {
      /**
      * Error condition is encountered.
      * @fires error
      */
      return Bastion.emit('error', Bastion.strings.error(message.guild.language, 'cooldown'), Bastion.strings.error(message.guild.language, 'gamblingCooldown', true, message.author, cooldown), message.channel);
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [ 'bf' ],
  enabled: true,
  argsDefinitions: [
    { name: 'outcome', type: String, alias: 'o', defaultOption: true },
    { name: 'money', type: Number, alias: 'm' }
  ]
};

exports.help = {
  name: 'betFlip',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'betflip < heads/tails > <-m amount>',
  example: [ 'betflip heads -m 100' ]
};
<|endoftext|>


<commit_before>// A function that builds the __new__ method for the factory function
__BRYTHON__.$__new__ = function(factory){
    return function(cls){
        /*
        if(cls===undefined){
            throw __BRYTHON__.builtins.TypeError(factory.$dict.__name__+'.__new__(): not enough arguments')
        }
        */
        var res = factory.apply(null,[])
        res.__class__ = cls.$dict
        var init_func = null
        try{init_func = __BRYTHON__.builtins.getattr(res,'__init__')}
        catch(err){}
        if(init_func!==null){
            var args = [], pos=0
            for(var i=1, _len_i = arguments.length; i < _len_i;i++){args[pos++]=arguments[i]}
            init_func.apply(null,args)
            res.__initialized__ = true
        }
        return res
    }
}

__BRYTHON__.builtins.object = (function($B){

var _b_=$B.builtins

// class object for the built-in class 'object'
var $ObjectDict = {
    //__class__:$type, : not here, added in py_type.js after $type is defined
    // __bases__ : set to an empty tuple in py_list.js after tuple is defined
    __name__:'object',
    $native:true
}

// function used to generate the methods that return 'unorderable types'
var $ObjectNI = function(name,op){
    return function(other){
        throw _b_.TypeError('unorderable types: object() '+op+
            ' '+ _b_.str($B.get_class(other).__name__)+'()')
    }
}

// Name of special methods : if they are not found as attributes, try
// the "reflected" attribute on the argument
// For instance, for "getattr(x,'__mul__')", if object x has no attribute
// "__mul__", try a function using the attribute "__rmul__" of its
// first argument

var opnames = ['add','sub','mul','truediv','floordiv','mod','pow',
    'lshift','rshift','and','xor','or']
var opsigns = ['+','-','*','/','//','%','**','<<','>>','&','^', '|']

$ObjectDict.__delattr__ = function(self,attr){delete self[attr]}

$ObjectDict.__dir__ = function(self) {
    var objects = [self], pos=1
    var mro = $B.get_class(self).__mro__
    for (var i=0, _len_i = mro.length; i < _len_i; i++) {
        objects[pos++]=mro[i]
    }

    var res = [], pos=0
    for (var i=0, _len_i = objects.length; i < _len_i; i++) {
        for(var attr in objects[i]){
            //if(attr.charAt(0)=='$' && attr.substr(0,2)!=='$$'){
            if(attr.charAt(0)=='$' && attr.charAt(1) != '$') {
                // exclude internal attributes set by Brython
                continue
            }
            if(!isNaN(parseInt(attr.charAt(0)))){
                // Exclude numerical attributes
                // '0', '1' are in attributes of string 'ab'
                continue
            }
            res[pos++]=attr
        }
    }
    res = _b_.list(_b_.set(res))
    _b_.list.$dict.sort(res)
    return res
}

$ObjectDict.__eq__ = function(self,other){
    // equality test defaults to identity of objects
    //test_issue_1393
    var _class=$B.get_class(self)
    if (_class.$native || _class.__name__ == 'function') {
       var _class1=$B.get_class(other)
       if (!_class1.$native && _class1.__name__ != 'function') {
          return _b_.getattr(other, '__eq__')(self)
       }
    }
    return self===other
}

$ObjectDict.__ge__ = $ObjectNI('__ge__','>=')

$ObjectDict.__getattribute__ = function(obj,attr){

    var klass = $B.get_class(obj)
    if(attr==='__class__'){
        return klass.$factory
    }
    var res = obj[attr],args=[]

    if(res===undefined){
        // search in classes hierarchy, following method resolution order
        //if(attr=='show'){console.log('object getattr '+attr+' of obj '+obj)}
        var mro = klass.__mro__
        for(var i=0, _len_i = mro.length; i < _len_i;i++){
            if(mro[i].$methods){
                var method = mro[i].$methods[attr]
                if(method!==undefined){return method(obj)}
            }
            var v=mro[i][attr]
            if(v!==undefined){
                res = v
                break
            }else if(attr=='__str__' && mro[i]['__repr__']!==undefined){
                // If the class doesn't define __str__ but defines __repr__,
                // use __repr__
                res = mro[i]['repr']
                break
            }
        }
    }else{
        if(res.__set__===undefined){
            // For non-data descriptors, the attribute found in object
            // dictionary takes precedence
            return res
        }
    }

    if(res!==undefined){
        var get_func = res.__get__

        if(get_func===undefined && (typeof res=='object')){
            var __get__ = _b_.getattr(res,'__get__',null);
            if(__get__ && (typeof __get__=='function')){
                get_func = function(x,y){return __get__.apply(x,[y,klass])}
            }
        }

        if(get_func===undefined && (typeof res=='function')){
            get_func = function(x){return x}
        }
        if(get_func!==undefined){ // descriptor
            res.__name__ = attr
            // __new__ is a static method
            if(attr=='__new__'){res.$type='staticmethod'}
            var res1 = get_func.apply(null,[res,obj,klass])
            if(typeof res1=='function'){
                // If attribute is a class then return it unchanged
                //
                // Example :
                // ===============
                // class A:
                //    def __init__(self,x):
                //        self.x = x
                //
                // class B:
                //    foo = A
                //    def __init__(self):
                //        self.info = self.foo(18)
                //
                // B()
                // ===============
                // In class B, when we call self.foo(18), self.foo is the
                // class A, its method __init__ must be called without B's
                // self as first argument

                if(res1.__class__===$B.$factory) return res

                // Same thing if the attribute is a method of an instance
                // =================
                // class myRepr:
                //     def repr(self, a):
                //         return a
                //
                // class myclass:
                //     _repr=myRepr()
                //     repr= _repr.repr
                //
                //     def myfunc(self):
                //         return self.repr('test')
                // =================
                // In function myfunc, self.repr is an instance of MyRepr,
                // it must be used as is, not transformed into a method

                else if(res1.__class__===$B.$MethodDict) return res

                // instance method object
                return $B.make_method(attr, klass, res, res1)(obj)

            }else{
                // result of __get__ is not a function
                return res1
            }
        }
        // attribute is not a descriptor : return it unchanged
        return res
    }else{
        // search __getattr__
        var _ga = obj['__getattr__']
        if(_ga===undefined){
            var mro = klass.__mro__
            if(mro===undefined){console.log('in getattr mro undefined for '+obj)}
            for(var i=0, _len_i = mro.length; i < _len_i;i++){
                var v=mro[i]['__getattr__']
                if(v!==undefined){
                    _ga = v
                    break
                }
            }
        }
        if(_ga!==undefined){
            try{return _ga(obj,attr)}
            catch(err){}
        }
        // for special methods such as __mul__, look for __rmul__ on operand
        if(attr.substr(0,2)=='__' && attr.substr(attr.length-2)=='__'){
            var attr1 = attr.substr(2,attr.length-4) // stripped of __
            var rank = opnames.indexOf(attr1)
            if(rank > -1){
                var rop = '__r'+opnames[rank]+'__' // name of reflected operator
                return function(){
                    try{
                        // Operands must be of different types
                        if($B.$get_class(arguments[0])===klass){throw Error('')}
                        return _b_.getattr(arguments[0],rop)(obj)
                    }catch(err){
                        var msg = "unsupported operand types for "+opsigns[rank]+": '"
                        msg += klass.__name__+"' and '" //+arguments[0].__class__.__name__+"'"
                        throw _b_.TypeError(msg)
                    }
                }
            }
        }
        //throw AttributeError('object '+obj.__class__.__name__+" has no attribute '"+attr+"'")
    }
}

$ObjectDict.__gt__ = $ObjectNI('__gt__','>')

$ObjectDict.__hash__ = function (self) {
    $B.$py_next_hash+=1;
    return $B.$py_next_hash;
}

$ObjectDict.__init__ = function(){}

$ObjectDict.__le__ = $ObjectNI('__le__','<=')

$ObjectDict.__lt__ = $ObjectNI('__lt__','<')

$ObjectDict.__mro__ = [$ObjectDict]

$ObjectDict.__new__ = function(cls){
    if(cls===undefined){throw _b_.TypeError('object.__new__(): not enough arguments')}
    return {__class__ : cls.$dict}
}

$ObjectDict.__ne__ = function(self,other){
   // see if any parent classes contain a __ne__ function
   var _f= $ObjectDict.__getattribute__(self, '__ne__')
   if (_f.__class__ !== self.__class__) return _b_.getattr(_f,'__ne__')(self, other)

   // check to see if any parent classes contain a __eq__ function
   var _f= $ObjectDict.__getattribute__(self, '__eq__')
   return _b_.bool(!_b_.getattr(_f,'__eq__')(self, other))
}

$ObjectDict.__or__ = function(self,other){
    if(_b_.bool(self)) return self
    return other
}

$ObjectDict.__repr__ = function(self){
    if(self===object) return "<class 'object'>"
    if(self.__class__===$B.$factory) return "<class '"+self.$dict.__name__+"'>"
    if(self.__class__.__module__!==undefined){
        return "<"+self.__class__.__module__+"."+self.__class__.__name__+" object>"
    }else{
        return "<"+self.__class__.__name__+" object>"
    }
}

$ObjectDict.__setattr__ = function(self,attr,val){
    if(val===undefined){ // setting an attribute to 'object' type is not allowed
        throw _b_.TypeError("can't set attributes of built-in/extension type 'object'")
    }else if(self.__class__===$ObjectDict){
        // setting an attribute to object() is not allowed
        if($ObjectDict[attr]===undefined){
            throw _b_.AttributeError("'object' object has no attribute '"+attr+"'")
        }else{
            throw _b_.AttributeError("'object' object attribute '"+attr+"' is read-only")
        }
    }
    self[attr] = val
}
$ObjectDict.__setattr__.__str__ = function(){return 'method object.setattr'}

$ObjectDict.__str__ = $ObjectDict.__repr__

$ObjectDict.__subclasshook__ = function(){return _b_.NotImplemented}

// constructor of the built-in class 'object'
function object(){return {__class__:$ObjectDict}}

object.$dict = $ObjectDict
// object.__class__ = $factory : this is done in py_types
$ObjectDict.$factory = object
object.__repr__ = object.__str__ = function(){return "<class 'object'>"}

return object

})(__BRYTHON__)
<commit_msg>fix foo.method not equals issue<commit_after>// A function that builds the __new__ method for the factory function
__BRYTHON__.$__new__ = function(factory){
    return function(cls){
        /*
        if(cls===undefined){
            throw __BRYTHON__.builtins.TypeError(factory.$dict.__name__+'.__new__(): not enough arguments')
        }
        */
        var res = factory.apply(null,[])
        res.__class__ = cls.$dict
        var init_func = null
        try{init_func = __BRYTHON__.builtins.getattr(res,'__init__')}
        catch(err){}
        if(init_func!==null){
            var args = [], pos=0
            for(var i=1, _len_i = arguments.length; i < _len_i;i++){args[pos++]=arguments[i]}
            init_func.apply(null,args)
            res.__initialized__ = true
        }
        return res
    }
}

__BRYTHON__.builtins.object = (function($B){

var _b_=$B.builtins

// class object for the built-in class 'object'
var $ObjectDict = {
    //__class__:$type, : not here, added in py_type.js after $type is defined
    // __bases__ : set to an empty tuple in py_list.js after tuple is defined
    __name__:'object',
    $native:true
}

// function used to generate the methods that return 'unorderable types'
var $ObjectNI = function(name,op){
    return function(other){
        throw _b_.TypeError('unorderable types: object() '+op+
            ' '+ _b_.str($B.get_class(other).__name__)+'()')
    }
}

// Name of special methods : if they are not found as attributes, try
// the "reflected" attribute on the argument
// For instance, for "getattr(x,'__mul__')", if object x has no attribute
// "__mul__", try a function using the attribute "__rmul__" of its
// first argument

var opnames = ['add','sub','mul','truediv','floordiv','mod','pow',
    'lshift','rshift','and','xor','or']
var opsigns = ['+','-','*','/','//','%','**','<<','>>','&','^', '|']

$ObjectDict.__delattr__ = function(self,attr){delete self[attr]}

$ObjectDict.__dir__ = function(self) {
    var objects = [self], pos=1
    var mro = $B.get_class(self).__mro__
    for (var i=0, _len_i = mro.length; i < _len_i; i++) {
        objects[pos++]=mro[i]
    }

    var res = [], pos=0
    for (var i=0, _len_i = objects.length; i < _len_i; i++) {
        for(var attr in objects[i]){
            //if(attr.charAt(0)=='$' && attr.substr(0,2)!=='$$'){
            if(attr.charAt(0)=='$' && attr.charAt(1) != '$') {
                // exclude internal attributes set by Brython
                continue
            }
            if(!isNaN(parseInt(attr.charAt(0)))){
                // Exclude numerical attributes
                // '0', '1' are in attributes of string 'ab'
                continue
            }
            res[pos++]=attr
        }
    }
    res = _b_.list(_b_.set(res))
    _b_.list.$dict.sort(res)
    return res
}

$ObjectDict.__eq__ = function(self,other){
    // equality test defaults to identity of objects
    //test_issue_1393
    var _class=$B.get_class(self)
    if (_class.$native || _class.__name__ == 'function') {
       var _class1=$B.get_class(other)
       if (!_class1.$native && _class1.__name__ != 'function') {
          return _b_.getattr(other, '__eq__')(self)
       }
    }
    return self===other
}

$ObjectDict.__ge__ = $ObjectNI('__ge__','>=')

$ObjectDict.__getattribute__ = function(obj,attr){

    var klass = $B.get_class(obj)
    if(attr==='__class__'){
        return klass.$factory
    }
    var res = obj[attr],args=[]

    if(res===undefined){
        // search in classes hierarchy, following method resolution order
        //if(attr=='show'){console.log('object getattr '+attr+' of obj '+obj)}
        var mro = klass.__mro__
        for(var i=0, _len_i = mro.length; i < _len_i;i++){
            if(mro[i].$methods){
                var method = mro[i].$methods[attr]
                if(method!==undefined){return method(obj)}
            }
            var v=mro[i][attr]
            if(v!==undefined){
                res = v
                break
            }else if(attr=='__str__' && mro[i]['__repr__']!==undefined){
                // If the class doesn't define __str__ but defines __repr__,
                // use __repr__
                res = mro[i]['repr']
                break
            }
        }
    }else{
        if(res.__set__===undefined){
            // For non-data descriptors, the attribute found in object
            // dictionary takes precedence
            return res
        }
    }

    if(res!==undefined){
        var get_func = res.__get__

        if(get_func===undefined && (typeof res=='object')){
            var __get__ = _b_.getattr(res,'__get__',null);
            if(__get__ && (typeof __get__=='function')){
                get_func = function(x,y){return __get__.apply(x,[y,klass])}
            }
        }

        if(get_func===undefined && (typeof res=='function')){
            get_func = function(x){return x}
        }
        if(get_func!==undefined){ // descriptor
            res.__name__ = attr
            // __new__ is a static method
            if(attr=='__new__'){res.$type='staticmethod'}
            var res1 = get_func.apply(null,[res,obj,klass])
            if(typeof res1=='function'){
                // If attribute is a class then return it unchanged
                //
                // Example :
                // ===============
                // class A:
                //    def __init__(self,x):
                //        self.x = x
                //
                // class B:
                //    foo = A
                //    def __init__(self):
                //        self.info = self.foo(18)
                //
                // B()
                // ===============
                // In class B, when we call self.foo(18), self.foo is the
                // class A, its method __init__ must be called without B's
                // self as first argument

                if(res1.__class__===$B.$factory) return res

                // Same thing if the attribute is a method of an instance
                // =================
                // class myRepr:
                //     def repr(self, a):
                //         return a
                //
                // class myclass:
                //     _repr=myRepr()
                //     repr= _repr.repr
                //
                //     def myfunc(self):
                //         return self.repr('test')
                // =================
                // In function myfunc, self.repr is an instance of MyRepr,
                // it must be used as is, not transformed into a method

                else if(res1.__class__===$B.$MethodDict) return res

                // instance method object
                return $B.make_method(attr, klass, res, res1)(obj)

            }else{
                // result of __get__ is not a function
                return res1
            }
        }
        // attribute is not a descriptor : return it unchanged
        return res
    }else{
        // search __getattr__
        var _ga = obj['__getattr__']
        if(_ga===undefined){
            var mro = klass.__mro__
            if(mro===undefined){console.log('in getattr mro undefined for '+obj)}
            for(var i=0, _len_i = mro.length; i < _len_i;i++){
                var v=mro[i]['__getattr__']
                if(v!==undefined){
                    _ga = v
                    break
                }
            }
        }
        if(_ga!==undefined){
            try{return _ga(obj,attr)}
            catch(err){}
        }
        // for special methods such as __mul__, look for __rmul__ on operand
        if(attr.substr(0,2)=='__' && attr.substr(attr.length-2)=='__'){
            var attr1 = attr.substr(2,attr.length-4) // stripped of __
            var rank = opnames.indexOf(attr1)
            if(rank > -1){
                var rop = '__r'+opnames[rank]+'__' // name of reflected operator
                return function(){
                    try{
                        // Operands must be of different types
                        if($B.$get_class(arguments[0])===klass){throw Error('')}
                        return _b_.getattr(arguments[0],rop)(obj)
                    }catch(err){
                        var msg = "unsupported operand types for "+opsigns[rank]+": '"
                        msg += klass.__name__+"' and '" //+arguments[0].__class__.__name__+"'"
                        throw _b_.TypeError(msg)
                    }
                }
            }
        }
        //throw AttributeError('object '+obj.__class__.__name__+" has no attribute '"+attr+"'")
    }
}

$ObjectDict.__gt__ = $ObjectNI('__gt__','>')

$ObjectDict.__hash__ = function (self) {
    $B.$py_next_hash+=1;
    return $B.$py_next_hash;
}

$ObjectDict.__init__ = function(){}

$ObjectDict.__le__ = $ObjectNI('__le__','<=')

$ObjectDict.__lt__ = $ObjectNI('__lt__','<')

$ObjectDict.__mro__ = [$ObjectDict]

$ObjectDict.__new__ = function(cls){
    if(cls===undefined){throw _b_.TypeError('object.__new__(): not enough arguments')}
    return {__class__ : cls.$dict}
}

$ObjectDict.__ne__ = function(self,other){
   // see if any parent classes contain a __ne__ function
   var _f= $ObjectDict.__getattribute__(self, '__ne__')
   if (_f.$infos.__func__ !== $ObjectDict.__ne__) return _b_.getattr(_f,'__ne__')(self, other)

   // check to see if any parent classes contain a __eq__ function
   var _f= $ObjectDict.__getattribute__(self, '__eq__')

   if (_f.$infos.__func__ !== $B.$MethodDict.__eq__) {
      // this sometimes produces bad results..
      // see class foo,  foo.method  example in 'basic test suite'
      return _b_.bool(!_b_.getattr(_f,'__eq__')(self, other))
   }

   return _b_.bool(!$ObjectDict.__eq__(self, other))
}

$ObjectDict.__or__ = function(self,other){
    if(_b_.bool(self)) return self
    return other
}

$ObjectDict.__repr__ = function(self){
    if(self===object) return "<class 'object'>"
    if(self.__class__===$B.$factory) return "<class '"+self.$dict.__name__+"'>"
    if(self.__class__.__module__!==undefined){
        return "<"+self.__class__.__module__+"."+self.__class__.__name__+" object>"
    }else{
        return "<"+self.__class__.__name__+" object>"
    }
}

$ObjectDict.__setattr__ = function(self,attr,val){
    if(val===undefined){ // setting an attribute to 'object' type is not allowed
        throw _b_.TypeError("can't set attributes of built-in/extension type 'object'")
    }else if(self.__class__===$ObjectDict){
        // setting an attribute to object() is not allowed
        if($ObjectDict[attr]===undefined){
            throw _b_.AttributeError("'object' object has no attribute '"+attr+"'")
        }else{
            throw _b_.AttributeError("'object' object attribute '"+attr+"' is read-only")
        }
    }
    self[attr] = val
}
$ObjectDict.__setattr__.__str__ = function(){return 'method object.setattr'}

$ObjectDict.__str__ = $ObjectDict.__repr__

$ObjectDict.__subclasshook__ = function(){return _b_.NotImplemented}

// constructor of the built-in class 'object'
function object(){return {__class__:$ObjectDict}}

object.$dict = $ObjectDict
// object.__class__ = $factory : this is done in py_types
$ObjectDict.$factory = object
object.__repr__ = object.__str__ = function(){return "<class 'object'>"}

return object

})(__BRYTHON__)
<|endoftext|>