<commit_before>import {keys, find, forEach} from 'lodash';

import {DEFAULT_TRANSFORM_REGEX, DEFAULT_GET_STATS_FILTER} from '../constants';

const StatsTransformer = {};

// convert the ids from the parsed stats objects into understandable keys
StatsTransformer.simplify = (stat) => find(keys(DEFAULT_TRANSFORM_REGEX), (key) => {
  // no other parameters necessary besides id
  let value = (DEFAULT_TRANSFORM_REGEX[key].regex.test(stat.id) ? key : false);

  if (value) {
    // some types need to check against a type field as well
    if (DEFAULT_TRANSFORM_REGEX[value].profiler) {
      if (!((stat[DEFAULT_TRANSFORM_REGEX[value].profiler.type].includes(DEFAULT_TRANSFORM_REGEX[value].profiler.value)) &&
      (value.toLowerCase().includes(DEFAULT_TRANSFORM_REGEX[value].profiler.value)))) {
        value = false;

        return value;
      }
    }
    // others were included but have a value that exclude them from the list because of duplicates that weren't chosen
    if (DEFAULT_TRANSFORM_REGEX[value].decider) {
      if (stat[DEFAULT_TRANSFORM_REGEX[value].decider] !== DEFAULT_TRANSFORM_REGEX[value].selector) {
        value = false;

        return value;
      }
    }
  }

  return value;
});

// parse the RTCStatsReport, extracting only the data we care about
StatsTransformer.parse = (report) => {
  const target = {};

  // from the stats object
  // get the rtc stats report
  if (report && report.forEach && report.size > 0) {
    report.forEach((stat) => {
      // each report has internal data
      if (stat && stat.type) {
        // pull only certain types
        if (DEFAULT_GET_STATS_FILTER.types.includes(stat.type)) {
          // insert into the target the statistic mapped to it's statical id
          target[stat.id] = stat;
        }
      }
    });
  }

  return target;
};

StatsTransformer.convert = (parsed, options) => {
  // supply your own simplification function (rather than id as the key)
  if (options.simplifyFn) {
    return options.simplifyFn(parsed);
  }
  // else use ours that stores things like rtcOutAudio, rtpInVideo, etc
  const target = {};

  forEach(parsed, (stat) => {
    const key = StatsTransformer.simplify(stat);

    if (key) {
      target[key] = stat;
    }
  });

  return target;
};

// transform the RTCStatsReport into a much more readable, processable format
StatsTransformer.transform = (report, options = {simplifyFn: undefined}) => {
  let data;
  // first parse it and cut out not necessary data
  const parsed = StatsTransformer.parse(report);

  // either convert the data or store each stat with it's id mapped as the key to the stat object itself
  if (DEFAULT_TRANSFORM_REGEX) {
    data = StatsTransformer.convert(parsed, options);
  }
  else {
    data = parsed;
  }

  return data;
};
export default StatsTransformer;
<commit_msg>fix(stats): add check for safari getStats filtering<commit_after>import {keys, find, forEach} from 'lodash';

import {DEFAULT_TRANSFORM_REGEX, DEFAULT_GET_STATS_FILTER} from '../constants';

const StatsTransformer = {};

// convert the ids from the parsed stats objects into understandable keys
StatsTransformer.simplify = (stat) => find(keys(DEFAULT_TRANSFORM_REGEX), (key) => {
  // no other parameters necessary besides id
  let value = (DEFAULT_TRANSFORM_REGEX[key].regex.test(stat.id) ? key : false);

  if (value) {
    // some types need to check against a type field as well
    if (DEFAULT_TRANSFORM_REGEX[value].profiler) {
      const mapStatToReadableType = stat[DEFAULT_TRANSFORM_REGEX[value].profiler.type];

      if (!((mapStatToReadableType && mapStatToReadableType.includes(DEFAULT_TRANSFORM_REGEX[value].profiler.value)) &&
      (value.toLowerCase().includes(DEFAULT_TRANSFORM_REGEX[value].profiler.value)))) {
        value = false;

        return value;
      }
    }
    // others were included but have a value that exclude them from the list because of duplicates that weren't chosen
    if (DEFAULT_TRANSFORM_REGEX[value].decider) {
      if (stat[DEFAULT_TRANSFORM_REGEX[value].decider] !== DEFAULT_TRANSFORM_REGEX[value].selector) {
        value = false;

        return value;
      }
    }
  }

  return value;
});

// parse the RTCStatsReport, extracting only the data we care about
StatsTransformer.parse = (report) => {
  const target = {};

  // from the stats object
  // get the rtc stats report
  if (report && report.forEach && report.size > 0) {
    report.forEach((stat) => {
      // each report has internal data
      if (stat && stat.type) {
        // pull only certain types
        if (DEFAULT_GET_STATS_FILTER.types.includes(stat.type)) {
          // insert into the target the statistic mapped to it's statical id
          target[stat.id] = stat;
        }
      }
    });
  }

  return target;
};

StatsTransformer.convert = (parsed, options) => {
  // supply your own simplification function (rather than id as the key)
  if (options.simplifyFn) {
    return options.simplifyFn(parsed);
  }
  // else use ours that stores things like rtcOutAudio, rtpInVideo, etc
  const target = {};

  forEach(parsed, (stat) => {
    const key = StatsTransformer.simplify(stat);

    if (key) {
      target[key] = stat;
    }
  });

  return target;
};

// transform the RTCStatsReport into a much more readable, processable format
StatsTransformer.transform = (report, options = {simplifyFn: undefined}) => {
  let data;
  // first parse it and cut out not necessary data
  const parsed = StatsTransformer.parse(report);

  // either convert the data or store each stat with it's id mapped as the key to the stat object itself
  if (DEFAULT_TRANSFORM_REGEX) {
    data = StatsTransformer.convert(parsed, options);
  }
  else {
    data = parsed;
  }

  return data;
};
export default StatsTransformer;
<|endoftext|>


<commit_before>
//parsing data nascita, pattern="dd/MM/yyyy"
angular.module('c4iapp').filter('birthDate', function($filter)
{
	 return function(input)
	 {
		if(input == null){ return ""; }

		//var dataNascita = $filter('birthDate')(new Date(input), 'dd/MM/yyyy');
		var anno, mese, giorno;

  		anno = input.substr(0,4);
  		mese = input.substr(4,2);
  		giorno = input.substr(6,2);
		var dataNascita = giorno + "/" + mese + "/" + giorno;

		return dataNascita.toUpperCase();

	 };
});

//parsing sesso(ita)
angular.module('c4iapp').filter('gender', function($filter)
{
	 return function(input)
	 {
		if(input == null){ return ""; }

		var sesso;
        if(input == 'male'){
        	sesso = 'maschile';
        }
        else if(input == 'female'){
        	sesso = 'femminile';
        }
		return sesso.toUpperCase();
	 };
});
<commit_msg>Optimzed the filter<commit_after>
//parsing data nascita, pattern="dd/MM/yyyy"
angular.module('c4iapp').filter('birthDate', ["$filter", "$log", function($filter, $log) {
    return function (input) {
        // Make sure a YYYYMMDD is passed
        if(!/^(\d){8}$/.test(input)){
            return "";
        }

        //var dataNascita = $filter('birthDate')(new Date(input), 'dd/MM/yyyy');
        var year = input.substr(0,4),
            month = input.substr(4,2),
            day = input.substr(6,2),
            bdate = new Date(year,month,day);

        return bdate.getDate() + "/" + bdate.getMonth()  + "/" + bdate.getYear();

    };
}]);

//parsing sesso(ita)
angular.module('c4iapp').filter('gender', ["$filter", "$log", function($filter, $log) {
    return function(input) {
        if (typeof input === "undefined") {
            return input;
        } else if (/^male/i.test(input)) {
            return "maschile";
        } else if (/^female/i.test(input)) {
            return "femminile";
        } else {
            $log.error("Unrecognized gender string: ", input);
            return input;
        }
    };
}]);
<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2013 Petar Petrov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var app = {
	Options: {
		VIBRATE: 200,
		VIBRATE_CLICK: 100
	},
	/**
	 * Entry point
	 */
    initialize: function() {
		// init local storage
		storage.init();
		// adjust moment.js BG localization
		moment.lang('bg', {
		    relativeTime : {
		        future: "след %s",
		        past:   "преди %s",
		        s:  "секунди",
		        m:  "минута",
		        mm: "%d минути",
		        h:  "час",
		        hh: "%d часа",
		        d:  "денy",
		        dd: "%d дни",
		        M:  "месец",
		        MM: "%d месеца",
		        y:  "година",
		        yy: "%d години"
		    }
		});
		moment().lang('bg');

        this.bindEvents();
    },
    /**
     * Bind any events that are required on startup. Common events are:
     * 'load', 'deviceready', 'offline', and 'online'.
     */
    bindEvents: function() {
    	document.addEventListener('deviceready', this.onDeviceReady, false);

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
//        document.addEventListener('touchstart', function(e) { e.preventDefault(); }, false);
//        document.addEventListener('touchend', function(e) { e.preventDefault(); }, false);
//        document.addEventListener('touchdown', function(e) { e.preventDefault(); }, false);

        $(document).on('pagebeforeshow', 'div:jqmData(role="page")', this.onPageLoad);
        $(document).on('tap', "a:jqmData(icon='refresh')", this.onRefresh);
        $(document).on('tap', "a:jqmData(role='ilink')", this.onGotoLink);
    },
    /**
     * The scope of 'this' is the event. In order to call the 'receivedEvent'
     * function, we must explicitly call 'app.receivedEvent(...);'
     */
    onDeviceReady: function() {
    	// speed optimization
    	$.mobile.pageContainer = $('#container');
    	$.mobile.defaultPageTransition = 'none'; // 'slide';
    	$.mobile.defaultDialogTransition = 'none';
    	// $.mobile.buttonMarkup.hoverDelay = 50;

    	// http://jquerymobile.com/demos/1.2.0/docs/pages/phonegap.html
    	$.support.cors = true;
    	$.mobile.allowCrossDomainPages = true;
    	$.mobile.page.prototype.options.domCache = true;

		$.mobile.loader.prototype.options.text = "Зареждане ...";
		$.mobile.loader.prototype.options.textVisible = true;
		$.mobile.loader.prototype.options.theme = "b";
		$.mobile.loader.prototype.options.html = "";

		// set version info
		cordova.exec(function(text) {
			$('#version').text('Версия: ' + text);
		}, function(error) {
			$('#version').text('');
		},
		"Version", "GetVersionName", []);
    },
    /**
     * Update items as soon as page load event is triggered
     */
    onPageLoad: function(event, data) {
    	var pageInfo = app.getCurrentPageInfo();
    	// check for valid page
    	if (pageInfo != null) {
	    	var pageData = storage.get(pageInfo.storageName);
	    	if (pageData) {
	    		app.updateListView(pageInfo, pageData);
	    	}
    	}
    },
    /**
     * Get all latest news entries for given section
     */
    onRefresh: function() {

    	var pageInfo = app.getCurrentPageInfo();
    	if (!pageInfo) {
    		return;
    	}

    	$.mobile.loading( 'show', {
    		text: 'Зареждане ...',
    		textVisible: true,
    		theme: 'b',
    		html: ""
    	});

    	grss.fetch(pageInfo.url, function(pageData, error) {
			// vibrate signal
			navigator.notification.vibrate(app.Options.VIBRATE);
    		if (error) {
    			// Notify
    			navigator.notification.alert(
    				    'Проблем при зареждане на информацията! Проверете интернет връзката си.',	// message
    				    null,		// callback
    				    'Грешка',	// title
    				    'OK'		// buttonName
    				);
    		} else {
    			if (pageData.items.length > 0) {
    				storage.save(pageInfo.storageName, pageData);
    				app.updateListView(pageInfo, pageData);
    			} else {
    				// Notify
        			navigator.notification.alert(
        				    'Няма налична нова информация! Опитайте по-късно.',	// message
        				    null,		// callback
        				    'Грешка',	// title
        				    'OK'		// buttonName
        				);
    			}
    		}

    		$.mobile.loading('hide');
    	});
	},
	/**
	 * Open an RSS item link in an InAppBrowser instance
	 */
	onGotoLink: function(event) {
		event.preventDefault();

		// vibrate signal
		navigator.notification.vibrate(app.Options.VIBRATE_CLICK);

		var ref = window.open($(this).attr('href'), '_system', 'location=no');
	},
    /**
     * Get information about the currently selected tab-page
     */
    getCurrentPageInfo: function() {
    	var pageInfo = {};
		pid = $.mobile.activePage.attr('id');

		switch(pid) {
		case "page-n":
			pageInfo.url = grss.URL_NEWS;
			pageInfo.storageName = storage.DataTypes.NEWS;
			break;
		case "page-e":
			pageInfo.url = grss.URL_EVENTS;
			pageInfo.storageName = storage.DataTypes.EVENTS;
			break;
		case "page-d":
			pageInfo.url = grss.URL_DECISIONS;
			pageInfo.storageName = storage.DataTypes.DECISIONS;
			break;
		default:
			// we're not updating...
			return null;
		}

		pageInfo.id = pid;

		return pageInfo;
    },
    /**
     * Update RSS items on currently selected tab-page
     */
    updateListView: function(pageInfo, pageData) {

    	var $page = $("div[id='" + pageInfo.id + "']");
    	var $content = $page.children( ":jqmData(role=content)" );

    	// set last update info
		var day = moment(pageData.lastUpdate);
		var mark = '

';
		mark += '
от ' + moment().startOf('hour').fromNow() + '
';

		// add items
//		var tpl = '

$$TITLE$$

$$DESC$$

';
//		mark += '
';
//		var tpl = '
';
//		tpl += '
$$TITLE$$

$$DESC$$

';

		var tpl = '
 \

 \

 \
					 \
					$$TITLE$$
  \

';

		mark += '
';

		var items = pageData.items;
		for (var i = 0; i < items.length; i++) {
			var entry = tpl;
			entry = entry.replace('$$TITLE$$', items[i].title);
//			entry = entry.replace('$$DESC$$', items[i].desc);
			entry = entry.replace('$$LINK$$', items[i].link);
			mark += entry;
		}
		mark += '
';
		mark += '

';

		// inject
    	$content.html(mark);
    	// enhance
//    	$page.page();

    	$content.find( ":jqmData(role=listview)" ).listview();

    	this.scroller = new iScroll($content[0]);
    	this.scroller.refresh();
    }
};
<commit_msg>Fixed issue where external links were not open using InAppBrowser.<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2013 Petar Petrov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var app = {
	Options: {
		VIBRATE: 200,
		VIBRATE_CLICK: 100
	},
	/**
	 * Entry point
	 */
    initialize: function() {
		// init local storage
		storage.init();
		// adjust moment.js BG localization
		moment.lang('bg', {
		    relativeTime : {
		        future: "след %s",
		        past:   "преди %s",
		        s:  "секунди",
		        m:  "минута",
		        mm: "%d минути",
		        h:  "час",
		        hh: "%d часа",
		        d:  "денy",
		        dd: "%d дни",
		        M:  "месец",
		        MM: "%d месеца",
		        y:  "година",
		        yy: "%d години"
		    }
		});
		moment().lang('bg');

        this.bindEvents();
    },
    /**
     * Bind any events that are required on startup. Common events are:
     * 'load', 'deviceready', 'offline', and 'online'.
     */
    bindEvents: function() {
    	document.addEventListener('deviceready', this.onDeviceReady, false);

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
//        document.addEventListener('touchstart', function(e) { e.preventDefault(); }, false);
//        document.addEventListener('touchend', function(e) { e.preventDefault(); }, false);
//        document.addEventListener('touchdown', function(e) { e.preventDefault(); }, false);

        $(document).on('pagebeforeshow', 'div:jqmData(role="page")', this.onPageLoad);
        $(document).on('tap', "a:jqmData(icon='refresh')", this.onRefresh);
        $(document).on('tap click', "a:jqmData(role='ilink')", this.onGotoLink);
    },
    /**
     * The scope of 'this' is the event. In order to call the 'receivedEvent'
     * function, we must explicitly call 'app.receivedEvent(...);'
     */
    onDeviceReady: function() {
    	// speed optimization
    	$.mobile.pageContainer = $('#container');
    	$.mobile.defaultPageTransition = 'none'; // 'slide';
    	$.mobile.defaultDialogTransition = 'none';
    	// $.mobile.buttonMarkup.hoverDelay = 50;

    	// http://jquerymobile.com/demos/1.2.0/docs/pages/phonegap.html
    	$.support.cors = true;
    	$.mobile.allowCrossDomainPages = true;
    	$.mobile.page.prototype.options.domCache = true;

		$.mobile.loader.prototype.options.text = "Зареждане ...";
		$.mobile.loader.prototype.options.textVisible = true;
		$.mobile.loader.prototype.options.theme = "b";
		$.mobile.loader.prototype.options.html = "";

		// set version info
		cordova.exec(function(text) {
			$('#version').text('Версия: ' + text);
		}, function(error) {
			$('#version').text('');
		},
		"Version", "GetVersionName", []);
    },
    /**
     * Update items as soon as page load event is triggered
     */
    onPageLoad: function(event, data) {
    	var pageInfo = app.getCurrentPageInfo();
    	// check for valid page
    	if (pageInfo != null) {
	    	var pageData = storage.get(pageInfo.storageName);
	    	if (pageData) {
	    		app.updateListView(pageInfo, pageData);
	    	}
    	}
    },
    /**
     * Get all latest news entries for given section
     */
    onRefresh: function() {

    	var pageInfo = app.getCurrentPageInfo();
    	if (!pageInfo) {
    		return;
    	}

    	$.mobile.loading( 'show', {
    		text: 'Зареждане ...',
    		textVisible: true,
    		theme: 'b',
    		html: ""
    	});

    	grss.fetch(pageInfo.url, function(pageData, error) {
			// vibrate signal
			navigator.notification.vibrate(app.Options.VIBRATE);
    		if (error) {
    			// Notify
    			navigator.notification.alert(
    				    'Проблем при зареждане на информацията! Проверете интернет връзката си.',
    				    null,		// callback
    				    'Грешка',	// title
    				    'OK'		// buttonName
    				);
    		} else {
    			if (pageData.items.length > 0) {
    				storage.save(pageInfo.storageName, pageData);
    				app.updateListView(pageInfo, pageData);
    			} else {
    				// Notify
        			navigator.notification.alert(
        				    'Няма налична нова информация! Опитайте по-късно.',	// message
        				    null,		// callback
        				    'Грешка',	// title
        				    'OK'		// buttonName
        				);
    			}
    		}

    		$.mobile.loading('hide');
    	});
	},
	/**
	 * Open an RSS item link in an InAppBrowser instance
	 */
	onGotoLink: function(event) {
		event.preventDefault();

		// vibrate signal
		navigator.notification.vibrate(app.Options.VIBRATE_CLICK);

		var ref = window.open($(this).attr('href'), '_blank', 'location=no');
	},
    /**
     * Get information about the currently selected tab-page
     */
    getCurrentPageInfo: function() {
    	var pageInfo = {};
		pid = $.mobile.activePage.attr('id');

		switch(pid) {
		case "page-n":
			pageInfo.url = grss.URL_NEWS;
			pageInfo.storageName = storage.DataTypes.NEWS;
			break;
		case "page-e":
			pageInfo.url = grss.URL_EVENTS;
			pageInfo.storageName = storage.DataTypes.EVENTS;
			break;
		case "page-d":
			pageInfo.url = grss.URL_DECISIONS;
			pageInfo.storageName = storage.DataTypes.DECISIONS;
			break;
		default:
			// we're not updating...
			return null;
		}

		pageInfo.id = pid;

		return pageInfo;
    },
    /**
     * Update RSS items on currently selected tab-page
     */
    updateListView: function(pageInfo, pageData) {

    	var $page = $("div[id='" + pageInfo.id + "']");
    	var $content = $page.children( ":jqmData(role=content)" );

    	// set last update info
		var day = moment(pageData.lastUpdate);
		var mark = '

';
		mark += '
от ' + moment().startOf('hour').fromNow() + '
';

		// add items
//		var tpl = '

$$TITLE$$

$$DESC$$

';
//		mark += '
';
//		var tpl = '
';
//		tpl += '
$$TITLE$$

$$DESC$$

';

		var tpl = '
 \

 \

 \
					 \
					$$TITLE$$
  \

';

		mark += '
';

		var items = pageData.items;
		for (var i = 0; i < items.length; i++) {
			var entry = tpl;
			entry = entry.replace('$$TITLE$$', items[i].title);
//			entry = entry.replace('$$DESC$$', items[i].desc);
			entry = entry.replace('$$LINK$$', items[i].link);
			mark += entry;
		}
		mark += '
';
		mark += '

';

		// inject
    	$content.html(mark);
    	// enhance
//    	$page.page();

    	$content.find( ":jqmData(role=listview)" ).listview();

    	this.scroller = new iScroll($content[0]);
    	this.scroller.refresh();
    }
};
<|endoftext|>


<commit_before>/**
 * ngSession
 *
 * @description Session handler module for AngularJS.
 * @module ngSession
 * @author Final Development Studio
 * @license MIT
 */

(function (window) {
  'use strict';

  var ng = window.angular;

  /* Default configuration */
  var config = {
    signOutUrl: '/api/users/sign-out',
    signInUrl: '/api/users/sign-in',
    updateUrl: '/api/session'
  };

  /**
   * ngSession service function.
   *
   * @private
   */
  function ngSessionServiceFn($rootScope, $http, $q) {
    $rootScope.session = {};

    /**
     * @module ngSession
     * @description ngSession Service
     */

    /**
     * Session update successful.
     *
     * @private
     */
    function onSessionUpdateSuccess(deferred, res) {
      $rootScope.session.user = res.data;

      deferred.resolve(res);
    }

    /**
     * On Sign In success.
     *
     * @private
     */
    function onSingInSuccess(deferred) {
      return update(null, deferred);
    }

    /**
     * On Sign Out success.
     *
     * @private
     */
    function onSingOutSuccess(deferred, res) {
      $rootScope.session.user = null;

      deferred.resolve(res);
    }

    /**
     * Signs a user in.
     *
     * It will perform a `POST` to the `config.signOutUrl` path and perform an
     * `update` if successful.
     *
     * @param {Object} data The data to send for sign in.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.signIn($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function signIn(data, config) {
      var deferred = $q.defer();

      /* Remove previous user object */
      $rootScope.session.user = null;

      $http.post(config.signInUrl, data, config)
        .then(onSingInSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Signs a user out.
     *
     * It will perform a POST to the `config.signOutUrl` path and delete the
     * user object on success.
     *
     * @param {Object} data The optional data to send for sign out.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.signOut($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function signOut(data, config) {
      var deferred = $q.defer();

      $http.post(config.signOutUrl, data, config)
        .then(onSingOutSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Reloads the session user object.
     *
     * It will perform a PUT to the `config.updateUrl` path and then a
     * consecuent session `update`.
     *
     * The server should handle the OUt request as a reload request and fetch
     * updated session data.
     *
     * @param {Object} data The optional data to send for the reload.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     * @param {Promise} deferred Optional deferred promise object.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.reload($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function reload(data, config, deferred) {
      if (!deferred) {
        deferred = $q.defer();
      }

      /* Reloads current session */
      $http.put(config.updateUrl, data, config)
        .then(update.bind(null, config, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Updates the session user object.
     *
     * It will perform a GET to the `config.updateUrl` path and set the
     * session's user object on success with the request's `res.data`.
     *
     * @param {Object} config Optional AngularJS HTTP request configuration.
     * @param {Promise} deferred Optional deferred promise object.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.update()
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function update(config, deferred) {
      if (!deferred) {
        deferred = $q.defer();
      }

      /* Retrieve current session */
      $http.get(config.updateUrl, config)
        .then(onSessionUpdateSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Retrieves a user data value by property name.
     *
     * @param {String} prop The property name to retrieve.
     *
     * @returns {Mixed} The property's value or the user object if no
     * property name is provided.
     *
     * @example ngSession.user('name'); // => 'John Smith'
     */
    function user(prop) {
      var session = $rootScope.session;

      if (!session) {
        return null;
      }

      if (prop && session.user) {
        return session.user[prop];
      }

      return session.user;
    }

    /**
     * Checks if the current user has any or all of the provided roles.
     *
     * @param {(String|String[])} roles The required roles. Can be a single
     *   string or a string array.
     * @param {Boolean} all If all the provided roles are required.
     *
     * @return {Boolean}
     *
     * @example
     * ngSession.hasRoles('ROLE.ADMIN'); // => false
     * ngSession.hasRoles('ROLE.USER'); // => true
     * ngSession.hasRoles(['ROLE.ADMIN', 'ROLE.USER']); // => true
     * ngSession.hasRoles(['ROLE.ADMIN', 'ROLE.USER'], true); // => false
     */
    function hasRole(roles, all) {
      var actual = user('roles');
      var matches = 0;

      if (!actual || !actual.length) {
        return false;
      }

      if (ng.isString(actual)) {
        actual = [actual];
      }

      if (ng.isString(roles)) {
        roles = [roles];
      }

      for (var i = 0, l = roles.length; i < l; i++) {
        if (actual.indexOf(roles[i]) > -1) {
          matches++;
        }
      }

      if (all) {
        return matches === roles.length;
      }

      return !!matches;
    }

    /**
     * Sets a value in the session object.
     *
     * @param {String} prop The property name to set.
     * @param {Mixed} The property value to set.
     *
     * @example ngSession.set('test', 'Test Value');
     */
    function set(prop, value) {
      $rootScope.session[prop] = value;
    }

    /**
     * Obtains a value from the session object.
     *
     * @param {String} prop The property name to obtain.
     *
     * @returns {Mixed} The property's value.
     *
     * @example ngSession.get('test'); // => 'Test Value'
     */
    function get(prop) {
      return $rootScope.session[prop];
    }

    /**
     * Deletes a property from the session object.
     *
     * @param {String} prop The property name.
     *
     * @example
     * ngSession.del('test');
     * ngSession.get('test'); // => null
     */
    function del(prop) {
      delete $rootScope.session[prop];
    }

    /* Session service definition */
    var ngSessionServiceDef = {
      hasRole: hasRole,
      signOut: signOut,
      signIn: signIn,
      reload: reload,
      update: update,
      user: user,
      get: get,
      set: set,
      del: del
    };

    return ngSessionServiceDef;
  }

  function sessionResolveFn($session) {
    return $session.update({
      cache: true
    });
  }

  var sessionResolveDef = [
    'ngSession',

    sessionResolveFn
  ];

  /**
   * ngSession run function.
   *
   * @private
   */
  function ngSessionRunFn($route) {
    for (var path in $route.routes) {
      var route = $route.routes[path];

      if (!ng.isObject(route.resolve)) {
        route.resolve = {};
      }

      route.resolve.__ngsession = sessionResolveDef;
    }
  }

  /**
   * @module ngSessionProvider
   * @description ngSession Provider
   */

  /**
   * Configuration method.
   *
   * @param {Object} config The configuration object.
   *
   * @example
   * ngSessionProvider.configure({
   *   signOutUrl: '/api/users/sign-out',
   *   signInUrl: '/api/users/sign-in',
   *   updateUrl: '/api/session'
   * });
   */
  function configure(cfg) {
    /* Sets session update GET URL */
    if (ng.isString(cfg.updateUrl)) {
      config.updateUrl = cfg.updateUrl;
    }

    /* Sets sign in POST URL */
    if (ng.isString(cfg.signInUrl)) {
      config.signInUrl = cfg.signInUrl;
    }

    /* Sets sign out POST URL */
    if (ng.isString(cfg.signOutUrl)) {
      config.signOutUrl = cfg.signOutUrl;
    }
  }

  /**
   * ngSession provider definition.
   *
   * @private
   */
  var ngSessionProviderDef = {
    configure: configure,

    $get: [
      '$rootScope', '$http', '$q',

      ngSessionServiceFn
    ]
  };

  /**
   * ngSession provider function.
   *
   * @private
   */
  function ngSessionProviderFn() {
    return ngSessionProviderDef;
  }

  /* Define AngularJS module */
  ng.module('ngSession', [])

  /* Define service provider */
  .provider('ngSession', ngSessionProviderFn)

  /* Define AngularJS module run function */
  .run(['$route', ngSessionRunFn]);

}(window));
<commit_msg>Fixed config variables mixup<commit_after>/**
 * ngSession
 *
 * @description Session handler module for AngularJS.
 * @module ngSession
 * @author Final Development Studio
 * @license MIT
 */

(function (window) {
  'use strict';

  var ng = window.angular;

  /* Default configuration */
  var CONFIG = {
    signOutUrl: '/api/users/sign-out',
    signInUrl: '/api/users/sign-in',
    updateUrl: '/api/session'
  };

  /**
   * ngSession service function.
   *
   * @private
   */
  function ngSessionServiceFn($rootScope, $http, $q) {
    $rootScope.session = {};

    /**
     * @module ngSession
     * @description ngSession Service
     */

    /**
     * Session update successful.
     *
     * @private
     */
    function onSessionUpdateSuccess(deferred, res) {
      $rootScope.session.user = res.data;

      deferred.resolve(res);
    }

    /**
     * On Sign In success.
     *
     * @private
     */
    function onSingInSuccess(deferred) {
      return update(null, deferred);
    }

    /**
     * On Sign Out success.
     *
     * @private
     */
    function onSingOutSuccess(deferred, res) {
      $rootScope.session.user = null;

      deferred.resolve(res);
    }

    /**
     * Signs a user in.
     *
     * It will perform a `POST` to the `config.signOutUrl` path and perform an
     * `update` if successful.
     *
     * @param {Object} data The data to send for sign in.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.signIn($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function signIn(data, config) {
      var deferred = $q.defer();

      /* Remove previous user object */
      $rootScope.session.user = null;

      $http.post(CONFIG.signInUrl, data, config)
        .then(onSingInSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Signs a user out.
     *
     * It will perform a POST to the `config.signOutUrl` path and delete the
     * user object on success.
     *
     * @param {Object} data The optional data to send for sign out.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.signOut($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function signOut(data, config) {
      var deferred = $q.defer();

      $http.post(CONFIG.signOutUrl, data, config)
        .then(onSingOutSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Reloads the session user object.
     *
     * It will perform a PUT to the `config.updateUrl` path and then a
     * consecuent session `update`.
     *
     * The server should handle the OUt request as a reload request and fetch
     * updated session data.
     *
     * @param {Object} data The optional data to send for the reload.
     * @param {Object} config Optional AngularJS HTTP request configuration.
     * @param {Promise} deferred Optional deferred promise object.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.reload($scope.data)
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function reload(data, config, deferred) {
      if (!deferred) {
        deferred = $q.defer();
      }

      /* Reloads current session */
      $http.put(CONFIG.updateUrl, data, config)
        .then(update.bind(null, config, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Updates the session user object.
     *
     * It will perform a GET to the `config.updateUrl` path and set the
     * session's user object on success with the request's `res.data`.
     *
     * @param {Object} config Optional AngularJS HTTP request configuration.
     * @param {Promise} deferred Optional deferred promise object.
     *
     * @returns {Promise} A promise resolving the request's `res` object.
     *
     * @example
     * ngSession.update()
     *   .then(function (res) {})
     *   .catch(function (res) {})
     */
    function update(config, deferred) {
      if (!deferred) {
        deferred = $q.defer();
      }

      /* Retrieve current session */
      $http.get(CONFIG.updateUrl, config)
        .then(onSessionUpdateSuccess.bind(null, deferred))
        .catch(deferred.reject);

      return deferred.promise;
    }

    /**
     * Retrieves a user data value by property name.
     *
     * @param {String} prop The property name to retrieve.
     *
     * @returns {Mixed} The property's value or the user object if no
     * property name is provided.
     *
     * @example ngSession.user('name'); // => 'John Smith'
     */
    function user(prop) {
      var session = $rootScope.session;

      if (!session) {
        return null;
      }

      if (prop && session.user) {
        return session.user[prop];
      }

      return session.user;
    }

    /**
     * Checks if the current user has any or all of the provided roles.
     *
     * @param {(String|String[])} roles The required roles.
     * @param {Boolean} all If all the provided roles are required.
     *
     * @return {Boolean}
     *
     * @example
     * ngSession.hasRoles('ROLE.ADMIN'); // => false
     * ngSession.hasRoles('ROLE.USER'); // => true
     * ngSession.hasRoles(['ROLE.ADMIN', 'ROLE.USER']); // => true
     * ngSession.hasRoles(['ROLE.ADMIN', 'ROLE.USER'], true); // => false
     */
    function hasRole(roles, all) {
      var actual = user('roles');
      var matches = 0;

      if (!actual || !actual.length) {
        return false;
      }

      if (ng.isString(actual)) {
        actual = [actual];
      }

      if (ng.isString(roles)) {
        roles = [roles];
      }

      for (var i = 0, l = roles.length; i < l; i++) {
        if (actual.indexOf(roles[i]) > -1) {
          matches++;
        }
      }

      if (all) {
        return matches === roles.length;
      }

      return !!matches;
    }

    /**
     * Sets a value in the session object.
     *
     * @param {String} prop The property name to set.
     * @param {Mixed} The property value to set.
     *
     * @example ngSession.set('test', 'Test Value');
     */
    function set(prop, value) {
      $rootScope.session[prop] = value;
    }

    /**
     * Obtains a value from the session object.
     *
     * @param {String} prop The property name to obtain.
     *
     * @returns {Mixed} The property's value.
     *
     * @example ngSession.get('test'); // => 'Test Value'
     */
    function get(prop) {
      return $rootScope.session[prop];
    }

    /**
     * Deletes a property from the session object.
     *
     * @param {String} prop The property name.
     *
     * @example
     * ngSession.del('test');
     * ngSession.get('test'); // => null
     */
    function del(prop) {
      delete $rootScope.session[prop];
    }

    /* Session service definition */
    var ngSessionServiceDef = {
      hasRole: hasRole,
      signOut: signOut,
      signIn: signIn,
      reload: reload,
      update: update,
      user: user,
      get: get,
      set: set,
      del: del
    };

    return ngSessionServiceDef;
  }

  var resolved = false;

  /**
   * Session resolve callback function.
   *
   * @private
   */
  function sessionResolveFn($session) {
    if (resolved) {
      return resolved;
    }

    resolved = true;

    return $session.update();
  }

  /* Session resolve definition */
  var sessionResolveDef = [
    'ngSession',

    sessionResolveFn
  ];

  /**
   * ngSession run function.
   *
   * @private
   */
  function ngSessionRunFn($route) {
    for (var path in $route.routes) {
      var route = $route.routes[path];

      if (!ng.isObject(route.resolve)) {
        route.resolve = {};
      }

      route.resolve._session = sessionResolveDef;
    }
  }

  /**
   * @module ngSessionProvider
   * @description ngSession Provider
   */

  /**
   * Configuration method.
   *
   * @param {Object} config The configuration object.
   *
   * @example
   * ngSessionProvider.configure({
   *   signOutUrl: '/api/users/sign-out',
   *   signInUrl: '/api/users/sign-in',
   *   updateUrl: '/api/session'
   * });
   */
  function configure(config) {
    /* Sets session update GET URL */
    if (ng.isString(config.updateUrl)) {
      CONFIG.updateUrl = config.updateUrl;
    }

    /* Sets sign in POST URL */
    if (ng.isString(config.signInUrl)) {
      CONFIG.signInUrl = config.signInUrl;
    }

    /* Sets sign out POST URL */
    if (ng.isString(config.signOutUrl)) {
      CONFIG.signOutUrl = config.signOutUrl;
    }
  }

  /**
   * ngSession provider definition.
   *
   * @private
   */
  var ngSessionProviderDef = {
    configure: configure,

    $get: [
      '$rootScope', '$http', '$q',

      ngSessionServiceFn
    ]
  };

  /**
   * ngSession provider function.
   *
   * @private
   */
  function ngSessionProviderFn() {
    return ngSessionProviderDef;
  }

  /* Define AngularJS module */
  ng.module('ngSession', [])

  /* Define service provider */
  .provider('ngSession', ngSessionProviderFn)

  /* Define AngularJS module run function */
  .run(['$route', ngSessionRunFn]);

}(window));
<|endoftext|>


<commit_before>"undefined" == typeof PDP ? !
function () {
  var a, b, c, d, e = "0.03",
    f = document.createDocumentFragment(),
    g = [{
      charset: "UTF-8",
      type: "link",
      url: "//alexxroche.github.io/personal-data-protocol/css/pdp.css",
      async: !0,
      nocache: !0
    }, {
      type: "script",
      url: "//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js",
      async: !1,
      nocache: !1
    }, {
      type: "script",
      url: "//www.google.com/jsapi",
      async: !1,
      nocache: !1
    }, {
      charset: "UTF-8",
      type: "script",
      url: "//alexxroche.github.io/personal-data-protocol/js/pdp.js",
      async: !1,
      nocache: !1
    }];
  for (d = 0; d < g.length; d++) a = g[d], b = document.createElement(a.type), c = a.nocache ? "?v=" + e : "", "link" === a.type ? (b.rel = "stylesheet", b.href = a.url + c) : "script" === a.type && (b.src = a.url + c), b.async = a.async, f.appendChild(b);
  document.head.appendChild(f)
}() : PDP.message("Personal Data Overlay is already loaded!", "error");

<commit_msg>Immediately Invoked Function Expression (IIFE)<commit_after>"undefined" == typeof PDP ? !
(function () {
  var a, b, c, d, e = "0.03",
    f = document.createDocumentFragment(),
    g = [{
      charset: "UTF-8",
      type: "link",
      url: "//alexxroche.github.io/personal-data-protocol/css/pdp.css",
      async: !0,
      nocache: !0
    }, {
      type: "script",
      url: "//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.0.min.js",
      async: !1,
      nocache: !1
    }, {
      type: "script",
      url: "//www.google.com/jsapi",
      async: !1,
      nocache: !1
    }, {
      charset: "UTF-8",
      type: "script",
      url: "//alexxroche.github.io/personal-data-protocol/js/pdp.js",
      async: !1,
      nocache: !1
    }];
  for (d = 0; d < g.length; d++) a = g[d], b = document.createElement(a.type), c = a.nocache ? "?v=" + e : "", "link" === a.type ? (b.rel = "stylesheet", b.href = a.url + c) : "script" === a.type && (b.src = a.url + c), b.async = a.async, f.appendChild(b);
  document.head.appendChild(f)
})() : PDP.message("Personal Data Overlay is already loaded!", "error");

<|endoftext|>


<commit_before>// const cookieTotal = require('clicking')

// setItem and getItem are referencing objects.
//

function save() {
  localStorage.setItem("cookieTotal", JSON.stringify(cookieTotal));
  localStorage.setItem("clickMultiplier", JSON.stringify(clickMultiplier));
  localStorage.setItem("grandmaTotal", JSON.stringify(grandmaTotal));
  localStorage.setItem("bakeryTotal", JSON.stringify(bakeryTotal));
}

function newGame() {
  localStorage.clear();
  cookieTotal = 0
  clickMultiplier = 1
  grandmaTotal = 0
  bakeryTotal = 0
  localStorage.setItem("cookieTotal", JSON.stringify(cookieTotal));
  localStorage.setItem("clickMultiplier", JSON.stringify(clickMultiplier));
  localStorage.setItem("grandmaTotal", JSON.stringify(grandmaTotal));
  localStorage.setItem("bakeryTotal", JSON.stringify(bakeryTotal));
  location.reload();
}

function load() {
    cookieTotal = JSON.parse(localStorage.getItem("cookieTotal"));
    clickMultiplier = JSON.parse(localStorage.getItem("clickMultiplier"));
    grandmaTotal = JSON.parse(localStorage.getItem("grandmaTotal"));
    bakeryTotal = JSON.parse(localStorage.getItem("bakeryTotal"));

}

window.setInterval(save, 1000)

// document.getElementById('savegame').onclick = save;
document.getElementById('newgame').onclick = newGame;
document.addEventListener("DOMContentLoaded", load());
<commit_msg>fixed loading on new browsers<commit_after>// const cookieTotal = require('clicking')

// setItem and getItem are referencing objects.
//

function save() {
  localStorage.setItem("cookieTotal", JSON.stringify(cookieTotal));
  localStorage.setItem("clickMultiplier", JSON.stringify(clickMultiplier));
  localStorage.setItem("grandmaTotal", JSON.stringify(grandmaTotal));
  localStorage.setItem("bakeryTotal", JSON.stringify(bakeryTotal));
}

function newGame() {
  localStorage.clear();
  cookieTotal = 0
  clickMultiplier = 1
  grandmaTotal = 0
  bakeryTotal = 0
  localStorage.setItem("cookieTotal", JSON.stringify(cookieTotal));
  localStorage.setItem("clickMultiplier", JSON.stringify(clickMultiplier));
  localStorage.setItem("grandmaTotal", JSON.stringify(grandmaTotal));
  localStorage.setItem("bakeryTotal", JSON.stringify(bakeryTotal));
  location.reload();
}

function load() {
  if (localStorage.getItem("cookieTotal") === null) {
    cookieTotal = 0
  } else {
    cookieTotal = JSON.parse(localStorage.getItem("cookieTotal"));
  }

  if (localStorage.getItem("clickMultiplier") === null) {
    clickMultiplier = 1
  } else {
    clickMultiplier = JSON.parse(localStorage.getItem("clickMultiplier"));
  }

  if (localStorage.getItem("grandmaTotal") === null) {
    grandmaTotal = 0
  } else {
    grandmaTotal = JSON.parse(localStorage.getItem("grandmaTotal"));
  }

  if (localStorage.getItem("bakeryTotal") === null) {
    bakeryTotal = 0
  } else {
    bakeryTotal = JSON.parse(localStorage.getItem("bakeryTotal"));
  }
}

window.setInterval(save, 1000)

// document.getElementById('savegame').onclick = save;
document.getElementById('newgame').onclick = newGame;
document.addEventListener("DOMContentLoaded", load());
<|endoftext|>


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

    $('body').on('click','.modificar', function(){
        if(confirm('Desea modificar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/modificarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                processData: false,
                dataType: "json",
            }).done(function(e){
                window.location.href = location.origin + '/hazquesuceda/emprendedor/editarproyecto/' + idProyecto;
            }).fail(function(e){

            });
        }
    });

    $('body').on('click','.clausurar', function(){
        if(confirm('Desea clausurar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/clausurarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                if(e.success){
                    //$("#acciones" + idProyecto).html("No hay acciones disponibles");
                    window.location.href = location.origin + '/hazquesuceda/misproyectos';
                }
            }).fail(function(e){

            });
        }
    });

    $('body').on('click','.renovar', function(){
        if(confirm('Desea renovar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/renovarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                if(e.success)
                {
                    $("#acciones"+idProyecto).html('<button type="button" title="Clausurar" class="btn btn-default clausurar" id="btnClausurar' + idProyecto + ' value="'+ idProyecto +' "> </button>');
                    window.location.href = location.origin + '/hazquesuceda/misproyectos';
                }
            }).fail(function(e){

            });
        }
    });

    $('body').on('click','.finalizar', function(){
        if(confirm('Desea finalizar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/finalizarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                $("#acciones" + idProyecto).html("No hay acciones disponibles");
            }).fail(function(e){
                alert("no successo");
            });
        }
    });

});<commit_msg>Funciones de acciones sobre proyectos funcionando<commit_after>$(document).ready(function (){

    $('body').on('click','.modificar', function(){
        if(confirm('Desea modificar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            redirect("emprendedor/editarproyecto",idProyecto);
        }
    });

    $('body').on('click','.clausurar', function(){
        if(confirm('Desea clausurar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/clausurarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                if(e.success){
                    redirect("misproyectos","");
                }
            }).fail(function(e){

            });
        }
    });

    $('body').on('click','.renovar', function(){
        if(confirm('Desea renovar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/renovarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                if(e.success)
                {
                    redirect("misproyectos","");
                }
            }).fail(function(e){

            });
        }
    });

    $('body').on('click','.finalizar', function(){
        if(confirm('Desea finalizar este proyecto?')) {
            var idProyecto = $(this).attr('value');
            $.ajax({
                url: 'emprendedor/finalizarproyecto',
                data: {idProyecto: idProyecto},
                method: "get",
                dataType: "json"
            }).done(function(e){
                redirect("misproyectos","");
            }).fail(function(e){

            });
        }
    });

    function redirect(uri,attr) {
        pathArray = location.href.split( '/' );
        protocol = pathArray[0];
        host = pathArray[2];
        if(host.includes(".org")){
            if(attr==""){
                url = protocol + '//' + host + '/' + uri;
            }
            else{
                url = protocol + '//' + host + '/' + uri + '/' + attr;
            }
        }
        else {
            if(attr==""){
                url = protocol + '//' + host + '/hazquesuceda/' + uri;
            }
            else{
                url = protocol + '//' + host + '/hazquesuceda/' + uri + '/' + attr;
            }
        }
        window.location.href = url;
    }

});<|endoftext|>


<commit_before>import React from 'react'
import Component from '../core/Component'
import ReactPlaceholder from 'react-placeholder'
import {
  TextBlock,
  MediaBlock,
  TextRow,
  RectShape,
  RoundShape
} from 'react-placeholder/lib/placeholders'
import marked from 'marked'
import URL from 'url-parse'
import { Data } from 'react-chunky'

export default class Text extends Component {
  constructor(props) {
    super(props)
    this.state = { ...this.state, loading: true, selectedLanguage: null }
  }

  componentDidMount() {
    super.componentDidMount()
    Data.Cache.retrieveCachedItem('selectedLanguage')
      .then(lang => {
        this.setState({ selectedLanguage: lang })
      })
      .catch(() => {
        return
      })
    this.loadContent()
  }

  parseUrl(source) {
    const ref = new URL(source)
    const type = ref.protocol.slice(0, -1).toLowerCase()
    const fullPath = `${ref.hostname}${ref.pathname ? ref.pathname : ''}`

    switch (type) {
      case 'local':
        return `${this.isDesktop ? '../../../../' : '/'}assets/text/${
          this.state.selectedLanguage ? this.state.selectedLanguage : ''
        }/${fullPath}.md`
      case 'github':
        return `https://raw.githubusercontent.com/${fullPath}.md`
      case 'dropbox':
        return `https://dl.dropboxusercontent.com/s/${fullPath}.md?raw=1&dl=1`
      case 'https':
      case 'http':
        return source
      default:
    }
  }

  loadFromUrl(url) {
    return fetch(url)
      .then(response => response.text())
      .then(markdown => marked(markdown, {}))
  }

  loadContent() {
    const source =
      this.props.source === 'text' ? this.props.textSource : this.props.source
    const url = this.parseUrl(source)

    if (!url) {
      return
    }

    this.loadFromUrl(url)
      .then(text => {
        this.setState({ loading: false, text })
      })
      .catch(error => {
        this.setState({ error })
      })
  }

  get placeholder() {
    return (

        <RectShape color="#CFD8DC" style={{ height: 40, marginBottom: 10 }} />
        <TextBlock rows={7} color="#ECEFF1" />

    )
  }

  renderComponentContent({ titleColor, textColor }) {
    const className = `text`
    return (

    )
  }

  renderComponent() {
    this.loadContent()
    return (

        <ReactPlaceholder
          showLoadingAnimation
          rows={7}
          ready={!this.state.loading}
          customPlaceholder={this.placeholder}
        >
          {this.renderComponentContent({
            titleColor: '#263238',
            textColor: '#455A64'
          })}
        </ReactPlaceholder>

    )
  }
}
<commit_msg>smarter text<commit_after>import React from 'react'
import Component from '../core/Component'
import ReactPlaceholder from 'react-placeholder'
import {
  TextBlock,
  MediaBlock,
  TextRow,
  RectShape,
  RoundShape
} from 'react-placeholder/lib/placeholders'
import marked from 'marked'
import URL from 'url-parse'
import { Data } from 'react-chunky'

export default class Text extends Component {
  constructor(props) {
    super(props)
    this.state = { ...this.state, loading: true, selectedLanguage: null }
  }

  componentDidMount() {
    super.componentDidMount()
    Data.Cache.retrieveCachedItem('selectedLanguage')
      .then(lang => {
        this.setState({ selectedLanguage: lang })
      })
      .catch(() => {
        return
      })
    this.loadContent()
  }

  parseUrl(source) {
    const ref = new URL(source)
    const type = ref.protocol.slice(0, -1).toLowerCase()
    const fullPath = `${ref.hostname}${ref.pathname ? ref.pathname : ''}`

    switch (type) {
      case 'local':
        return `${this.isDesktop ? '../../../../' : '/'}assets/text/${
          this.state.selectedLanguage ? this.state.selectedLanguage : ''
        }/${fullPath}.md`
      case 'github':
        return `https://raw.githubusercontent.com/${fullPath}.md`
      case 'dropbox':
        return `https://dl.dropboxusercontent.com/s/${fullPath}.md?raw=1&dl=1`
      case 'https':
      case 'http':
        return source
      default:
    }
  }

  loadFromUrl(url) {
    const translatedUrl = this.state.selectedLanguage
      ? url.replace('/text/', `/text/${this.state.selectedLanguage}/`)
      : url
    return fetch(translatedUrl)
      .then(response => response.text())
      .then(markdown => marked(markdown, {}))
  }

  loadContent() {
    const source =
      this.props.source === 'text' ? this.props.textSource : this.props.source
    const url = this.parseUrl(source)

    if (!url) {
      return
    }

    this.loadFromUrl(url)
      .then(text => {
        this.setState({ loading: false, text })
      })
      .catch(error => {
        this.setState({ error })
      })
  }

  get placeholder() {
    return (

        <RectShape color="#CFD8DC" style={{ height: 40, marginBottom: 10 }} />
        <TextBlock rows={7} color="#ECEFF1" />

    )
  }

  renderComponentContent({ titleColor, textColor }) {
    const className = `text`
    return (

    )
  }

  renderComponent() {
    this.loadContent()
    return (

        <ReactPlaceholder
          showLoadingAnimation
          rows={7}
          ready={!this.state.loading}
          customPlaceholder={this.placeholder}
        >
          {this.renderComponentContent({
            titleColor: '#263238',
            textColor: '#455A64'
          })}
        </ReactPlaceholder>

    )
  }
}
<|endoftext|>


<commit_before>import * as d3 from 'd3';
import { utilRebind } from '../../util/rebind';
import { t } from '../../util/locale';
import { actionReverse } from '../../actions';
import { osmOneWayTags } from '../../osm';
import { svgIcon } from '../../svg';

export { uiFieldCheck as uiFieldDefaultCheck };
export { uiFieldCheck as uiFieldOnewayCheck };

export function uiFieldCheck(field, context) {
    var dispatch = d3.dispatch('change'),
        options = field.strings && field.strings.options,
        values = [],
        texts = [],
        input = d3.select(null),
        text = d3.select(null),
        label = d3.select(null),
        reverser = d3.select(null),
        impliedYes,
        entityId,
        value;

    if (options) {
        for (var k in options) {
            values.push(k === 'undefined' ? undefined : k);
            texts.push(field.t('options.' + k, { 'default': options[k] }));
        }
    } else {
        values = [undefined, 'yes'];
        texts = [t('inspector.unknown'), t('inspector.check.yes')];
        if (field.type !== 'defaultCheck') {
            values.push('no');
            texts.push(t('inspector.check.no'));
        }
    }

    // Checks tags to see whether an undefined value is "Assumed to be Yes"
    function checkImpliedYes() {
        impliedYes = (field.id === 'oneway_yes');

        // hack: pretend `oneway` field is a `oneway_yes` field
        // where implied oneway tag exists (e.g. `junction=roundabout`) #2220, #1841
        if (field.id === 'oneway') {
            var entity = context.entity(entityId);
            for (var key in entity.tags) {
                if (key in osmOneWayTags && (entity.tags[key] in osmOneWayTags[key])) {
                    impliedYes = true;
                    texts[0] = t('presets.fields.oneway_yes.options.undefined');
                    break;
                }
            }
        }
    }

    function reverserHidden() {
        if (!d3.select('div.inspector-hover').empty()) return true;
        return !(value === 'yes' || (impliedYes && !value));
    }

    function reverserSetText(selection) {
        if (reverserHidden()) return selection;

        var entity = context.entity(entityId),
            first = entity.first(),
            last = entity.isClosed() ? entity.nodes[entity.nodes.length - 2] : entity.last(),
            pseudoDirection = first < last,
            icon = pseudoDirection ? '#icon-forward' : '#icon-backward';

        selection.selectAll('.reverser-span')
            .text(t('inspector.check.reverser'))
            .call(svgIcon(icon, 'inline'));

        return selection;
    }

    var check = function(selection) {
        checkImpliedYes();
        selection.classed('checkselect', 'true');

        label = selection.selectAll('.preset-input-wrap')
            .data([0]);

        var enter = label.enter()
            .append('label')
            .attr('class', 'preset-input-wrap');

        enter
            .append('input')
            .property('indeterminate', field.type !== 'defaultCheck')
            .attr('type', 'checkbox')
            .attr('id', 'preset-input-' + field.id);

        enter
            .append('span')
            .text(texts[0])
            .attr('class', 'value');

        if (field.type === 'onewayCheck') {
            enter
                .append('a')
                .attr('id', 'preset-input-' + field.id + '-reverser')
                .attr('class', 'reverser button' + (reverserHidden() ? ' hide' : ''))
                .attr('href', '#')
                .append('span')
                .attr('class', 'reverser-span');
        }

        label = label.merge(enter);
        input = label.selectAll('input');
        text = label.selectAll('span.value');
        reverser = label.selectAll('.reverser');

        input
            .on('click', function() {
                var t = {};
                t[field.key] = values[(values.indexOf(value) + 1) % values.length];
                dispatch.call('change', this, t);
                d3.event.stopPropagation();
            });

        reverser
            .call(reverserSetText)
            .on('click', function() {
                d3.event.preventDefault();
                d3.event.stopPropagation();
                context.perform(
                    actionReverse(entityId),
                    t('operations.reverse.annotation')
                );
                d3.select(this)
                    .call(reverserSetText);
            });
    };

    check.entity = function(_) {
        if (!arguments.length) return context.hasEntity(entityId);
        entityId = _.id;
        return check;
    };

    check.tags = function(tags) {
        checkImpliedYes();
        value = tags[field.key];

        input
            .property('indeterminate', field.type !== 'defaultCheck' && !value)
            .property('checked', value === 'yes');

        text
            .text(texts[values.indexOf(value)]);

        label
            .classed('set', !!value);

        reverser
            .classed('hide', reverserHidden())
            .call(reverserSetText);
    };

    check.focus = function() {
        input.node().focus();
    };

    return utilRebind(check, dispatch, 'on');
}
<commit_msg>Support 1 and -1 in onewayCheck field (closes #3910)<commit_after>import * as d3 from 'd3';
import { utilRebind } from '../../util/rebind';
import { t } from '../../util/locale';
import { actionReverse } from '../../actions';
import { osmOneWayTags } from '../../osm';
import { svgIcon } from '../../svg';

export { uiFieldCheck as uiFieldDefaultCheck };
export { uiFieldCheck as uiFieldOnewayCheck };

export function uiFieldCheck(field, context) {
    var dispatch = d3.dispatch('change'),
        options = field.strings && field.strings.options,
        values = [],
        texts = [],
        input = d3.select(null),
        text = d3.select(null),
        label = d3.select(null),
        reverser = d3.select(null),
        impliedYes,
        entityId,
        value;

    if (options) {
        for (var k in options) {
            values.push(k === 'undefined' ? undefined : k);
            texts.push(field.t('options.' + k, { 'default': options[k] }));
        }
    } else {
        values = [undefined, 'yes'];
        texts = [t('inspector.unknown'), t('inspector.check.yes')];
        if (field.type !== 'defaultCheck') {
            values.push('no');
            texts.push(t('inspector.check.no'));
        }
    }

    // Checks tags to see whether an undefined value is "Assumed to be Yes"
    function checkImpliedYes() {
        impliedYes = (field.id === 'oneway_yes');

        // hack: pretend `oneway` field is a `oneway_yes` field
        // where implied oneway tag exists (e.g. `junction=roundabout`) #2220, #1841
        if (field.id === 'oneway') {
            var entity = context.entity(entityId);
            for (var key in entity.tags) {
                if (key in osmOneWayTags && (entity.tags[key] in osmOneWayTags[key])) {
                    impliedYes = true;
                    texts[0] = t('presets.fields.oneway_yes.options.undefined');
                    break;
                }
            }
        }
    }

    function reverserHidden() {
        if (!d3.select('div.inspector-hover').empty()) return true;
        return !(value === 'yes' || (impliedYes && !value));
    }

    function reverserSetText(selection) {
        if (reverserHidden()) return selection;

        var entity = context.entity(entityId),
            first = entity.first(),
            last = entity.isClosed() ? entity.nodes[entity.nodes.length - 2] : entity.last(),
            pseudoDirection = first < last,
            icon = pseudoDirection ? '#icon-forward' : '#icon-backward';

        selection.selectAll('.reverser-span')
            .text(t('inspector.check.reverser'))
            .call(svgIcon(icon, 'inline'));

        return selection;
    }

    var check = function(selection) {
        checkImpliedYes();
        selection.classed('checkselect', 'true');

        label = selection.selectAll('.preset-input-wrap')
            .data([0]);

        var enter = label.enter()
            .append('label')
            .attr('class', 'preset-input-wrap');

        enter
            .append('input')
            .property('indeterminate', field.type !== 'defaultCheck')
            .attr('type', 'checkbox')
            .attr('id', 'preset-input-' + field.id);

        enter
            .append('span')
            .text(texts[0])
            .attr('class', 'value');

        if (field.type === 'onewayCheck') {
            enter
                .append('a')
                .attr('id', 'preset-input-' + field.id + '-reverser')
                .attr('class', 'reverser button' + (reverserHidden() ? ' hide' : ''))
                .attr('href', '#')
                .append('span')
                .attr('class', 'reverser-span');
        }

        label = label.merge(enter);
        input = label.selectAll('input');
        text = label.selectAll('span.value');
        reverser = label.selectAll('.reverser');

        input
            .on('click', function() {
                var t = {};
                t[field.key] = values[(values.indexOf(value) + 1) % values.length];
                dispatch.call('change', this, t);
                d3.event.stopPropagation();
            });

        reverser
            .call(reverserSetText)
            .on('click', function() {
                d3.event.preventDefault();
                d3.event.stopPropagation();
                context.perform(
                    actionReverse(entityId),
                    t('operations.reverse.annotation')
                );
                d3.select(this)
                    .call(reverserSetText);
            });
    };

    check.entity = function(_) {
        if (!arguments.length) return context.hasEntity(entityId);
        entityId = _.id;
        return check;
    };

    check.tags = function(tags) {
        checkImpliedYes();
        value = tags[field.key] && tags[field.key].toLowerCase();

        if (field.type === 'onewayCheck' && (value === '1' || value === '-1')) {
            value = 'yes';
        }

        input
            .property('indeterminate', field.type !== 'defaultCheck' && !value)
            .property('checked', value === 'yes');

        text
            .text(texts[values.indexOf(value)]);

        label
            .classed('set', !!value);

        reverser
            .classed('hide', reverserHidden())
            .call(reverserSetText);
    };

    check.focus = function() {
        input.node().focus();
    };

    return utilRebind(check, dispatch, 'on');
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import getConfig from 'next/config'
import {translate} from 'react-i18next'

import VectorDownload from '../downloads/vector'

const {publicRuntimeConfig: {
  GEODATA_API_URL
}} = getConfig()

class ServiceResource extends React.Component {
  static propTypes = {
    resource: PropTypes.shape({
      serviceType: PropTypes.string.isRequired,
      href: PropTypes.string.isRequired,
      features: PropTypes.arrayOf(PropTypes.shape({
        name: PropTypes.string.isRequired,
        available: PropTypes.bool.isRequired
      })).isRequired
    }).isRequired,

    setPreview: PropTypes.func.isRequired,
    t: PropTypes.func.isRequired
  }

  setPreview = feature => {
    const {resource, setPreview} = this.props

    setPreview(
      `/wfs/${resource.serviceId}/${feature.name}`,
      feature.name
    )
  }

  renderFeature(feature) {
    const {resource, setPreview} = this.props

    const url = `${GEODATA_API_URL}/wfs/${resource.serviceId}/${feature.name}`

    return (
      <VectorDownload
        key={feature.name}
        name={feature.name}
        url={url}
        available={feature.available}
        setPreview={() => setPreview(url, feature.name)}
      />
    )
  }

  render() {
    const {resource, t} = this.props

    return (

{t(`downloads.services.${resource.serviceType}`)}

{resource.href}

          {resource.features.map(
            feature => this.renderFeature(feature)
          )}

    )
  }
}

export default translate('dataset')(ServiceResource)
<commit_msg>Fix wfs preview and download<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import getConfig from 'next/config'
import {translate} from 'react-i18next'

import VectorDownload from '../downloads/vector'

const {publicRuntimeConfig: {
  GEODATA_API_URL
}} = getConfig()

class ServiceResource extends React.Component {
  static propTypes = {
    resource: PropTypes.shape({
      serviceType: PropTypes.string.isRequired,
      href: PropTypes.string.isRequired,
      features: PropTypes.arrayOf(PropTypes.shape({
        typeName: PropTypes.string.isRequired,
        available: PropTypes.bool.isRequired,
        name: PropTypes.string
      })).isRequired
    }).isRequired,

    setPreview: PropTypes.func.isRequired,
    t: PropTypes.func.isRequired
  }

  renderFeature(feature) {
    const {resource, setPreview} = this.props

    const url = `${GEODATA_API_URL}/services/${resource.serviceId}/feature-types/${feature.name}/download`

    return (
      <VectorDownload
        key={feature.typeName}
        name={feature.typeName}
        url={url}
        available={feature.available}
        setPreview={() => setPreview(url, feature.typeName)}
      />
    )
  }

  render() {
    const {resource, t} = this.props

    return (

{t(`downloads.services.${resource.serviceType}`)}

{resource.href}

          {resource.features.map(
            feature => this.renderFeature(feature)
          )}

    )
  }
}

export default translate('dataset')(ServiceResource)
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule InteractionManager
 * @flow
 */
'use strict';

var ErrorUtils = require('ErrorUtils');
var EventEmitter = require('EventEmitter');
var Set = require('Set');

var invariant = require('invariant');
var keyMirror = require('keyMirror');
var setImmediate = require('setImmediate');

var _emitter = new EventEmitter();
var _interactionSet = new Set();
var _addInteractionSet = new Set();
var _deleteInteractionSet = new Set();
var _nextUpdateHandle = null;
var _queue = [];
var _inc = 0;

/**
 * InteractionManager allows long-running work to be scheduled after any
 * interactions/animations have completed. In particular, this allows JavaScript
 * animations to run smoothly.
 *
 * Applications can schedule tasks to run after interactions with the following:
 *
 * ```
 * InteractionManager.runAfterInteractions(() => {
 *   // ...long-running synchronous task...
 * });
 * ```
 *
 * Compare this to other scheduling alternatives:
 *
 * - requestAnimationFrame(): for code that animates a view over time.
 * - setImmediate/setTimeout(): run code later, note this may delay animations.
 * - runAfterInteractions(): run code later, without delaying active animations.
 *
 * The touch handling system considers one or more active touches to be an
 * 'interaction' and will delay `runAfterInteractions()` callbacks until all
 * touches have ended or been cancelled.
 *
 * InteractionManager also allows applications to register animations by
 * creating an interaction 'handle' on animation start, and clearing it upon
 * completion:
 *
 * ```
 * var handle = InteractionManager.createInteractionHandle();
 * // run animation... (`runAfterInteractions` tasks are queued)
 * // later, on animation completion:
 * InteractionManager.clearInteractionHandle(handle);
 * // queued tasks run if all handles were cleared
 * ```
 */
var InteractionManager = {
  Events: keyMirror({
    interactionStart: true,
    interactionComplete: true,
  }),

  /**
   * Schedule a function to run after all interactions have completed.
   */
  runAfterInteractions(callback: Function) {
    invariant(
      typeof callback === 'function',
      'Must specify a function to schedule.'
    );
    scheduleUpdate();
    _queue.push(callback);
  },

  /**
   * Notify manager that an interaction has started.
   */
  createInteractionHandle(): number {
    scheduleUpdate();
    var handle = ++_inc;
    _addInteractionSet.add(handle);
    return handle;
  },

  /**
   * Notify manager that an interaction has completed.
   */
  clearInteractionHandle(handle: number) {
    invariant(
      !!handle,
      'Must provide a handle to clear.'
    );
    scheduleUpdate();
    _addInteractionSet.delete(handle);
    _deleteInteractionSet.add(handle);
  },

  addListener: _emitter.addListener.bind(_emitter),
};

/**
 * Schedule an asynchronous update to the interaction state.
 */
function scheduleUpdate() {
  if (!_nextUpdateHandle) {
    _nextUpdateHandle = setImmediate(processUpdate);
  }
}

/**
 * Notify listeners, process queue, etc
 */
function processUpdate() {
  var interactionCount = _interactionSet.size;
  _addInteractionSet.forEach(handle =>
    _interactionSet.add(handle)
  );
  _deleteInteractionSet.forEach(handle =>
    _interactionSet.delete(handle)
  );
  var nextInteractionCount = _interactionSet.size;

  if (interactionCount !== 0 && nextInteractionCount === 0) {
    // transition from 1+ --> 0 interactions
    _emitter.emit(InteractionManager.Events.interactionComplete);
  } else if (interactionCount === 0 && nextInteractionCount !== 0) {
    // transition from 0 --> 1+ interactions
    _emitter.emit(InteractionManager.Events.interactionStart);
  }

  // process the queue regardless of a transition
  if (nextInteractionCount === 0) {
    _queue.forEach(callback => {
      ErrorUtils.applyWithGuard(callback);
    });
    _queue = [];
  }
  _nextUpdateHandle = null;
  _addInteractionSet.clear();
  _deleteInteractionSet.clear();
}

module.exports = InteractionManager;
<commit_msg>React Native: Fix InteractionManager Race Condition<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule InteractionManager
 * @flow
 */
'use strict';

var ErrorUtils = require('ErrorUtils');
var EventEmitter = require('EventEmitter');
var Set = require('Set');

var invariant = require('invariant');
var keyMirror = require('keyMirror');
var setImmediate = require('setImmediate');

var _emitter = new EventEmitter();
var _interactionSet = new Set();
var _addInteractionSet = new Set();
var _deleteInteractionSet = new Set();
var _nextUpdateHandle = null;
var _queue = [];
var _inc = 0;

/**
 * InteractionManager allows long-running work to be scheduled after any
 * interactions/animations have completed. In particular, this allows JavaScript
 * animations to run smoothly.
 *
 * Applications can schedule tasks to run after interactions with the following:
 *
 * ```
 * InteractionManager.runAfterInteractions(() => {
 *   // ...long-running synchronous task...
 * });
 * ```
 *
 * Compare this to other scheduling alternatives:
 *
 * - requestAnimationFrame(): for code that animates a view over time.
 * - setImmediate/setTimeout(): run code later, note this may delay animations.
 * - runAfterInteractions(): run code later, without delaying active animations.
 *
 * The touch handling system considers one or more active touches to be an
 * 'interaction' and will delay `runAfterInteractions()` callbacks until all
 * touches have ended or been cancelled.
 *
 * InteractionManager also allows applications to register animations by
 * creating an interaction 'handle' on animation start, and clearing it upon
 * completion:
 *
 * ```
 * var handle = InteractionManager.createInteractionHandle();
 * // run animation... (`runAfterInteractions` tasks are queued)
 * // later, on animation completion:
 * InteractionManager.clearInteractionHandle(handle);
 * // queued tasks run if all handles were cleared
 * ```
 */
var InteractionManager = {
  Events: keyMirror({
    interactionStart: true,
    interactionComplete: true,
  }),

  /**
   * Schedule a function to run after all interactions have completed.
   */
  runAfterInteractions(callback: Function) {
    invariant(
      typeof callback === 'function',
      'Must specify a function to schedule.'
    );
    scheduleUpdate();
    _queue.push(callback);
  },

  /**
   * Notify manager that an interaction has started.
   */
  createInteractionHandle(): number {
    scheduleUpdate();
    var handle = ++_inc;
    _addInteractionSet.add(handle);
    return handle;
  },

  /**
   * Notify manager that an interaction has completed.
   */
  clearInteractionHandle(handle: number) {
    invariant(
      !!handle,
      'Must provide a handle to clear.'
    );
    scheduleUpdate();
    _addInteractionSet.delete(handle);
    _deleteInteractionSet.add(handle);
  },

  addListener: _emitter.addListener.bind(_emitter),
};

/**
 * Schedule an asynchronous update to the interaction state.
 */
function scheduleUpdate() {
  if (!_nextUpdateHandle) {
    _nextUpdateHandle = setImmediate(processUpdate);
  }
}

/**
 * Notify listeners, process queue, etc
 */
function processUpdate() {
  _nextUpdateHandle = null;

  var interactionCount = _interactionSet.size;
  _addInteractionSet.forEach(handle =>
    _interactionSet.add(handle)
  );
  _deleteInteractionSet.forEach(handle =>
    _interactionSet.delete(handle)
  );
  var nextInteractionCount = _interactionSet.size;

  if (interactionCount !== 0 && nextInteractionCount === 0) {
    // transition from 1+ --> 0 interactions
    _emitter.emit(InteractionManager.Events.interactionComplete);
  } else if (interactionCount === 0 && nextInteractionCount !== 0) {
    // transition from 0 --> 1+ interactions
    _emitter.emit(InteractionManager.Events.interactionStart);
  }

  // process the queue regardless of a transition
  if (nextInteractionCount === 0) {
    var queue = _queue;
    _queue = [];
    queue.forEach(callback => {
      ErrorUtils.applyWithGuard(callback);
    });
  }

  _addInteractionSet.clear();
  _deleteInteractionSet.clear();
}

module.exports = InteractionManager;
<|endoftext|>


<commit_before>/**
 * Copyright 2015, Yahoo Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var React = require('react');
var objectAssign = require('object-assign');
var hoistNonReactStatics = require('hoist-non-react-statics');

function createComponent(Component, stores, getStateFromStores, customContextTypes) {
    var componentName = Component.displayName || Component.name;
    var componentContextTypes = objectAssign({
        getStore: React.PropTypes.func.isRequired
    }, customContextTypes);
    var StoreConnector = React.createClass({
        displayName: componentName + 'StoreConnector',
        contextTypes: componentContextTypes,
        getInitialState: function getInitialState() {
            return this.getStateFromStores();
        },
        componentDidMount: function componentDidMount() {
            stores.forEach(function storesEach(Store) {
                this.context.getStore(Store).addChangeListener(this._onStoreChange);
            }, this);
        },
        componentWillUnmount: function componentWillUnmount() {
            stores.forEach(function storesEach(Store) {
                this.context.getStore(Store).removeChangeListener(this._onStoreChange);
            }, this);
        },
        getStateFromStores: function () {
            if ('function' !== typeof getStateFromStores) {
                //@TODO remove this branch in next minor
                if ('production' !== process.env.NODE_ENV) {
                    console.warn('Using connectToStores with a state getter ' +
                        'map has been deprecated. Please use the new API as ' +
                        'documented at ' +
                        'http://fluxible.io/api/addons/connectToStores.html');
                }
                var state = {};
                Object.keys(getStateFromStores).forEach(function (storeName) {
                    var stateGetter = getStateFromStores[storeName];
                    var store = this.context.getStore(storeName);
                    objectAssign(state, stateGetter(store, this.props));
                }, this);
                return state;
            }
            // @TODO remove merged context and pass only context to state getter
            //      in next minor version
            var storeInstances = {};
            var context = this.context;
            stores.forEach(function (store) {
                var storeName = store.storeName || store.name || store;
                if ('production' !== process.env.NODE_ENV) {
                    Object.defineProperty(storeInstances, storeName, {
                        get: function () {
                            console.warn(componentName + '\'s connectToStores ' +
                                'state getter is trying to access ' + storeName +
                                '. connectToStore no longer passes the ' +
                                'stores to the state getter. The state getter ' +
                                'signature is now (context, props) and you ' +
                                'should access the store using ' +
                                '`context.getStore(' + storeName + ')`. See ' +
                                'https://github.com/yahoo/fluxible/pull/124 ' +
                                'for more details on this change.');
                            return context.getStore(store);
                        }
                    });
                } else {
                    storeInstances[storeName] = this.context.getStore(store);
                }
            }, this);
            var mergedContext = objectAssign(storeInstances, this.context);
            return getStateFromStores(mergedContext, this.props);

            // @TODO just do this in next minor version
            //return getStateFromStores(this.context, this.props);
        },
        _onStoreChange: function onStoreChange() {
            if (this.isMounted()) {
                this.setState(this.getStateFromStores());
            }
        },
        render: function render() {
            return React.createElement(Component, objectAssign({}, this.props, this.state));
        }
    });

    hoistNonReactStatics(StoreConnector, Component);

    return StoreConnector;
}

/**
 * Registers change listeners and retrieves state from stores using the `getStateFromStores`
 * method. Concept provided by Dan Abramov via
 * https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
 *
 * Example:
 *   connectToStores(Component, [FooStore], {
 *       FooStore: function (store, props) {
 *           return {
 *               foo: store.getFoo()
 *           }
 *       }
 *   })
 *
 * Also supports the decorator pattern:
 *   @connectToStores([FooStore],  {
 *       FooStore: function (store, props) {
 *           return {
 *               foo: store.getFoo()
 *           }
 *       }
 *   })
 *   class ConnectedComponent extends React.Component {
 *       render() {
 *           return <div/>;
 *       }
 *   }
 *
 * @method connectToStores
 * @param {React.Component} [Component] component to pass state as props to.
 * @param {array} stores List of stores to listen for changes
 * @param {function} getStateFromStores function that receives all stores and should return
 *      the full state object. Receives `stores` hash and component `props` as arguments
 * @returns {React.Component} or {Function} if using decorator pattern
 */
module.exports = function connectToStores(Component, stores, getStateFromStores) {
    // support decorator pattern
    if (arguments.length === 2) {
        stores = arguments[0];
        getStateFromStores = arguments[1];
        return function connectToStoresDecorator(ComponentToDecorate) {
            return createComponent(ComponentToDecorate, stores, getStateFromStores);
        };
    }

    return createComponent.apply(null, arguments);
};
<commit_msg>fixes calling stateGetter when component receives new props<commit_after>/**
 * Copyright 2015, Yahoo Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var React = require('react');
var objectAssign = require('object-assign');
var hoistNonReactStatics = require('hoist-non-react-statics');

function createComponent(Component, stores, getStateFromStores, customContextTypes) {
    var componentName = Component.displayName || Component.name;
    var componentContextTypes = objectAssign({
        getStore: React.PropTypes.func.isRequired
    }, customContextTypes);
    var StoreConnector = React.createClass({
        displayName: componentName + 'StoreConnector',
        contextTypes: componentContextTypes,
        getInitialState: function getInitialState() {
            return this.getStateFromStores();
        },
        componentDidMount: function componentDidMount() {
            stores.forEach(function storesEach(Store) {
                this.context.getStore(Store).addChangeListener(this._onStoreChange);
            }, this);
        },
        componentWillUnmount: function componentWillUnmount() {
            stores.forEach(function storesEach(Store) {
                this.context.getStore(Store).removeChangeListener(this._onStoreChange);
            }, this);
        },
        componentWillReceiveProps: function componentWillReceiveProps(nextProps){
            this.setState(this.getStateFromStores(nextProps));
        },
        getStateFromStores: function (props) {
            props = props || this.props;
            if ('function' !== typeof getStateFromStores) {
                //@TODO remove this branch in next minor
                if ('production' !== process.env.NODE_ENV) {
                    console.warn('Using connectToStores with a state getter ' +
                        'map has been deprecated. Please use the new API as ' +
                        'documented at ' +
                        'http://fluxible.io/api/addons/connectToStores.html');
                }
                var state = {};
                Object.keys(getStateFromStores).forEach(function (storeName) {
                    var stateGetter = getStateFromStores[storeName];
                    var store = this.context.getStore(storeName);
                    objectAssign(state, stateGetter(store, props));
                }, this);
                return state;
            }
            // @TODO remove merged context and pass only context to state getter
            //      in next minor version
            var storeInstances = {};
            var context = this.context;
            stores.forEach(function (store) {
                var storeName = store.storeName || store.name || store;
                if ('production' !== process.env.NODE_ENV) {
                    Object.defineProperty(storeInstances, storeName, {
                        get: function () {
                            console.warn(componentName + '\'s connectToStores ' +
                                'state getter is trying to access ' + storeName +
                                '. connectToStore no longer passes the ' +
                                'stores to the state getter. The state getter ' +
                                'signature is now (context, props) and you ' +
                                'should access the store using ' +
                                '`context.getStore(' + storeName + ')`. See ' +
                                'https://github.com/yahoo/fluxible/pull/124 ' +
                                'for more details on this change.');
                            return context.getStore(store);
                        }
                    });
                } else {
                    storeInstances[storeName] = this.context.getStore(store);
                }
            }, this);
            var mergedContext = objectAssign(storeInstances, this.context);
            return getStateFromStores(mergedContext, props);

            // @TODO just do this in next minor version
            //return getStateFromStores(this.context, props);
        },
        _onStoreChange: function onStoreChange() {
            if (this.isMounted()) {
                this.setState(this.getStateFromStores());
            }
        },
        render: function render() {
            return React.createElement(Component, objectAssign({}, this.props, this.state));
        }
    });

    hoistNonReactStatics(StoreConnector, Component);

    return StoreConnector;
}

/**
 * Registers change listeners and retrieves state from stores using the `getStateFromStores`
 * method. Concept provided by Dan Abramov via
 * https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
 *
 * Example:
 *   connectToStores(Component, [FooStore], {
 *       FooStore: function (store, props) {
 *           return {
 *               foo: store.getFoo()
 *           }
 *       }
 *   })
 *
 * Also supports the decorator pattern:
 *   @connectToStores([FooStore],  {
 *       FooStore: function (store, props) {
 *           return {
 *               foo: store.getFoo()
 *           }
 *       }
 *   })
 *   class ConnectedComponent extends React.Component {
 *       render() {
 *           return <div/>;
 *       }
 *   }
 *
 * @method connectToStores
 * @param {React.Component} [Component] component to pass state as props to.
 * @param {array} stores List of stores to listen for changes
 * @param {function} getStateFromStores function that receives all stores and should return
 *      the full state object. Receives `stores` hash and component `props` as arguments
 * @returns {React.Component} or {Function} if using decorator pattern
 */
module.exports = function connectToStores(Component, stores, getStateFromStores) {
    // support decorator pattern
    if (arguments.length === 2) {
        stores = arguments[0];
        getStateFromStores = arguments[1];
        return function connectToStoresDecorator(ComponentToDecorate) {
            return createComponent(ComponentToDecorate, stores, getStateFromStores);
        };
    }

    return createComponent.apply(null, arguments);
};
<|endoftext|>


<commit_before>import io from 'socket.io-client';

function presenceConnector(presenceUrl, joinRoomCallback) {
    this._socket = io.connect(presenceUrl, {'forceNew': true});
    this._socket.on('connect', () => {
        this._socket.emit('client-get-partner', 'client');
    });
    this._socket.on('server-join-room', (roomId) => {
        joinRoomCallback(roomId);
    });
    this.disconnect = function() {
        this._socket.disconnect();
    }
    this.reconnect = function() {
        this._socket.connect();
    }
};

module.exports = presenceConnector;
<commit_msg>Replace hardcoded string with cookie variable in presenceConnector<commit_after>import io from 'socket.io-client';

function presenceConnector(presenceUrl, joinRoomCallback) {
    this._cookieId = 'cookie';
    this._socket = io.connect(presenceUrl, {'forceNew': true});
    this._socket.on('connect', () => {
        this._socket.emit('client-get-partner', this._cookieId);
    });
    this._socket.on('server-join-room', (roomId) => {
        joinRoomCallback(roomId);
    });
    this.disconnect = function() {
        this._socket.disconnect();
    }
    this.reconnect = function() {
        this._socket.connect();
    }
};

module.exports = presenceConnector;
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const http = require('http');

const request = require('../common/request');
const common = require('../common/common');

let config;

if (process.env.NODE_ENV === "local") {
	config = require('../config/local.json');
} else {
	config = require('../config/prod.json');
}

app.use(bodyParser.json());

app.use(express.static('public'));

function makeMunicipalRequest(mlsID, mortID) {
	const body = {
		mlsID,
		mortID
	};
	const {
		domain,
		port
	} = config.hostnames.mun;
	return request.makeRequest(domain, port, '/mun/appraisal', 'POST', body);
}

function makeInsuranceRequest(mlsID, mortID) {
	const body = {
		mortID,
		mlsID,
		appraiseValue: Math.floor(Math.random() * 500000 + 500000)
	}
	const {
		domain,
		port
	} = config.hostnames.insinc;
	//TODO wire up to insinc once completed
	console.log('request to /insinc/realestate', JSON.stringify(body, null, 5));
	// request.makeRequest(domain, port, '/insinc/realestate', 'POST', body);
}

function logAndRespond(request, response, endpoint, code, message) {
	common.logInfo("RE", endpoint, request, code, message);
	return response.status(code).send(message);
}

app.post('/re/appraisal', function(req, res) {
	if (!req.body.mlsID) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter mlsID');
	}

	if (!req.body.mortID) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter mortID');
	}

	if (!req.body.name) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter name');
	}

	logAndRespond(req, res, '/re/appraisal', 200);

	makeMunicipalRequest(req.body.mlsID, req.body.mortID);

	makeInsuranceRequest(req.body.mlsID, req.body.mortID);
});

app.listen(config.hostnames.re.port, function() {
	console.log(`Listening on port ${config.hostnames.re.port}!`);
});
<commit_msg>send name from re to insinc<commit_after>'use strict';

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const http = require('http');

const request = require('../common/request');
const common = require('../common/common');

let config;

if (process.env.NODE_ENV === "local") {
	config = require('../config/local.json');
} else {
	config = require('../config/prod.json');
}

app.use(bodyParser.json());

app.use(express.static('public'));

function makeMunicipalRequest(mlsID, mortID) {
	const body = {
		mlsID,
		mortID
	};
	const {
		domain,
		port
	} = config.hostnames.mun;
	return request.makeRequest(domain, port, '/mun/appraisal', 'POST', body);
}

function makeInsuranceRequest(mlsID, mortID, name) {
	const body = {
		mortID,
		mlsID,
		name,
		appraiseValue: Math.floor(Math.random() * 500000 + 500000)
	}
	const {
		domain,
		port
	} = config.hostnames.insinc;
	//TODO wire up to insinc once completed
	console.log('request to /insinc/realestate', JSON.stringify(body, null, 5));
	// request.makeRequest(domain, port, '/insinc/realestate', 'POST', body);
}

function logAndRespond(request, response, endpoint, code, message) {
	common.logInfo("RE", endpoint, request, code, message);
	return response.status(code).send(message);
}

app.post('/re/appraisal', function(req, res) {
	if (!req.body.mlsID) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter mlsID');
	}

	if (!req.body.mortID) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter mortID');
	}

	if (!req.body.name) {
		return logAndRespond(req, res, '/re/appraisal', 400, 'Bad Request missing body parameter name');
	}

	logAndRespond(req, res, '/re/appraisal', 200);

	makeMunicipalRequest(req.body.mlsID, req.body.mortID);

	makeInsuranceRequest(req.body.mlsID, req.body.mortID, req.body.name);
});

app.listen(config.hostnames.re.port, function() {
	console.log(`Listening on port ${config.hostnames.re.port}!`);
});
<|endoftext|>