<commit_before>sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel"
], function (Controller, JSONModel) {
	"use strict";

	return Controller.extend("sap.f.cardsdemo.controller.Custom", {
		onInit: function () {
			this._createListModel();
			this._createAnalyticalModel();
			this._createTableModel();
		},
		_createListModel: function () {
			var oData = {
				"content": {
					"data": {
						"request": {
							"url": "./cardcontent/someitems.json"
						}
					},
					"item": {
						"icon": {
							"label": "{{icon_label}}",
							"value": "{icon}"
						},
						"title": {
							"label": "{{title_label}}",
							"value": "{Name}"
						},
						"description": {
							"label": "{{description_label}}",
							"value": "{Description}"
						}
					}
				},
				"items2": [
					{
						"title": "Test 1"
					},
					{
						"title": "Test 2"
					},
					{
						"title": "Test 3"
					}
				]
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "list");
		},
		_createAnalyticalModel: function () {
			var oData = {
				"content": {
					"chart": {
					"type": "line",
					"vizProperties": {
						"legend": {
						"visible": true
						},
						"legendGroup": {
						"layout": {
							"position": "right",
							"alignment": "center"
						}
						},
						"plotArea": {
						"dataLabel": {
							"visible": true
						},
						"window": {
							"start": "firstDataPoint",
							"end": "lastDataPoint"
						}
						},
						"title":  {
						"text": "Line chart",
						"visible": true,
						"alignment": "bottom"
						}
					},
					"measureUid": "valueAxis",
					"dimensionUid": "categoryAxis",
					"data": {
						"request": {
							"url": "./cardcontent/revenue.json"
						},
						"path": "/list"
					},
					"dimensions": [
						{
						"label": "Weeks",
						"value": "{Week}"
						}
					],
					"measures": [
						{
						"label": "Revenue",
						"value": "{Revenue}"
						},
						{
						"label": "Cost",
						"value": "{Cost}"
						}
					]
					}
				}
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "analytical");
		},
		_createTableModel: function () {
			var oData = {
				"content": {
					"data": {
						"request": {
							"url": "./cardcontent/tableitems.json"
						},
						"path": "/names"
					},
					"columns": [
						{
							"label": "First Name",
							"value": "{firstName}"
						},
						{
							"label": "Last Name",
							"value": "{lastName}"
						}
					]
				},
				modelData: [
					{ product: "Power Projector 4713", type: "Locked" },
					{ product: "Power Projector 4713", type: "LockedBy", additionalInfo: "John Doe" },
					{ product: "Power Projector 4713", type: "LockedBy" },
					{ product: "Gladiator MX", type: "Draft" },
					{ product: "Hurricane GX", type: "Unsaved" },
					{ product: "Hurricane GX", type: "UnsavedBy", additionalInfo: "John Doe" },
					{ product: "Hurricane GX", type: "UnsavedBy"},
					{ product: "Hurricane GX", type: "Unsaved" },
					{ product: "Webcam", type: "Favorite" },
					{ product: "Deskjet Super Highspeed", type: "Flagged" }
				]
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "table");
		}
    });
});<commit_msg>[INTERNAL] sap.f.Card: Cards demo is now working<commit_after>sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/model/json/JSONModel"
], function (Controller, JSONModel) {
	"use strict";

	return Controller.extend("sap.f.cardsdemo.controller.Custom", {
		onInit: function () {
			this._createListModel();
			this._createAnalyticalModel();
			this._createTableModel();
		},
		_createListModel: function () {
			var oData = {
				"content": {
					"data": {
						"request": {
							"url": "./cardcontent/someitems.json"
						}
					},
					"item": {
						"icon": {
							"label": "{{icon_label}}",
							"value": "{icon}"
						},
						"title": {
							"label": "{{title_label}}",
							"value": "{Name}"
						},
						"description": {
							"label": "{{description_label}}",
							"value": "{Description}"
						}
					}
				},
				"items2": [
					{
						"title": "Test 1"
					},
					{
						"title": "Test 2"
					},
					{
						"title": "Test 3"
					}
				]
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "list");
		},
		_createAnalyticalModel: function () {
			var oData = {
				"content": {
					"chart": {
						"chartType": "line",
						"legend": {
							"visible": true,
							"position": "right",
							"alignment": "center"
						},
						"plotArea": {
							"dataLabel": {
								"visible": true
							},
							"window": {
								"start": "firstDataPoint",
								"end": "lastDataPoint"
							}
						},
						"title": {
							"text": "Line chart",
							"visible": true,
							"alignment": "bottom"
						},
						"measureAxis": "valueAxis",
						"dimensionAxis": "categoryAxis",
						"data": {
							"request": {
								"url": "./cardcontent/revenue.json"
							},
							"path": "/list"
						},
						"dimensions": [
							{
								"label": "Weeks",
								"value": "{Week}"
							}
						],
						"measures": [
							{
								"label": "Revenue",
								"value": "{Revenue}"
							},
							{
								"label": "Cost",
								"value": "{Cost}"
							}
						]
					}
				}
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "analytical");
		},
		_createTableModel: function () {
			var oData = {
				"content": {
					"data": {
						"request": {
							"url": "./cardcontent/tableitems.json"
						},
						"path": "/names"
					},
					"columns": [
						{
							"label": "First Name",
							"value": "{firstName}"
						},
						{
							"label": "Last Name",
							"value": "{lastName}"
						}
					]
				},
				modelData: [
					{ product: "Power Projector 4713", type: "Locked" },
					{ product: "Power Projector 4713", type: "LockedBy", additionalInfo: "John Doe" },
					{ product: "Power Projector 4713", type: "LockedBy" },
					{ product: "Gladiator MX", type: "Draft" },
					{ product: "Hurricane GX", type: "Unsaved" },
					{ product: "Hurricane GX", type: "UnsavedBy", additionalInfo: "John Doe" },
					{ product: "Hurricane GX", type: "UnsavedBy"},
					{ product: "Hurricane GX", type: "Unsaved" },
					{ product: "Webcam", type: "Favorite" },
					{ product: "Deskjet Super Highspeed", type: "Flagged" }
				]
			};
			var oModel = new JSONModel();
			oModel.setData(oData);
			this.getView().setModel(oModel, "table");
		}
    });
});<|endoftext|>


<commit_before>import {PLATFORM} from 'aurelia-pal';

const originStorage = new Map();
const unknownOrigin = Object.freeze({moduleId: undefined, moduleMember: undefined});

/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*/
export class Origin {
  /**
  * The id of the module from which the item originated.
  */
  moduleId: string;
  /**
  * The member name of the export on the module object from which the item originated.
  */
  moduleMember: string;

  /**
  * Creates an instance of Origin metadata.
  * @param moduleId The id of the module from which the item originated.
  * @param moduleMember The member name of the export on the module object from which the item originated.
  */
  constructor(moduleId: string, moduleMember: string) {
    this.moduleId = moduleId;
    this.moduleMember = moduleMember;
  }

  /**
  * Get the Origin metadata for the specified function.
  * @param fn The function to inspect for Origin metadata.
  * @return Returns the Origin metadata.
  */
  static get(fn: Function): Origin {
    let origin = originStorage.get(fn);

    if (origin === undefined) {
      PLATFORM.eachModule((key, value) => {
        if (typeof value === 'object') {
          for (let name in value) {
            let exp = value[name];
            if (exp === fn) {
              originStorage.set(fn, origin = new Origin(key, name));
              return true;
            }
          }
        }

        if (value === fn) {
          originStorage.set(fn, origin = new Origin(key, 'default'));
          return true;
        }

        return false;
      });
    }

    return origin || unknownOrigin;
  }

  /**
  * Set the Origin metadata for the specified function.
  * @param fn The function to set the Origin metadata on.
  * @param fn The Origin metadata to store on the function.
  * @return Returns the Origin metadata.
  */
  static set(fn: Function, origin: Origin): void {
    originStorage.set(fn, origin);
  }
}
<commit_msg>fix(metadata): IE cross origin frame Access Denied on Window['frameElement'] in Origin.get<commit_after>import {PLATFORM} from 'aurelia-pal';

const originStorage = new Map();
const unknownOrigin = Object.freeze({moduleId: undefined, moduleMember: undefined});

/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*/
export class Origin {
  /**
  * The id of the module from which the item originated.
  */
  moduleId: string;
  /**
  * The member name of the export on the module object from which the item originated.
  */
  moduleMember: string;

  /**
  * Creates an instance of Origin metadata.
  * @param moduleId The id of the module from which the item originated.
  * @param moduleMember The member name of the export on the module object from which the item originated.
  */
  constructor(moduleId: string, moduleMember: string) {
    this.moduleId = moduleId;
    this.moduleMember = moduleMember;
  }

  /**
  * Get the Origin metadata for the specified function.
  * @param fn The function to inspect for Origin metadata.
  * @return Returns the Origin metadata.
  */
  static get(fn: Function): Origin {
    let origin = originStorage.get(fn);

    if (origin === undefined) {
      PLATFORM.eachModule((key, value) => {
        if (typeof value === 'object') {
          for (let name in value) {
            try {
              let exp = value[name];
              if (exp === fn) {
                originStorage.set(fn, origin = new Origin(key, name));
                return true;
              }
            } catch (e) {
              // IE11 in cross origin frame fails when accessing Window['frameElement'] with Access Denied script error.
              // Window gets exported from webpack buildin/global.js.
            }
          }
        }

        if (value === fn) {
          originStorage.set(fn, origin = new Origin(key, 'default'));
          return true;
        }

        return false;
      });
    }

    return origin || unknownOrigin;
  }

  /**
  * Set the Origin metadata for the specified function.
  * @param fn The function to set the Origin metadata on.
  * @param fn The Origin metadata to store on the function.
  * @return Returns the Origin metadata.
  */
  static set(fn: Function, origin: Origin): void {
    originStorage.set(fn, origin);
  }
}
<|endoftext|>


<commit_before>// SSO login, register modal iframe
// --------------------------------

(function(){

	$( document ).ready(function(){

		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		} else {
			window.amnestySSO.init = false;
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\

\

BECOME AN AMNESTY DECODER
\

 By registering you'll be able to see your progress and participate in the forum. If you'd prefer you can skip registration.
\

\

\
					<button class="btn-secondary--alt--md--fullwidth btn-register login-modal" id="register-btn">REGISTER</button>\

\
					<button class="btn-secondary--alt--md--fullwidth btn-sign-in login-modal" id="login-btn">SIGN IN</button>\

\
					<button class="btn-link btn-skip-registration login-modal" id="skip-btn">Skip registration</button>\

\

\

Loading ...
\
				Loading\

\

\

\

\
			';

			//modal html
			$('body').append(html);

			window.amnestySSO.showImModalContent = function(loginModalMode) {

				if (loginModalMode == 'register') {
					$("#amnestySSOModal .modal-title").html('Register');
				} else if (loginModalMode == 'login') {
					$("#amnestySSOModal .modal-title").html('Login');
				} else {
					$("#amnestySSOModal .modal-title").html('');
				}

				if (loginModalMode == 'register' || loginModalMode == 'login') {
					$("#amnestySSOModal .option").hide();

					var iframeLink = {
						'login' : window.amnestySSO.imServerUrl + '/login/modal',
						'register': window.amnestySSO.imServerUrl + '/register/modal'
					}
					//link IM's login form with modal's content
					$("#amnestySSOModal .loading").show();
					$('#amnestySSOModal iframe').show();
					$('#amnestySSOModal iframe').attr('src', iframeLink[loginModalMode]);
				} else {
					//show register, login, skip options again
					$("#amnestySSOModal .loading").hide();
					$('#amnestySSOModal iframe').hide();
					$("#amnestySSOModal .option").show();
				}
			};

			$('#amnestySSOModal iframe').load(function(){
			      $("#amnestySSOModal .loading").hide();
			});

			$('#amnestySSOModal #register-btn').click(function(){
				//update for later redirect to tutorial page
				window.amnestySSO.loginModalMode = 'register';

				//set bigger height
				$('#amnestySSOModal .modal-body iframe').height('80vh');

				window.amnestySSO.showImModalContent('register');
			});

			$('#amnestySSOModal #login-btn').click(function(){
				window.amnestySSO.showImModalContent('login');
			});

			$('#amnestySSOModal #skip-btn').click(function(){
				$('#amnestySSOModal').modal('hide');
			});

			//wait IM login form to return token
			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== window.amnestySSO.imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						//if user hasn't tried tutorial yet then show it
						if (!window.pybossaTutorial.isSkippedOrComplete()) {
							window.location = '/project/decode-darfur/tutorial';
						}
						//other case, just reload current window
						else {
							location.reload();
						}
					})
					.fail(function(data){
        				console.log('failed');
        				console.log(data);
        			})
        			.always(function(){
        			});
			}
		}
	});

})();

// Bootstrap login/register modal if query string has ?modal=login/register/all
// ---
(function(){
	$( document ).ready(function(){

		window.amnestySSO.bootstrapLoginRegister = function() {
			//only show modal when user is not logged in
			if ( window.amnestySSO.isAnonymous != 'True') {
				return;
			}

			//not valid mode
			var validModalMode = ['login', 'register', 'all'];
			if ( !( validModalMode.indexOf(window.amnestySSO.loginModalMode) > -1 ) ) {
				return;
			}

			switch (window.amnestySSO.loginModalMode) {
				case 'login' :
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('login');

					break;

				case 'register' :
					//set bigger height
					$('#amnestySSOModal .modal-body iframe').height('80vh');

					//show register modal
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('register');

					break;

				case 'all' :
					$('#amnestySSOModal').modal('show');

					break;
			}
		}

		window.amnestySSO.bootstrapLoginRegister();
	});
})();
// Flag modal
// ----------
(function(){
	$( document ).ready(function(){
		//we rename flagModal to flagModal2 so external "data-target='#flagModal'" element can't open that modal directly
		var html = '\

\

\

\

\

\

Comment on this area
\
	          <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\
	          <textarea class="form-control" rows="3" id="flag-content" placeholder="Tell us if you see something in this area that our researchers and other Decoders should take a closer look at."></textarea>\

\

\
	            <button type="button" class="btn-primary--md--fullwidth btn-flag" id="flag-btn">\
	              \
	              Flag this section\
	            </button>\

\
	            Your comment will appear in the Amnesty Decoders community forum\

\

\

\

Thanks for your comments and suggestions
\

\
	          View comment on forum\

\

\
	          <button type="button" class="btn btn-primary" data-dismiss="modal" id="flag-btn-close">Close</button>\

\

\

\

\

\
	\
			';

		$('body').append(html);

		$("[data-target='#flagModal']").click(function(){
			if(!window.isInTutorial){
				//only logged-in user can comment
				if (window.amnestySSO.isAnonymous != 'True') {
					$('#flagModal2').modal('show');
				}
				//show register/login modal for new user
				else {
					window.amnestySSO.loginModalMode = 'all';
					var flagFormDescriptionHtml = '\

Sign in to help us make the most out of your hard work.
\

Signing in allows you to participate in discussions and allows us to give you credit for your work and make the best use of the data you provide.
\
					\
					';
					$('#amnestySSOModal .description').html(flagFormDescriptionHtml);
					window.amnestySSO.showImModalContent('all');
					$('#amnestySSOModal').modal('show');
				}
			}
		});

		$(".btn-flag").click(function(){
			var comment = $('#flag-content').val();
			comment = comment.trim();

			if (!comment) {
				$("#flagModal2 .message").html("Please enter your comment");
				return;
			}

			//loading button
			$('.btn-flag .glyphicon-refresh').show();

			$.get('/discourse/create-comment', {
					"comment": comment,
					"task-id": pybossa.task.id
				})
				.done(function(data){
					$('#flagModal2 .view-comment-on-forum').attr('href', data.topic_url);
					//clear error message
					$("#flagModal2 .message").html("");
					//hide comment input
					$('#flagModal2 .submit-comment-container').hide();
					//show forum link
					$('#flagModal2 .after-submit-sucess').show();
				})
				.fail(function(data){
					var message = "There is error";
					if (data && data.responseText) {
						var error = $.parseJSON(data.responseText);
						if (error && error.errors) {
							message = error.errors.join('
');
						}
					}
					$("#flagModal2 .message").html(message);
				})
				.always(function() {
					//remove loading button
					$('.btn-flag .glyphicon-refresh').hide();
				});
		});

		$('#flagModal2').on('hidden.bs.modal', function (e) {
			//reset
			//show comment input
			$('#flagModal2 .submit-comment-container').show();
			$('#flag-content').val("")
			//hide forum link
			$('#flagModal2 .after-submit-sucess').hide();
			//clear error message
			$("#flagModal2 .message").html("");
		});

		$('#flagModal2').on('show.bs.modal', function (e) {
			$('.btn-flag .glyphicon-refresh').hide();
		});
	});

})();<commit_msg>update style for flag modal text<commit_after>// SSO login, register modal iframe
// --------------------------------

(function(){

	$( document ).ready(function(){

		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		} else {
			window.amnestySSO.init = false;
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\

\

BECOME AN AMNESTY DECODER
\

 By registering you'll be able to see your progress and participate in the forum. If you'd prefer you can skip registration.
\

\

\
					<button class="btn-secondary--alt--md--fullwidth btn-register login-modal" id="register-btn">REGISTER</button>\

\
					<button class="btn-secondary--alt--md--fullwidth btn-sign-in login-modal" id="login-btn">SIGN IN</button>\

\
					<button class="btn-link btn-skip-registration login-modal" id="skip-btn">Skip registration</button>\

\

\

Loading ...
\
				Loading\

\

\

\

\
			';

			//modal html
			$('body').append(html);

			window.amnestySSO.showImModalContent = function(loginModalMode) {

				if (loginModalMode == 'register') {
					$("#amnestySSOModal .modal-title").html('Register');
				} else if (loginModalMode == 'login') {
					$("#amnestySSOModal .modal-title").html('Login');
				} else {
					$("#amnestySSOModal .modal-title").html('');
				}

				if (loginModalMode == 'register' || loginModalMode == 'login') {
					$("#amnestySSOModal .option").hide();

					var iframeLink = {
						'login' : window.amnestySSO.imServerUrl + '/login/modal',
						'register': window.amnestySSO.imServerUrl + '/register/modal'
					}
					//link IM's login form with modal's content
					$("#amnestySSOModal .loading").show();
					$('#amnestySSOModal iframe').show();
					$('#amnestySSOModal iframe').attr('src', iframeLink[loginModalMode]);
				} else {
					//show register, login, skip options again
					$("#amnestySSOModal .loading").hide();
					$('#amnestySSOModal iframe').hide();
					$("#amnestySSOModal .option").show();
				}
			};

			$('#amnestySSOModal iframe').load(function(){
			      $("#amnestySSOModal .loading").hide();
			});

			$('#amnestySSOModal #register-btn').click(function(){
				//update for later redirect to tutorial page
				window.amnestySSO.loginModalMode = 'register';

				//set bigger height
				$('#amnestySSOModal .modal-body iframe').height('80vh');

				window.amnestySSO.showImModalContent('register');
			});

			$('#amnestySSOModal #login-btn').click(function(){
				window.amnestySSO.showImModalContent('login');
			});

			$('#amnestySSOModal #skip-btn').click(function(){
				$('#amnestySSOModal').modal('hide');
			});

			//wait IM login form to return token
			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== window.amnestySSO.imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						//if user hasn't tried tutorial yet then show it
						if (!window.pybossaTutorial.isSkippedOrComplete()) {
							window.location = '/project/decode-darfur/tutorial';
						}
						//other case, just reload current window
						else {
							location.reload();
						}
					})
					.fail(function(data){
        				console.log('failed');
        				console.log(data);
        			})
        			.always(function(){
        			});
			}
		}
	});

})();

// Bootstrap login/register modal if query string has ?modal=login/register/all
// ---
(function(){
	$( document ).ready(function(){

		window.amnestySSO.bootstrapLoginRegister = function() {
			//only show modal when user is not logged in
			if ( window.amnestySSO.isAnonymous != 'True') {
				return;
			}

			//not valid mode
			var validModalMode = ['login', 'register', 'all'];
			if ( !( validModalMode.indexOf(window.amnestySSO.loginModalMode) > -1 ) ) {
				return;
			}

			switch (window.amnestySSO.loginModalMode) {
				case 'login' :
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('login');

					break;

				case 'register' :
					//set bigger height
					$('#amnestySSOModal .modal-body iframe').height('80vh');

					//show register modal
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('register');

					break;

				case 'all' :
					$('#amnestySSOModal').modal('show');

					break;
			}
		}

		window.amnestySSO.bootstrapLoginRegister();
	});
})();
// Flag modal
// ----------
(function(){
	$( document ).ready(function(){
		//we rename flagModal to flagModal2 so external "data-target='#flagModal'" element can't open that modal directly
		var html = '\

\

\

\

\

\

Comment on this area
\
	          <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\
	          <textarea class="form-control" rows="3" id="flag-content" placeholder="Tell us if you see something in this area that our researchers and other Decoders should take a closer look at."></textarea>\

\

\
	            <button type="button" class="btn-primary--md--fullwidth btn-flag" id="flag-btn">\
	              \
	              Flag this section\
	            </button>\

\
	            Your comment will appear in the Amnesty Decoders community forum\

\

\

\

Thanks for your comments and suggestions
\

\
	          View comment on forum\

\

\
	          <button type="button" class="btn btn-primary" data-dismiss="modal" id="flag-btn-close">Close</button>\

\

\

\

\

\
	\
			';

		$('body').append(html);

		$("[data-target='#flagModal']").click(function(){
			if(!window.isInTutorial){
				//only logged-in user can comment
				if (window.amnestySSO.isAnonymous != 'True') {
					$('#flagModal2').modal('show');
				}
				//show register/login modal for new user
				else {
					window.amnestySSO.loginModalMode = 'all';
					var flagFormDescriptionHtml = '\

Sign in to help us make the most out of your hard work.
\

Signing in allows you to participate in discussions and allows us to give you credit for your work and make the best use of the data you provide.
\
					\
					';
					$('#amnestySSOModal .description').html(flagFormDescriptionHtml);
					window.amnestySSO.showImModalContent('all');
					$('#amnestySSOModal').modal('show');
				}
			}
		});

		$(".btn-flag").click(function(){
			var comment = $('#flag-content').val();
			comment = comment.trim();

			if (!comment) {
				$("#flagModal2 .message").html("Please enter your comment");
				return;
			}

			//loading button
			$('.btn-flag .glyphicon-refresh').show();

			$.get('/discourse/create-comment', {
					"comment": comment,
					"task-id": pybossa.task.id
				})
				.done(function(data){
					$('#flagModal2 .view-comment-on-forum').attr('href', data.topic_url);
					//clear error message
					$("#flagModal2 .message").html("");
					//hide comment input
					$('#flagModal2 .submit-comment-container').hide();
					//show forum link
					$('#flagModal2 .after-submit-sucess').show();
				})
				.fail(function(data){
					var message = "There is error";
					if (data && data.responseText) {
						var error = $.parseJSON(data.responseText);
						if (error && error.errors) {
							message = error.errors.join('
');
						}
					}
					$("#flagModal2 .message").html(message);
				})
				.always(function() {
					//remove loading button
					$('.btn-flag .glyphicon-refresh').hide();
				});
		});

		$('#flagModal2').on('hidden.bs.modal', function (e) {
			//reset
			//show comment input
			$('#flagModal2 .submit-comment-container').show();
			$('#flag-content').val("")
			//hide forum link
			$('#flagModal2 .after-submit-sucess').hide();
			//clear error message
			$("#flagModal2 .message").html("");
		});

		$('#flagModal2').on('show.bs.modal', function (e) {
			$('.btn-flag .glyphicon-refresh').hide();
		});
	});

})();<|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>'use strict';

const logger = require('../logger');
const ClientMetrics = require('../client-metrics');
const joi = require('joi');
const { clientMetricsSchema, clientRegisterSchema } = require('./metrics-schema');
const { catchLogAndSendErrorResponse } = require('./route-utils');

module.exports = function (app, config) {
    const {
        clientMetricsStore,
        clientInstanceStore,
        clientApplicationsStore,
    } = config.stores;

    const metrics = new ClientMetrics(clientMetricsStore);

    app.get('/client/seen-toggles', (req, res) => {
        const seenAppToggles = metrics.getAppsWithToggles();
        res.json(seenAppToggles);
    });

    app.get('/client/seen-apps', (req, res) => {
        const seenApps = metrics.getSeenAppsPerToggle();
        clientApplicationsStore.getApplications()
            .then(toLookup)
            .then(metaData => {
                Object.keys(seenApps).forEach(key => {
                    seenApps[key] = seenApps[key].map(entry => {
                        if (metaData[entry.appName]) {
                            return Object.assign({}, entry, metaData[entry.appName]);
                        }
                        return entry;
                    });
                });
                res.json(seenApps);
            });
    });

    app.get('/client/metrics/feature-toggles', (req, res) => {
        res.json(metrics.getTogglesMetrics());
    });

    app.get('/client/metrics/feature-toggles/:name', (req, res) => {
        const name = req.params.name;
        const data = metrics.getTogglesMetrics();
        const lastHour = data.lastHour[name] || {};
        const lastMinute = data.lastMinute[name] || {};
        res.json({
            lastHour,
            lastMinute,
        });
    });

    app.post('/client/metrics', (req, res) => {
        const data = req.body;
        const clientIp = req.ip;

        joi.validate(data, clientMetricsSchema, (err, cleaned) => {
            if (err) {
                return res.status(400).json(err);
            }

            clientMetricsStore
                .insert(cleaned)
                .then(() => clientInstanceStore.insert({
                    appName: cleaned.appName,
                    instanceId: cleaned.instanceId,
                    clientIp,
                }))
                .catch(err => logger.error('failed to store metrics', err));

            res.status(202).end();
        });
    });

    app.post('/client/register', (req, res) => {
        const data = req.body;

        joi.validate(data, clientRegisterSchema, (err, clientRegistration) => {
            if (err) {
                return res.status(400).json(err);
            }

            clientRegistration.clientIp = req.ip;

            clientApplicationsStore
                .upsert(clientRegistration)
                .then(() => clientInstanceStore.insert(clientRegistration))
                .then(() => logger.info(`New client registered with
                            appName=${clientRegistration.appName} and instanceId=${clientRegistration.instanceId}`))
                .catch(err => logger.error('failed to register client', err));

            res.status(202).end();
        });
    });

    app.post('/client/applications/:appName', (req, res) => {
        const input = Object.assign({}, req.body, {
            appName: req.params.appName,
        });
        clientApplicationsStore
            .upsert(input)
            .then(() => res.status(202).end())
            .catch((e) => {
                logger.error(e);
                res.status(500).end();
            });
    });

    function toLookup (metaData) {
        return metaData.reduce((result, entry) => {
            result[entry.appName] = entry;
            return result;
        }, {});
    }

    app.get('/client/applications/', (req, res) => {
        clientApplicationsStore
            .getApplications(req.query)
            .then(applications => res.json({ applications }))
            .catch(err => catchLogAndSendErrorResponse(err, res));
    });

    app.get('/client/applications/:appName', (req, res) => {
        const appName = req.params.appName;
        const seenToggles = metrics.getSeenTogglesByAppName(appName);

        Promise.all([
            clientApplicationsStore.getApplication(appName),
            clientInstanceStore.getByAppName(appName),
        ])
        .then(([application, instances]) => {
            const appDetails = {
                appName: application.appName,
                createdAt: application.createdAt,
                description: application.description,
                url: application.url,
                color: application.color,
                icon: application.icon,
                strategies: application.strategies,
                instances,
                seenToggles,
                links: {
                    self: `/api/client/applications/${application.appName}`,
                },
            };
            res.json(appDetails);
        })
        .catch(err => catchLogAndSendErrorResponse(err, res));
    });
};
<commit_msg>check toggles and strategies in clientapps<commit_after>'use strict';

const logger = require('../logger');
const ClientMetrics = require('../client-metrics');
const joi = require('joi');
const { clientMetricsSchema, clientRegisterSchema } = require('./metrics-schema');
const { catchLogAndSendErrorResponse } = require('./route-utils');

module.exports = function (app, config) {
    const {
        clientMetricsStore,
        clientInstanceStore,
        clientApplicationsStore,
        strategyStore,
        featureToggleStore,
    } = config.stores;

    const metrics = new ClientMetrics(clientMetricsStore);

    app.get('/client/seen-toggles', (req, res) => {
        const seenAppToggles = metrics.getAppsWithToggles();
        res.json(seenAppToggles);
    });

    app.get('/client/seen-apps', (req, res) => {
        const seenApps = metrics.getSeenAppsPerToggle();
        clientApplicationsStore.getApplications()
            .then(toLookup)
            .then(metaData => {
                Object.keys(seenApps).forEach(key => {
                    seenApps[key] = seenApps[key].map(entry => {
                        if (metaData[entry.appName]) {
                            return Object.assign({}, entry, metaData[entry.appName]);
                        }
                        return entry;
                    });
                });
                res.json(seenApps);
            });
    });

    app.get('/client/metrics/feature-toggles', (req, res) => {
        res.json(metrics.getTogglesMetrics());
    });

    app.get('/client/metrics/feature-toggles/:name', (req, res) => {
        const name = req.params.name;
        const data = metrics.getTogglesMetrics();
        const lastHour = data.lastHour[name] || {};
        const lastMinute = data.lastMinute[name] || {};
        res.json({
            lastHour,
            lastMinute,
        });
    });

    app.post('/client/metrics', (req, res) => {
        const data = req.body;
        const clientIp = req.ip;

        joi.validate(data, clientMetricsSchema, (err, cleaned) => {
            if (err) {
                return res.status(400).json(err);
            }

            clientMetricsStore
                .insert(cleaned)
                .then(() => clientInstanceStore.insert({
                    appName: cleaned.appName,
                    instanceId: cleaned.instanceId,
                    clientIp,
                }))
                .catch(err => logger.error('failed to store metrics', err));

            res.status(202).end();
        });
    });

    app.post('/client/register', (req, res) => {
        const data = req.body;

        joi.validate(data, clientRegisterSchema, (err, clientRegistration) => {
            if (err) {
                return res.status(400).json(err);
            }

            clientRegistration.clientIp = req.ip;

            clientApplicationsStore
                .upsert(clientRegistration)
                .then(() => clientInstanceStore.insert(clientRegistration))
                .then(() => logger.info(`New client registered with
                            appName=${clientRegistration.appName} and instanceId=${clientRegistration.instanceId}`))
                .catch(err => logger.error('failed to register client', err));

            res.status(202).end();
        });
    });

    app.post('/client/applications/:appName', (req, res) => {
        const input = Object.assign({}, req.body, {
            appName: req.params.appName,
        });
        clientApplicationsStore
            .upsert(input)
            .then(() => res.status(202).end())
            .catch((e) => {
                logger.error(e);
                res.status(500).end();
            });
    });

    function toLookup (metaData) {
        return metaData.reduce((result, entry) => {
            result[entry.appName] = entry;
            return result;
        }, {});
    }

    app.get('/client/applications/', (req, res) => {
        clientApplicationsStore
            .getApplications(req.query)
            .then(applications => res.json({ applications }))
            .catch(err => catchLogAndSendErrorResponse(err, res));
    });

    app.get('/client/applications/:appName', (req, res) => {
        const appName = req.params.appName;
        const seenToggles = metrics.getSeenTogglesByAppName(appName);

        Promise.all([
            clientApplicationsStore.getApplication(appName),
            clientInstanceStore.getByAppName(appName),
            strategyStore.getStrategies(),
            featureToggleStore.getFeatures(),
        ])
        .then(([application, instances, strategies, features]) => {
            const appDetails = {
                appName: application.appName,
                createdAt: application.createdAt,
                description: application.description,
                url: application.url,
                color: application.color,
                icon: application.icon,
                strategies: application.strategies.map(name => {
                    const found = strategies.find((feature) => feature.name === name);
                    if (found) {
                        return found;
                    }
                    return { name, notFound: true  };
                }),
                instances,
                seenToggles: seenToggles.map(name => {
                    const found = features.find((feature) => feature.name === name);
                    if (found) {
                        return found;
                    }
                    return { name, notFound: true };
                }),
                links: {
                    self: `/api/client/applications/${application.appName}`,
                },
            };
            res.json(appDetails);
        })
        .catch(err => catchLogAndSendErrorResponse(err, res));
    });
};
<|endoftext|>


<commit_before>/*jslint esversion: 6, node: true, nomen: true, unparam: true */
// TODO: enhance readability using res.format() https://expressjs.com/en/4x/api.html#res.format

'use strict';

var debug = require('debug')('myBus:rv2');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var http_auth = require('../module/http_auth.js');
var sqlEscape = require('../module/sqlEscape.js');

// initial DB object
var mysql = require('promise-mysql');
var sql_config = require('../sql_config');
var db = mysql.createPool(sql_config.db);

router.get('/route', (req, res) => {
    debug(JSON.stringify(req.query));
    if (req.query.route) {
        var query = `SELECT * FROM \`Bus_stop\` WHERE \`route\`=${Number(req.query.route)}`;
        db.query(query).then((rows, field)=>{
            res.send(JSON.stringify(rows));
        }, (err)=>{
            throw err;
        });
    } else {
        var err = new Error('Too few arguments');
        err.status = 400;
        throw err;
    }
});

router.get('/bus', (req, res) => {
    res.set("Connection", "close");
    res.send('this is bus');
});

router.post('/register', (req, res) => {
    http_auth.register(req.body.uuid, req.body.password, req.body.phone).then((user) => {
        res.send(JSON.stringify(user));
    }, (err) => {
        res.status(err.code);
        res.json({
            description: err.message
        });
    });
});

router.get('/busArrival', (req, res) => {
    if (req.query.route === undefined) {
        res.status(400);
        res.json({
            description: 'Too few arguments (missing route)'
        });
    } else {
        var query = `SELECT * FROM \`Bus_arrival\` WHERE \`route\` = ${req.query.route} `;
        if (req.query.is_reverse !== undefined) {
            query += `AND \`is_reverse\` = ${sqlEscape.escapeBoolean(req.query.is_reverse)}`;
        }
        db.query(query).then((rows) => {
            if (rows.length === 0) {
                res.send(JSON.stringify(null));
            } else {
                res.send(JSON.stringify(rows));
            }
        });
    }
});

router.get('/lineStatus', (req, res) => {
    var query = '';

    if (req.query.verbose === undefined || sqlEscape.escapeBoolean(req.query.verbose) === true) {
        query += 'SELECT * ';
    } else {
        query += 'SELECT `closestStop` ';
    }

    query += 'FROM `Bus_status` ';

    if (req.query.route && req.query.is_reverse) {
        query += `WHERE \`route\` = ${db.escape(req.query.route)} AND \`is_reverse\` = ${sqlEscape.escapeBoolean(req.query.is_reverse)} `;
    } else {
        res.status(400);
        res.json({
            description: 'Too few arguments'
        });
    }

    if (req.query.sn) {
        query += `ORDER BY ABS(closestStop-${req.query.sn})`;
    }

    debug(query);
    res.set("Connection", "close");
    db.query(query).then((rows) => {
        if (rows.length === 0) {
            res.send(JSON.stringify(null));
        } else if (req.query.sn === undefined) {
            res.send(JSON.stringify(rows));
        } else {
            res.send(JSON.stringify(rows[0].closestStop));
        }
    });
});

router.post('/reservation',
    passport.authenticate('standard',{session: false}),
    (req, res) => {
        // INSERT INTO `Reservation_List`(`UUID`, `route`, `is_reverse`, `from_sn`, `to_sn`) VALUES ('B397A7F7',160,false,1,3)
        try {
            sqlEscape.escapeParam(req.body,
                'route', {type: 'number'},
                //'is_reverse', {optional: true},     // actually not needed anymore
                'from_sn', {type: 'number'},
                'to_sn', {type: 'number'}
            );
        } catch (err) {
            res.status(406);
            res.json({
                description: err.message
            });
        }

        var query = `INSERT INTO \`Reservation_List\`(\`UID\`, \`route\`, \`is_reverse\`, \`from_sn\`, \`to_sn\`) ` +
                    `VALUES ('${req.user.UUID}',${req.body.route},${(req.body.from_sn<req.body.to_sn)},${req.body.from_sn},${req.body.to_sn})`;
        db.query(query).then((rows, field) => {
            res.json({description: "Register OK"});
        }, (err) => {
            if (err.code.includes('ER_DUP_ENTRY')) {
                debug(`Reservation with id ${req.user.UUID} already exist, update`);
                //UPDATE `Reservation_List` SET `route`=160,`is_reverse`=true,`from_sn`=5,`to_sn`=3 WHERE `UID`='b397a7f7'
                query = `UPDATE \`Reservation_List\` SET \`route\`=${req.body.route},\`is_reverse\`=${(req.body.from_sn<req.body.to_sn)},\`from_sn\`=${req.body.from_sn},\`to_sn\`=${req.body.to_sn} WHERE \`UID\`='${req.user.UUID}'`;
                db.query(query).then(() => {
                    res.json({description: "Register UPDATE OK"});
                });
            } else if (err.code.includes('ER_NO_REFERENCED_ROW')) {
                res.status(400);
                res.json({
                    description: 'Error you are not registered yet'
                });
            } else {
                res.status(500);
                res.json({description: 'Unknown Error'});
            }
        });
});

router.post('/environment', (req, res) => {
    // INSERT INTO `Weather` (`route`, `sn`, `is_reverse`, `humidity`, `temperature`, `timestamp`) VALUES ('160', '2', '0', '50', '32', CURRENT_TIMESTAMP);
    // UPDATE `Weather` SET `route`='160',`sn`='2',`is_reverse`='true',`humidity`='50',`temperature`='32',`timestamp`=NOW() WHERE `route`='160' AND `sn`='2' AND `is_reverse`='true'
    var query = '';

    if (req.body.route === undefined || req.body.sn === undefined || req.body.is_reverse === undefined) {
        res.status(400);
        res.json({
            description: 'Too few arguments (route, sn, is_reverse are required)'
        });
        return;
    }

    query = `UPDATE \`Weather\` SET ` +
            `${req.body.humidity ? `\`humidity\`='${req.body.humidity}',` : ''}` +
            `${req.body.temp ? `\`temperature\`='${req.body.temp}',` : ''}` +
            `\`timestamp\`=CURRENT_TIMESTAMP ` +
            `WHERE \`route\`='${req.body.route}' AND \`sn\`='${req.body.sn}' AND \`is_reverse\`='${sqlEscape.escapeBoolean(req.body.sn)}'`;

    db.query(query).then((result) => {
        if (result.affectedRows <= 0) {
            query = `INSERT INTO \`Weather\` (\`route\`, \`sn\`, \`is_reverse\`, \`timestamp\`, ` +
                    `${req.body.humidity ? '`humidity`, ': ''}` +
                    `${req.body.tempe ? '`temperature`, ': ''}` +
                    `) VALUES ('${req.body.route}', '${req.body.sn}', '${req.body.is_reverse}', CURRENT_TIMESTAMP, ` +
                    `${req.body.humidity ? `'${req.body.humidity}', ` : ''}` +
                    `${req.body.temp ? `'${req.body.temp}'` : ''}` +
                    `)`;

            return db.query(query).then(() => {
                res.send('OK');
            });
        } else {
            res.send('OK');
        }
    });
});

router.get('/account/:uuid',
    passport.authenticate('standard',{session: false}),
    (req, res) => {
        if (req.params.uuid === req.user.UUID) {
            res.send(JSON.stringify(req.user));
        } else {
            debug(`User ${req.user.UUID} try to access ${req.params.uuid}'s account info'`);
            res.status(401);
            res.send('{"description":"Unauthorized"}');
        }

    }
);

module.exports = router;
<commit_msg>disable /reservation auth<commit_after>/*jslint esversion: 6, node: true, nomen: true, unparam: true */
// TODO: enhance readability using res.format() https://expressjs.com/en/4x/api.html#res.format

'use strict';

var debug = require('debug')('myBus:rv2');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var http_auth = require('../module/http_auth.js');
var sqlEscape = require('../module/sqlEscape.js');

// initial DB object
var mysql = require('promise-mysql');
var sql_config = require('../sql_config');
var db = mysql.createPool(sql_config.db);

router.get('/route', (req, res) => {
    debug(JSON.stringify(req.query));
    if (req.query.route) {
        var query = `SELECT * FROM \`Bus_stop\` WHERE \`route\`=${Number(req.query.route)}`;
        db.query(query).then((rows, field)=>{
            res.send(JSON.stringify(rows));
        }, (err)=>{
            throw err;
        });
    } else {
        var err = new Error('Too few arguments');
        err.status = 400;
        throw err;
    }
});

router.get('/bus', (req, res) => {
    res.set("Connection", "close");
    res.send('this is bus');
});

router.post('/register', (req, res) => {
    http_auth.register(req.body.uuid, req.body.password, req.body.phone).then((user) => {
        res.send(JSON.stringify(user));
    }, (err) => {
        res.status(err.code);
        res.json({
            description: err.message
        });
    });
});

router.get('/busArrival', (req, res) => {
    if (req.query.route === undefined) {
        res.status(400);
        res.json({
            description: 'Too few arguments (missing route)'
        });
    } else {
        var query = `SELECT * FROM \`Bus_arrival\` WHERE \`route\` = ${req.query.route} `;
        if (req.query.is_reverse !== undefined) {
            query += `AND \`is_reverse\` = ${sqlEscape.escapeBoolean(req.query.is_reverse)}`;
        }
        db.query(query).then((rows) => {
            if (rows.length === 0) {
                res.send(JSON.stringify(null));
            } else {
                res.send(JSON.stringify(rows));
            }
        });
    }
});

router.get('/lineStatus', (req, res) => {
    var query = '';

    if (req.query.verbose === undefined || sqlEscape.escapeBoolean(req.query.verbose) === true) {
        query += 'SELECT * ';
    } else {
        query += 'SELECT `closestStop` ';
    }

    query += 'FROM `Bus_status` ';

    if (req.query.route && req.query.is_reverse) {
        query += `WHERE \`route\` = ${db.escape(req.query.route)} AND \`is_reverse\` = ${sqlEscape.escapeBoolean(req.query.is_reverse)} `;
    } else {
        res.status(400);
        res.json({
            description: 'Too few arguments'
        });
    }

    if (req.query.sn) {
        query += `ORDER BY ABS(closestStop-${req.query.sn})`;
    }

    debug(query);
    res.set("Connection", "close");
    db.query(query).then((rows) => {
        if (rows.length === 0) {
            res.send(JSON.stringify(null));
        } else if (req.query.sn === undefined) {
            res.send(JSON.stringify(rows));
        } else {
            res.send(JSON.stringify(rows[0].closestStop));
        }
    });
});

router.post('/reservation', (req, res) => {
    // INSERT INTO `Reservation_List`(`UUID`, `route`, `is_reverse`, `from_sn`, `to_sn`) VALUES ('B397A7F7',160,false,1,3)
    try {
        sqlEscape.escapeParam(req.body,
            'route', {type: 'number'},
            //'is_reverse', {optional: true},     // actually not needed anymore
            'from_sn', {type: 'number'},
            'to_sn', {type: 'number'}
        );
    } catch (err) {
        res.status(406);
        res.json({
            description: err.message
        });
    }

    var query = `INSERT INTO \`Reservation_List\`(\`UID\`, \`route\`, \`is_reverse\`, \`from_sn\`, \`to_sn\`) ` +
                `VALUES ('${req.user.UUID}',${req.body.route},${(req.body.from_sn<req.body.to_sn)},${req.body.from_sn},${req.body.to_sn})`;
    db.query(query).then((rows, field) => {
        res.json({description: "Register OK"});
    }, (err) => {
        if (err.code.includes('ER_DUP_ENTRY')) {
            debug(`Reservation with id ${req.user.UUID} already exist, update`);
            //UPDATE `Reservation_List` SET `route`=160,`is_reverse`=true,`from_sn`=5,`to_sn`=3 WHERE `UID`='b397a7f7'
            query = `UPDATE \`Reservation_List\` SET \`route\`=${req.body.route},\`is_reverse\`=${(req.body.from_sn<req.body.to_sn)},\`from_sn\`=${req.body.from_sn},\`to_sn\`=${req.body.to_sn} WHERE \`UID\`='${req.user.UUID}'`;
            db.query(query).then(() => {
                res.json({description: "Register UPDATE OK"});
            });
        } else if (err.code.includes('ER_NO_REFERENCED_ROW')) {
            res.status(400);
            res.json({
                description: 'Error you are not registered yet'
            });
        } else {
            res.status(500);
            res.json({description: 'Unknown Error'});
        }
    });
});

router.post('/environment', (req, res) => {
    // INSERT INTO `Weather` (`route`, `sn`, `is_reverse`, `humidity`, `temperature`, `timestamp`) VALUES ('160', '2', '0', '50', '32', CURRENT_TIMESTAMP);
    // UPDATE `Weather` SET `route`='160',`sn`='2',`is_reverse`='true',`humidity`='50',`temperature`='32',`timestamp`=NOW() WHERE `route`='160' AND `sn`='2' AND `is_reverse`='true'
    var query = '';

    if (req.body.route === undefined || req.body.sn === undefined || req.body.is_reverse === undefined) {
        res.status(400);
        res.json({
            description: 'Too few arguments (route, sn, is_reverse are required)'
        });
        return;
    }

    query = `UPDATE \`Weather\` SET ` +
            `${req.body.humidity ? `\`humidity\`='${req.body.humidity}',` : ''}` +
            `${req.body.temp ? `\`temperature\`='${req.body.temp}',` : ''}` +
            `\`timestamp\`=CURRENT_TIMESTAMP ` +
            `WHERE \`route\`='${req.body.route}' AND \`sn\`='${req.body.sn}' AND \`is_reverse\`='${sqlEscape.escapeBoolean(req.body.sn)}'`;

    db.query(query).then((result) => {
        if (result.affectedRows <= 0) {
            query = `INSERT INTO \`Weather\` (\`route\`, \`sn\`, \`is_reverse\`, \`timestamp\`, ` +
                    `${req.body.humidity ? '`humidity`, ': ''}` +
                    `${req.body.tempe ? '`temperature`, ': ''}` +
                    `) VALUES ('${req.body.route}', '${req.body.sn}', '${req.body.is_reverse}', CURRENT_TIMESTAMP, ` +
                    `${req.body.humidity ? `'${req.body.humidity}', ` : ''}` +
                    `${req.body.temp ? `'${req.body.temp}'` : ''}` +
                    `)`;

            return db.query(query).then(() => {
                res.send('OK');
            });
        } else {
            res.send('OK');
        }
    });
});

router.get('/account/:uuid',
    passport.authenticate('standard',{session: false}),
    (req, res) => {
        if (req.params.uuid === req.user.UUID) {
            res.send(JSON.stringify(req.user));
        } else {
            debug(`User ${req.user.UUID} try to access ${req.params.uuid}'s account info'`);
            res.status(401);
            res.send('{"description":"Unauthorized"}');
        }

    }
);

module.exports = router;
<|endoftext|>


<commit_before>
// settings
// !!! need to change this to the right value
var gamesNeededToWin = 5;

// # partials
// __________

// set up the partials logic
Session.set('partial', 'loggedOut');
// !!!
// un-comment this line for testing faster
// Session.set('partial', 'loggedIn');

Template.partials.helpers({
  partial: function(partialName) {
    return Session.get('partial') === partialName;
  }
});

// # loggedOut
// ___________

Session.set('player', null);
// !!!
// un-comment this line for testing faster
// Session.set('player', 'x');

Template.loggedOut.events({
  'click #login-x': function(e) {
    Session.set('player', 'x');
    Session.set('partial', 'loggedIn');
  },
  'click #login-o': function(e) {
    Session.set('player', 'o');
    Session.set('partial', 'loggedIn');
  }
});

// # loggedIn
// __________

// # startButton
// _______

Template.startButton.events({
  'click .start-game' : function(e) {

    var series = Series.findOne({active: true}, {sort: {startTime: -1}});
    if (series) {
      return; // series already in progress
    }

    Meteor.apply('startSeries', [], function(error, result){
      if (error) {
        console.log('Error starting game:', error);
      }
      if (result.error) {
        console.log('Error starting game:', result.message);
      }
    });

  }
});

Template.startButton.gameInProgress = function() {
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  return !!series;
};

// # stats
// _______

Template.stats.player = function() {
  return Session.get('player');
};
Template.stats.wins = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var wins = Games.find({result: Session.get('player'), startTime: {$gt: seriesStartTime}}).count();
  return wins;
};
Template.stats.losses = function() {
  var opponent;
  if (Session.get('player') === 'x') {
    opponent = 'o';
  }
  else {
    opponent = 'x';
  }

  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var losses = Games.find({result: opponent, startTime: {$gt: seriesStartTime}}).count();
  return losses;
};
Template.stats.ties = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var ties = Games.find({result: 't', startTime: {$gt: seriesStartTime}}).count();
  return ties;
};
Template.stats.happening = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Games.find({result: false, startTime: {$gt: seriesStartTime}}).count();
};

// # newScript
// ___________

Template.newScript.events({
  'click .submit-new-script' : function(e) {
    var editor = ace.edit('aceEditor');
    var logic = editor.getValue();

    Meteor.apply('insertScript', [Session.get('player'), logic], function(error, result){

      // error in my code happened
      if (error) {
        console.log(error);
      }

      // error in user script happened
      if (result.error) {
        // !!! we should improve this by making it a notification
        // using bootstrap will be nice
        console.log('your script had an error:');
        console.log(result.message);
      }
      else {
        // success!

        // replace the text in the code editor
        editor.setValue('function selectMove(move, board){\n\t// write your code here\n\n\t// for example:\n\t// increment the weight of the middle right square by 1\n\tif (move.row === 1 && move.column === 2) {\n\t\tmove.weight = move.weight + 1;\n\t}\n}');
      }

    });
  }
});

Template.newScript.gameInProgress = function() {
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  return !!series;
};

Template.aceEditor.rendered = function() {
  var editor = ace.edit('aceEditor');
  // editor.setTheme('ace/theme/github');
  editor.setTheme('ace/theme/tomorrow_night');
  editor.getSession().setMode('ace/mode/javascript');
  editor.setHighlightActiveLine(true);
  editor.setShowPrintMargin(false);
  editor.getSession().setTabSize(2);

  editor.setOptions({
    maxLines: 20
  });

};

// # scripts
// _________

Template.scripts.events({
  'click .activate-script' : function(e) {

    Meteor.apply('activateScript', [this._id], function(error, result){

      // error in my code happened
      if (error) {
        console.log(error);
      }

    });

  }
});

Template.scripts.scripts = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Scripts.find(
    {player: Session.get('player'), timestamp: {$gt: seriesStartTime}},
    {sort: {timestamp: -1}}
  );
};
Template.scripts.count = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Scripts.find(
    {player: Session.get('player'), timestamp: {$gt: seriesStartTime}}
  ).count();
};

// # board
// _______

Session.set('winner', null);

Template.board.winner = function() {
  return Session.get('winner');
}

Template.board.rows = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var game = Games.findOne(
    {startTime: {$gt: seriesStartTime}},
    {sort:{startTime:-1}}
  );

  if (game) {
    if (game.result) {
      Session.set('winner', game.result);
    }
    else {
      Session.set('winner', null);
    }
    return game.board;
  }
};

// ties being decided a turn too earnly
// extra moves being played after a "win" is declared
<commit_msg>only show scripts for previous game<commit_after>
// settings
// !!! need to change this to the right value
var gamesNeededToWin = 5;

// # partials
// __________

// set up the partials logic
Session.set('partial', 'loggedOut');
// !!!
// un-comment this line for testing faster
// Session.set('partial', 'loggedIn');

Template.partials.helpers({
  partial: function(partialName) {
    return Session.get('partial') === partialName;
  }
});

// # loggedOut
// ___________

Session.set('player', null);
// !!!
// un-comment this line for testing faster
// Session.set('player', 'x');

Template.loggedOut.events({
  'click #login-x': function(e) {
    Session.set('player', 'x');
    Session.set('partial', 'loggedIn');
  },
  'click #login-o': function(e) {
    Session.set('player', 'o');
    Session.set('partial', 'loggedIn');
  }
});

// # loggedIn
// __________

// # startButton
// _______

Template.startButton.events({
  'click .start-game' : function(e) {

    var series = Series.findOne({active: true}, {sort: {startTime: -1}});
    if (series) {
      return; // series already in progress
    }

    Meteor.apply('startSeries', [], function(error, result){
      if (error) {
        console.log('Error starting game:', error);
      }
      if (result.error) {
        console.log('Error starting game:', result.message);
      }
    });

  }
});

Template.startButton.gameInProgress = function() {
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  return !!series;
};

// # stats
// _______

Template.stats.player = function() {
  return Session.get('player');
};
Template.stats.wins = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var wins = Games.find({result: Session.get('player'), startTime: {$gt: seriesStartTime}}).count();
  return wins;
};
Template.stats.losses = function() {
  var opponent;
  if (Session.get('player') === 'x') {
    opponent = 'o';
  }
  else {
    opponent = 'x';
  }

  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var losses = Games.find({result: opponent, startTime: {$gt: seriesStartTime}}).count();
  return losses;
};
Template.stats.ties = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var ties = Games.find({result: 't', startTime: {$gt: seriesStartTime}}).count();
  return ties;
};
Template.stats.happening = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Games.find({result: false, startTime: {$gt: seriesStartTime}}).count();
};

// # newScript
// ___________

Template.newScript.events({
  'click .submit-new-script' : function(e) {
    var editor = ace.edit('aceEditor');
    var logic = editor.getValue();

    Meteor.apply('insertScript', [Session.get('player'), logic], function(error, result){

      // error in my code happened
      if (error) {
        console.log(error);
      }

      // error in user script happened
      if (result.error) {
        // !!! we should improve this by making it a notification
        // using bootstrap will be nice
        console.log('your script had an error:');
        console.log(result.message);
      }
      else {
        // success!

        // replace the text in the code editor
        editor.setValue('function selectMove(move, board){\n\t// write your code here\n\n\t// for example:\n\t// increment the weight of the middle right square by 1\n\tif (move.row === 1 && move.column === 2) {\n\t\tmove.weight = move.weight + 1;\n\t}\n}');
      }

    });
  }
});

Template.newScript.gameInProgress = function() {
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  return !!series;
};

Template.aceEditor.rendered = function() {
  var editor = ace.edit('aceEditor');
  // editor.setTheme('ace/theme/github');
  editor.setTheme('ace/theme/tomorrow_night');
  editor.getSession().setMode('ace/mode/javascript');
  editor.setHighlightActiveLine(true);
  editor.setShowPrintMargin(false);
  editor.getSession().setTabSize(2);

  editor.setOptions({
    maxLines: 20
  });

};

// # scripts
// _________

Template.scripts.events({
  'click .activate-script' : function(e) {

    Meteor.apply('activateScript', [this._id], function(error, result){

      // error in my code happened
      if (error) {
        console.log(error);
      }

    });

  }
});

Template.scripts.scripts = function() {

  // display all the scripts for the previous game (or current game if a game is happening)
  var seriesStartTime = 0;
  var series = Series.findOne({}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Scripts.find(
    {player: Session.get('player'), timestamp: {$gt: seriesStartTime}},
    {sort: {timestamp: -1}}
  );
};
Template.scripts.count = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  return Scripts.find(
    {player: Session.get('player'), timestamp: {$gt: seriesStartTime}}
  ).count();
};

// # board
// _______

Session.set('winner', null);

Template.board.winner = function() {
  return Session.get('winner');
}

Template.board.rows = function() {
  var seriesStartTime = 0;
  var series = Series.findOne({active: true}, {sort: {startTime: -1}});
  if (series) {
    seriesStartTime = series.startTime;
  }

  var game = Games.findOne(
    {startTime: {$gt: seriesStartTime}},
    {sort:{startTime:-1}}
  );

  if (game) {
    if (game.result) {
      Session.set('winner', game.result);
    }
    else {
      Session.set('winner', null);
    }
    return game.board;
  }
};

// ties being decided a turn too earnly
// extra moves being played after a "win" is declared
<|endoftext|>


<commit_before>/**
 * Analytics Setup form.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import Button from '../../../../components/Button';
import {
	SETUP_FLOW_MODE_LEGACY,
	SETUP_FLOW_MODE_UA,
	SETUP_FLOW_MODE_GA4,
	SETUP_FLOW_MODE_GA4_TRANSITIONAL,
	MODULES_ANALYTICS,
	FORM_SETUP,
	EDIT_SCOPE,
} from '../../datastore/constants';
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import { CORE_FORMS } from '../../../../googlesitekit/datastore/forms/constants';
import { trackEvent } from '../../../../util';
import { isPermissionScopeError } from '../../../../util/errors';
import SetupFormLegacy from './SetupFormLegacy';
import SetupFormUA from './SetupFormUA';
import SetupFormGA4 from './SetupFormGA4';
import SetupFormGA4Transitional from './SetupFormGA4Transitional';
const { useSelect, useDispatch } = Data;

export default function SetupForm( { finishSetup } ) {
	const canSubmitChanges = useSelect( ( select ) =>
		select( MODULES_ANALYTICS ).canSubmitChanges()
	);
	const hasEditScope = useSelect( ( select ) =>
		select( CORE_USER ).hasScope( EDIT_SCOPE )
	);

	const autoSubmit = useSelect( ( select ) =>
		select( CORE_FORMS ).getValue( FORM_SETUP, 'autoSubmit' )
	);
	const setupFlowMode = useSelect( ( select ) =>
		select( MODULES_ANALYTICS ).getSetupFlowMode()
	);

	const { setValues } = useDispatch( CORE_FORMS );
	const { submitChanges } = useDispatch( MODULES_ANALYTICS );
	const submitForm = useCallback(
		async ( event ) => {
			event.preventDefault();

			const { error } = await submitChanges();
			if ( isPermissionScopeError( error ) ) {
				setValues( FORM_SETUP, { autoSubmit: true } );
			}

			if ( ! error ) {
				setValues( FORM_SETUP, { autoSubmit: false } );
				await trackEvent( 'analytics_setup', 'analytics_configured' );
				finishSetup();
			}
		},
		[ finishSetup, setValues, submitChanges ]
	);

	// If the user lands back on this component with autoSubmit and the edit scope,
	// resubmit the form.
	useEffect( () => {
		if ( autoSubmit && hasEditScope ) {
			submitForm( { preventDefault: () => {} } );
		}
	}, [ hasEditScope, autoSubmit, submitForm ] );

	return (
		<form
			className="googlesitekit-analytics-setup__form"
			onSubmit={ submitForm }
		>
			{ setupFlowMode === SETUP_FLOW_MODE_LEGACY && <SetupFormLegacy /> }
			{ setupFlowMode === SETUP_FLOW_MODE_UA && <SetupFormUA /> }
			{ setupFlowMode === SETUP_FLOW_MODE_GA4 && <SetupFormGA4 /> }
			{ setupFlowMode === SETUP_FLOW_MODE_GA4_TRANSITIONAL && (
				<SetupFormGA4Transitional />
			) }

				<Button disabled={ ! canSubmitChanges }>
					{ __( 'Configure Analytics', 'google-site-kit' ) }
				</Button>

		</form>
	);
}

SetupForm.propTypes = {
	finishSetup: PropTypes.func,
};

SetupForm.defaultProps = {
	finishSetup: () => {},
};
<commit_msg>Revert whitespace changes.<commit_after>/**
 * Analytics Setup form.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import Button from '../../../../components/Button';
import {
	SETUP_FLOW_MODE_LEGACY,
	SETUP_FLOW_MODE_UA,
	SETUP_FLOW_MODE_GA4,
	SETUP_FLOW_MODE_GA4_TRANSITIONAL,
	MODULES_ANALYTICS,
	FORM_SETUP,
	EDIT_SCOPE,
} from '../../datastore/constants';
import { CORE_USER } from '../../../../googlesitekit/datastore/user/constants';
import { CORE_FORMS } from '../../../../googlesitekit/datastore/forms/constants';
import { trackEvent } from '../../../../util';
import { isPermissionScopeError } from '../../../../util/errors';
import SetupFormLegacy from './SetupFormLegacy';
import SetupFormUA from './SetupFormUA';
import SetupFormGA4 from './SetupFormGA4';
import SetupFormGA4Transitional from './SetupFormGA4Transitional';
const { useSelect, useDispatch } = Data;

export default function SetupForm( { finishSetup } ) {
	const canSubmitChanges = useSelect( ( select ) =>
		select( MODULES_ANALYTICS ).canSubmitChanges()
	);
	const hasEditScope = useSelect( ( select ) =>
		select( CORE_USER ).hasScope( EDIT_SCOPE )
	);
	const autoSubmit = useSelect( ( select ) =>
		select( CORE_FORMS ).getValue( FORM_SETUP, 'autoSubmit' )
	);
	const setupFlowMode = useSelect( ( select ) =>
		select( MODULES_ANALYTICS ).getSetupFlowMode()
	);

	const { setValues } = useDispatch( CORE_FORMS );
	const { submitChanges } = useDispatch( MODULES_ANALYTICS );
	const submitForm = useCallback(
		async ( event ) => {
			event.preventDefault();
			const { error } = await submitChanges();
			if ( isPermissionScopeError( error ) ) {
				setValues( FORM_SETUP, { autoSubmit: true } );
			}
			if ( ! error ) {
				setValues( FORM_SETUP, { autoSubmit: false } );
				await trackEvent( 'analytics_setup', 'analytics_configured' );
				finishSetup();
			}
		},
		[ finishSetup, setValues, submitChanges ]
	);

	// If the user lands back on this component with autoSubmit and the edit scope,
	// resubmit the form.
	useEffect( () => {
		if ( autoSubmit && hasEditScope ) {
			submitForm( { preventDefault: () => {} } );
		}
	}, [ hasEditScope, autoSubmit, submitForm ] );

	return (
		<form
			className="googlesitekit-analytics-setup__form"
			onSubmit={ submitForm }
		>
			{ setupFlowMode === SETUP_FLOW_MODE_LEGACY && <SetupFormLegacy /> }
			{ setupFlowMode === SETUP_FLOW_MODE_UA && <SetupFormUA /> }
			{ setupFlowMode === SETUP_FLOW_MODE_GA4 && <SetupFormGA4 /> }
			{ setupFlowMode === SETUP_FLOW_MODE_GA4_TRANSITIONAL && (
				<SetupFormGA4Transitional />
			) }

				<Button disabled={ ! canSubmitChanges }>
					{ __( 'Configure Analytics', 'google-site-kit' ) }
				</Button>

		</form>
	);
}

SetupForm.propTypes = {
	finishSetup: PropTypes.func,
};

SetupForm.defaultProps = {
	finishSetup: () => {},
};
<|endoftext|>


<commit_before>var vm = require('vm');
var parseUrl = require('url').parse;
var VM_OPTIONS = {
    displayErrors: false,
    timeout: 100,
    filename: 'proxy.pac'
  };
var dateRange = require('./dateRange');
var dnsDomainIs = require('./dnsDomainIs');
var dnsDomainLevels = require('./dnsDomainLevels');
var getDnsResolve = require('./dnsResolve');
var isInNet = require('./isInNet');
var isPlainHostName = require('./isPlainHostName');
var isResolvable = require('./isResolvable');
var localHostOrDomainIs = require('./localHostOrDomainIs');
var myIpAddress = require('./myIpAddress');
var shExpMatch = require('./shExpMatch');
var timeRange = require('./timeRange');
var weekdayRange = require('./weekdayRange');

function generateFn(script, dnsResolve) {
  try {
    var fn = vm.runInNewContext(script + ';FindProxyForURL', {
      dateRange: dateRange,
      dnsDomainIs: dnsDomainIs,
      dnsDomainLevels: dnsDomainLevels,
      dnsResolve: getDnsResolve(dnsResolve),
      isInNet: isInNet,
      isPlainHostName: isPlainHostName,
      isResolvable: isResolvable,
      localHostOrDomainIs: localHostOrDomainIs,
      myIpAddress: myIpAddress,
      shExpMatch: shExpMatch,
      timeRange: timeRange,
      weekdayRange: weekdayRange
    }, VM_OPTIONS);
    return typeof fn === 'function' ? fn : null;
  } catch(e) {}
}

var DIRECT = 'DIRECT';
var directPac = function(url, host, cb) {
  cb(null, DIRECT);
};
var emptyDnsResolve = function(host, cb) {
  cb();
};
module.exports = function(script, dnsResolve) {
  var _FindProxyForURL = generateFn(script, dnsResolve) || directPac;
  if (typeof dnsResolve !== 'function') {
    dnsResolve = emptyDnsResolve;
  }
  return function FindProxyForURL(url, host, cb) {
    var result;
    dnsResolve(host,  function() {
      try {
        host = host || parseUrl(url).hostname;
        result = _FindProxyForURL(url, host);
        result = typeof result == 'string' ? result : DIRECT;
      } catch(e) {}
      if (typeof cb == 'function') {
        cb(null, result || DIRECT);
      }
    });
    return result || DIRECT;
  };
};
<commit_msg>refactor: dnsResolve<commit_after>var vm = require('vm');
var parseUrl = require('url').parse;
var VM_OPTIONS = {
    displayErrors: false,
    timeout: 100,
    filename: 'proxy.pac'
  };
var dateRange = require('./dateRange');
var dnsDomainIs = require('./dnsDomainIs');
var dnsDomainLevels = require('./dnsDomainLevels');
var getDnsResolve = require('./dnsResolve');
var isInNet = require('./isInNet');
var isPlainHostName = require('./isPlainHostName');
var isResolvable = require('./isResolvable');
var localHostOrDomainIs = require('./localHostOrDomainIs');
var myIpAddress = require('./myIpAddress');
var shExpMatch = require('./shExpMatch');
var timeRange = require('./timeRange');
var weekdayRange = require('./weekdayRange');

function generateFn(script, dnsResolve) {
  try {
    var fn = vm.runInNewContext(script + ';FindProxyForURL', {
      dateRange: dateRange,
      dnsDomainIs: dnsDomainIs,
      dnsDomainLevels: dnsDomainLevels,
      dnsResolve: getDnsResolve(dnsResolve),
      isInNet: isInNet,
      isPlainHostName: isPlainHostName,
      isResolvable: isResolvable,
      localHostOrDomainIs: localHostOrDomainIs,
      myIpAddress: myIpAddress,
      shExpMatch: shExpMatch,
      timeRange: timeRange,
      weekdayRange: weekdayRange
    }, VM_OPTIONS);
    return typeof fn === 'function' ? fn : null;
  } catch(e) {}
}

var DIRECT = 'DIRECT';
var directPac = function(url, host, cb) {
  cb(null, DIRECT);
};
var emptyDnsResolve = function(host, cb) {
  cb();
};
module.exports = function(script, dnsResolve) {
  var hasDnsResolve = /\bdnsResolve\(/.test(script);
  var _FindProxyForURL = generateFn(script, dnsResolve) || directPac;
  if (!hasDnsResolve || typeof dnsResolve !== 'function') {
    dnsResolve = emptyDnsResolve;
  }
  return function FindProxyForURL(url, host, cb) {
    var result;
    dnsResolve(host,  function() {
      try {
        host = host || parseUrl(url).hostname;
        result = _FindProxyForURL(url, host);
        result = typeof result == 'string' ? result : DIRECT;
      } catch(e) {}
      if (typeof cb == 'function') {
        cb(null, result || DIRECT);
      }
    });
    return result || DIRECT;
  };
};
<|endoftext|>


<commit_before>/* eslint { indent: 0 } */
import BaseModel from "Models/BaseModel";
import Matrix from "./Matrix";

import cloneDeep from "lodash.clonedeep";
import { slFetch } from "saylua-fetch";

const LB_FPS = 60;
const LB_MIN_TIMEOUT = 10;
const LB_LR_INTERVAL = 2;
const LB_PIECES = [[0, 1, 0, 0, // i
                    0, 1, 0, 0,
                    0, 1, 0, 0,
                    0, 1, 0, 0],

                   [0, 0, 2, 0, // j
                    0, 0, 2, 0,
                    0, 2, 2, 0,
                    0, 0, 0, 0],

                   [0, 3, 0, 0, // l
                    0, 3, 0, 0,
                    0, 3, 3, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // o
                    0, 4, 4, 0,
                    0, 4, 4, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // t
                    5, 5, 5, 0,
                    0, 5, 0, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // s
                    0, 6, 6, 0,
                    6, 6, 0, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // z
                    7, 7, 0, 0,
                    0, 7, 7, 0,
                    0, 0, 0, 0]];

// GameState
// --------------------------------------
// Keeps track of the player's current tetris state.

export default class GameState extends BaseModel {
  constructor() {
    super();
    this.gameId = document.querySelector('meta[name="arcade-game-id"]').content;
  }

  clearGameState() {
    this.frames = 0;
    this.lastDrop = 0;
    this.lastLR = 0;
    this.timeout = 800;
    this.gameOver = false;
    this.paused = false;
    this.canDrop = true;
    this.canRotate = true;
    this.canSpeed = true;
    this.keyState = {};
    this.fast = false;
    this.score = 0;
    this.gameMatrix = new Matrix(18, 10);
    this.placedPieces = new Matrix(18, 10);
    this.nextPiece = null;
    this.piece = {"matrix": new Matrix(4, 4), "r": -3, "c": 2};

    this.gameLog = [];
    this.scoreSent = false;

    clearInterval(this.timer);
  }

  start() {
    this.clearGameState();
    this.getNextPiece();

    this.startTime = new Date().getTime();
    this.timer = setInterval(this.timeStep.bind(this), 1000 / LB_FPS);
  }

  isRunning() {
    return this.timer && !(this.gameOver || this.paused);
  }

  checkGameOver() {
    // If the first row has any pieces, there is a game over.
    let matrix = this.placedPieces;
    for (let i = 0; i < matrix.width; i++) {
      if (matrix.get(0, i)) return true;
    }
    return false;
  }

  endGame() {
    this.piece = null;
    this.gameOver = true;

    let game = this;

    slFetch('/api/arcade/score/' + this.gameId + '/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        score: this.score,
        startTime: this.startTime,
        gameLog: this.gameLog,
        frames: this.frames
      })
    }).then((response) => {
      if (response.ok) {
        return response.json();
      }
      console.error('Sending score failed!'); // eslint-disable-line no-console
    }).then((json) => {
      // TODO: Actually use the response. Retry this on failure.
      game.scoreSent = true;
      game.triggerUpdate();
    });

    this.triggerUpdate();
  }

  timeStep() {
    if (!this.isRunning()) return;

    this.frames++;

    let timeout = this.timeout;
    if (this.keyState[13] || this.keyState[80]) { // Enter, p
      this.pause();
    }
    if (this.keyState[32] && this.canDrop) { // Space
      this.drop();
      this.canDrop = false;
    }
    if (!this.keyState[32]) { // Space
      this.canDrop = true;
    }
    if ((this.keyState[38] || this.keyState[87]) && this.canRotate) { // Up, w
      this.rotate();
      this.canRotate = false;
    }
    if (!(this.keyState[38] || this.keyState[87])) { // Up, w
      this.canRotate = true;
    }
    if ((this.keyState[40] || this.keyState[83]) && this.canSpeed) { // Down, s
      this.speedUp();
    }
    if (!(this.keyState[40] || this.keyState[83])) { // Down, s
      this.canSpeed = true;
    }
    if (!(this.keyState[40] || this.keyState[83])) { // Down, s
      this.speedDown();
    }
    if ((this.keyState[37] || this.keyState[65]) && this.frames - this.lastLR > LB_LR_INTERVAL) { // Left, a
      this.lastLR = this.frames;
      this.moveLeft();
    }
    if ((this.keyState[39] || this.keyState[68]) && this.frames - this.lastLR > LB_LR_INTERVAL) { // Right, d
      this.lastLR = this.frames;
      this.moveRight();
    }
    if (this.fast && this.canSpeed) {
      timeout = LB_MIN_TIMEOUT;
    }
    if ((this.frames - this.lastDrop) / LB_FPS >= timeout / 1000) {
      this.lastDrop = this.frames;
      this.movePieceDown();
      this.draw();
    }
  }

  movePieceDown() {
    let p = this.piece;
    if (!this.canSpeed && p.r > -2) {
      this.canSpeed = true;
    }
    if (this.validPlacement(p.matrix, p.r + 1, p.c)) {
      p.r++;
      return true;
    }
    // If moving down is invalid, the piece cannot fall anymore.
    this.placedPieces.addMatrix(p.matrix, p.r, p.c);
    this.canSpeed = false;

    if (this.checkGameOver()) {
      // GAME OVER.
      this.endGame();
    } else {
      this.getNextPiece();

      // Check if a line was made.
      if (this.clearLines(p.r, p.r + 4).length > 0) {
        this.score += 50;
        this.timeout -= 3;
      }
    }
    return false;
  }

  clearLines(minRow, maxRow) {
    let matrix = this.placedPieces;
    let deleted = [];

    for (let i = minRow; i < maxRow; i++) {
      let j = 0;
      while (matrix.get(i, j) && j < matrix.width) {
        j++;
      }
      if (j == matrix.width) {
        // There is a line at i.
        deleted.push(i);
      }
    }
    matrix.deleteRows(deleted);
    return deleted;
  }

  validPlacement(piece, r, c) {
    let matrix = this.placedPieces;
    for (let i = 0; i < piece.height; i++) {
      for (let j = 0; j < piece.width; j++) {
        let row = r + i;
        let col = c + j;

        if (matrix.withinBounds(row, col)) {
          // If the piece intersects another piece. Ignore ghost pieces with value 8.
          if (piece.get(i, j) && (matrix.get(row, col) && matrix.get(row, col) != 8)) {
            return false;
          }
        } else if (row >= 0 && piece.get(i, j)) {
          // If the piece goes past the sides or the bottom.
          // (don't count the top)
          return false;
        } else if ((j < 1 || j > 10) && piece.get(i, j)) {
          // If the piece goes past the sides (counting the top).
          return false;
        }
      }
    }
    return true;
  }

  getNextPiece() {
    if (!this.nextPiece) {
      this.setNextPiece();
    }
    this.piece = {"matrix": this.nextPiece, "r": -2, "c": 3};
    this.setNextPiece();
  }

  setNextPiece() {
    let i = Math.floor(Math.random() * LB_PIECES.length);
    this.nextPiece = new Matrix(4, 4, LB_PIECES[i]);
  }

  draw() {
    let matrix = cloneDeep(this.placedPieces);
    let p = this.piece;
    if (p) {
      matrix.addMatrix(p.matrix, p.r, p.c);
      // draw ghost piece
      let g = cloneDeep(p);
      for (var i = 0; i < g.length; i++) {
        if (g[i] != 0) {
          g[i] = 8;
        }
      }
      matrix.addMatrix(g.matrix, g.r + 8, g.c);
    }

    // gameMatrix is bound to a BlockGrid, which should render this.
    this.gameMatrix = matrix;

    // Make sure the component updates.
    this.triggerUpdate();
  }

  pause() {
    if (!this.timer) return;
    this.paused = !this.paused;
    this.triggerUpdate();
  }

  drop() {
    if (!this.isRunning()) return;
    while (this.movePieceDown());
    this.draw();
  }

  speedUp() {
    this.fast = true;
  }

  speedDown() {
    this.fast = false;
  }

  rotate() {
    if (!this.isRunning()) return;
    let p = cloneDeep(this.piece);
    p.matrix.rotate();
    if (this.validPlacement(p.matrix, p.r, p.c)) {
      this.piece = p;
      this.draw();
    }
  }

  moveLeft() {
    if (!this.isRunning()) return;
    let p = this.piece;
    if (this.validPlacement(p.matrix, p.r, p.c - 1)) {
      p.c--;
      this.draw();
    }
  }

  moveRight() {
    if (!this.isRunning()) return;
    let p = this.piece;
    if (this.validPlacement(p.matrix, p.r, p.c + 1)) {
      p.c++;
      this.draw();
    }
  }
}
<commit_msg>Drop ghost pieces<commit_after>/* eslint { indent: 0 } */
import BaseModel from "Models/BaseModel";
import Matrix from "./Matrix";

import cloneDeep from "lodash.clonedeep";
import { slFetch } from "saylua-fetch";

const LB_FPS = 60;
const LB_MIN_TIMEOUT = 10;
const LB_LR_INTERVAL = 2;
const LB_PIECES = [[0, 1, 0, 0, // i
                    0, 1, 0, 0,
                    0, 1, 0, 0,
                    0, 1, 0, 0],

                   [0, 0, 2, 0, // j
                    0, 0, 2, 0,
                    0, 2, 2, 0,
                    0, 0, 0, 0],

                   [0, 3, 0, 0, // l
                    0, 3, 0, 0,
                    0, 3, 3, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // o
                    0, 4, 4, 0,
                    0, 4, 4, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // t
                    5, 5, 5, 0,
                    0, 5, 0, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // s
                    0, 6, 6, 0,
                    6, 6, 0, 0,
                    0, 0, 0, 0],

                   [0, 0, 0, 0, // z
                    7, 7, 0, 0,
                    0, 7, 7, 0,
                    0, 0, 0, 0]];

// GameState
// --------------------------------------
// Keeps track of the player's current tetris state.

export default class GameState extends BaseModel {
  constructor() {
    super();
    this.gameId = document.querySelector('meta[name="arcade-game-id"]').content;
  }

  clearGameState() {
    this.frames = 0;
    this.lastDrop = 0;
    this.lastLR = 0;
    this.timeout = 800;
    this.gameOver = false;
    this.paused = false;
    this.canDrop = true;
    this.canRotate = true;
    this.canSpeed = true;
    this.keyState = {};
    this.fast = false;
    this.score = 0;
    this.gameMatrix = new Matrix(18, 10);
    this.placedPieces = new Matrix(18, 10);
    this.nextPiece = null;
    this.piece = {"matrix": new Matrix(4, 4), "r": -3, "c": 2};

    this.gameLog = [];
    this.scoreSent = false;

    clearInterval(this.timer);
  }

  start() {
    this.clearGameState();
    this.getNextPiece();

    this.startTime = new Date().getTime();
    this.timer = setInterval(this.timeStep.bind(this), 1000 / LB_FPS);
  }

  isRunning() {
    return this.timer && !(this.gameOver || this.paused);
  }

  checkGameOver() {
    // If the first row has any pieces, there is a game over.
    let matrix = this.placedPieces;
    for (let i = 0; i < matrix.width; i++) {
      if (matrix.get(0, i)) return true;
    }
    return false;
  }

  endGame() {
    this.piece = null;
    this.gameOver = true;

    let game = this;

    slFetch('/api/arcade/score/' + this.gameId + '/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        score: this.score,
        startTime: this.startTime,
        gameLog: this.gameLog,
        frames: this.frames
      })
    }).then((response) => {
      if (response.ok) {
        return response.json();
      }
      console.error('Sending score failed!'); // eslint-disable-line no-console
    }).then((json) => {
      // TODO: Actually use the response. Retry this on failure.
      game.scoreSent = true;
      game.triggerUpdate();
    });

    this.triggerUpdate();
  }

  timeStep() {
    if (!this.isRunning()) return;

    this.frames++;

    let timeout = this.timeout;
    if (this.keyState[13] || this.keyState[80]) { // Enter, p
      this.pause();
    }
    if (this.keyState[32] && this.canDrop) { // Space
      this.drop();
      this.canDrop = false;
    }
    if (!this.keyState[32]) { // Space
      this.canDrop = true;
    }
    if ((this.keyState[38] || this.keyState[87]) && this.canRotate) { // Up, w
      this.rotate();
      this.canRotate = false;
    }
    if (!(this.keyState[38] || this.keyState[87])) { // Up, w
      this.canRotate = true;
    }
    if ((this.keyState[40] || this.keyState[83]) && this.canSpeed) { // Down, s
      this.speedUp();
    }
    if (!(this.keyState[40] || this.keyState[83])) { // Down, s
      this.canSpeed = true;
    }
    if (!(this.keyState[40] || this.keyState[83])) { // Down, s
      this.speedDown();
    }
    if ((this.keyState[37] || this.keyState[65]) && this.frames - this.lastLR > LB_LR_INTERVAL) { // Left, a
      this.lastLR = this.frames;
      this.moveLeft();
    }
    if ((this.keyState[39] || this.keyState[68]) && this.frames - this.lastLR > LB_LR_INTERVAL) { // Right, d
      this.lastLR = this.frames;
      this.moveRight();
    }
    if (this.fast && this.canSpeed) {
      timeout = LB_MIN_TIMEOUT;
    }
    if ((this.frames - this.lastDrop) / LB_FPS >= timeout / 1000) {
      this.lastDrop = this.frames;
      this.movePieceDown();
      this.draw();
    }
  }

  movePieceDown() {
    let p = this.piece;
    if (!this.canSpeed && p.r > -2) {
      this.canSpeed = true;
    }
    if (this.validPlacement(p.matrix, p.r + 1, p.c)) {
      p.r++;
      return true;
    }
    // If moving down is invalid, the piece cannot fall anymore.
    this.placedPieces.addMatrix(p.matrix, p.r, p.c);
    this.canSpeed = false;

    if (this.checkGameOver()) {
      // GAME OVER.
      this.endGame();
    } else {
      this.getNextPiece();

      // Check if a line was made.
      if (this.clearLines(p.r, p.r + 4).length > 0) {
        this.score += 50;
        this.timeout -= 3;
      }
    }
    return false;
  }

  clearLines(minRow, maxRow) {
    let matrix = this.placedPieces;
    let deleted = [];

    for (let i = minRow; i < maxRow; i++) {
      let j = 0;
      while (matrix.get(i, j) && j < matrix.width) {
        j++;
      }
      if (j == matrix.width) {
        // There is a line at i.
        deleted.push(i);
      }
    }
    matrix.deleteRows(deleted);
    return deleted;
  }

  validPlacement(piece, r, c) {
    let matrix = this.placedPieces;
    for (let i = 0; i < piece.height; i++) {
      for (let j = 0; j < piece.width; j++) {
        let row = r + i;
        let col = c + j;

        if (matrix.withinBounds(row, col)) {
          // If the piece intersects another piece. Ignore ghost pieces with value 8.
          if (piece.get(i, j) && (matrix.get(row, col) && matrix.get(row, col) != 8)) {
            return false;
          }
        } else if (row >= 0 && piece.get(i, j)) {
          // If the piece goes past the sides or the bottom.
          // (don't count the top)
          return false;
        } else if ((j < 1 || j > 10) && piece.get(i, j)) {
          // If the piece goes past the sides (counting the top).
          return false;
        }
      }
    }
    return true;
  }

  getNextPiece() {
    if (!this.nextPiece) {
      this.setNextPiece();
    }
    this.piece = {"matrix": this.nextPiece, "r": -2, "c": 3};
    this.setNextPiece();
  }

  setNextPiece() {
    let i = Math.floor(Math.random() * LB_PIECES.length);
    this.nextPiece = new Matrix(4, 4, LB_PIECES[i]);
  }

  draw() {
    let matrix = cloneDeep(this.placedPieces);
    let p = this.piece;
    if (p) {
      matrix.addMatrix(p.matrix, p.r, p.c);
      // draw ghost piece
      let g = cloneDeep(p);
      for (var i = 0; i < g.length; i++) {
        if (g[i] != 0) {
          g[i] = 8;
        }
      }
      while (g.validPlacement) {
        g.r++;
      }
      matrix.addMatrix(g.matrix, g.r, g.c);
    }

    // gameMatrix is bound to a BlockGrid, which should render this.
    this.gameMatrix = matrix;

    // Make sure the component updates.
    this.triggerUpdate();
  }

  pause() {
    if (!this.timer) return;
    this.paused = !this.paused;
    this.triggerUpdate();
  }

  drop() {
    if (!this.isRunning()) return;
    while (this.movePieceDown());
    this.draw();
  }

  speedUp() {
    this.fast = true;
  }

  speedDown() {
    this.fast = false;
  }

  rotate() {
    if (!this.isRunning()) return;
    let p = cloneDeep(this.piece);
    p.matrix.rotate();
    if (this.validPlacement(p.matrix, p.r, p.c)) {
      this.piece = p;
      this.draw();
    }
  }

  moveLeft() {
    if (!this.isRunning()) return;
    let p = this.piece;
    if (this.validPlacement(p.matrix, p.r, p.c - 1)) {
      p.c--;
      this.draw();
    }
  }

  moveRight() {
    if (!this.isRunning()) return;
    let p = this.piece;
    if (this.validPlacement(p.matrix, p.r, p.c + 1)) {
      p.c++;
      this.draw();
    }
  }
}
<|endoftext|>


<commit_before>var util = require("util");
var AWS = require("aws-sdk");
var helpers = require("../helpers");
var Policy = require("../s3post").Policy;
var S3Form = require("../s3post").S3Form;
var AWS_CONFIG_FILE = "config.json";
var POLICY_FILE = "policy.json";
var INDEX_TEMPLATE = "index.ejs";

var s3 = new AWS.S3();
AWS.config.loadFromPath('./config.json');

var task = function(request, callback){

var params = {
		Bucket: 'lab4-weeia',
	};

	s3.listObjects(params, function(err, data) {
		if (err) console.log(err, err.stack);
		else     console.log(data);
	var linki = [];
	var linkiprzet=[];
		//przelatujemy przez każdy plik z bucketu
		for(var i in data.Contents) {
			//jeżeli nie jest to nazwa bucketu tylko plik

				linki.push( {nazwa: data.Contents[i].Key.substring(13)});

				linkiprzet.push( {nazwa: data.Contents[i].Key.substring(13)});

		}
	//1. load configuration
	var awsConfig = helpers.readJSONFile(AWS_CONFIG_FILE);
	var policyData = helpers.readJSONFile(POLICY_FILE);

	//2. prepare policy
	var policy = new Policy(policyData);

	//3. generate form fields for S3 POST
	var s3Form = new S3Form(policy);
	//4. get bucket name
	var fields=s3Form.generateS3FormFields();

	fields.push( {name : 'x-amz-meta-uploader', value : 'piotr.wozniak'});

	var f2=s3Form.addS3CredientalsFields(fields,awsConfig);
	callback(null, {template: INDEX_TEMPLATE, params:{fields:fields,bucket:"lab4-weeia", links:linki, linkiprzet:linkiprzet}});

});

}
exports.action = task;
<commit_msg>final<commit_after>var util = require("util");
var AWS = require("aws-sdk");
var helpers = require("../helpers");
var Policy = require("../s3post").Policy;
var S3Form = require("../s3post").S3Form;
var AWS_CONFIG_FILE = "config.json";
var POLICY_FILE = "policy.json";
var INDEX_TEMPLATE = "index.ejs";

var s3 = new AWS.S3();
AWS.config.loadFromPath('./config.json');

var task = function(request, callback){

var params = {
		Bucket: 'lab4-weeia'
	};

	s3.listObjects(params, function(err, data) {
		if (err) console.log(err, err.stack);
		else     console.log(data);
	var linki = [];
	var linkiprzet=[];
		//przelatujemy przez każdy plik z bucketu
		for(var i in data.Contents) {
			//jeżeli nie jest to nazwa bucketu tylko plik
		if (data.Prefix=="piotrwozniak"){
				linki.push( {nazwa: data.Contents[i].Key.substring(13)});

		}

			if (data.Prefix == "processed"){
				linkiprzet.push( {nazwa: data.Contents[i].Key.substring(13)});

		}

		}
	//1. load configuration
	var awsConfig = helpers.readJSONFile(AWS_CONFIG_FILE);
	var policyData = helpers.readJSONFile(POLICY_FILE);

	//2. prepare policy
	var policy = new Policy(policyData);

	//3. generate form fields for S3 POST
	var s3Form = new S3Form(policy);
	//4. get bucket name
	var fields=s3Form.generateS3FormFields();

	fields.push( {name : 'x-amz-meta-uploader', value : 'piotr.wozniak'});

	var f2=s3Form.addS3CredientalsFields(fields,awsConfig);
	callback(null, {template: INDEX_TEMPLATE, params:{fields:fields,bucket:"lab4-weeia", links:linki, linkiprzet:linkiprzet}});

});

}
exports.action = task;
<|endoftext|>


<commit_before>"use strict"

const each = require("async/each")

module.exports = function TrackerManager(zeronet) {
  const self = this

  let trackers = []

  let lastid

  function updateNext() {
    if (!trackers.length) return
    if (lastid >= trackers.length) return (lastid = 0)
    trackers[lastid].update()
    lastid++
  }

  function updateAll() {
    updateNext()
    if (lastid) setTimeout(updateAll, 1000)
  }

  const main = setInterval(() => {
    lastid = 0
    updateAll()
  }, (30 + trackers.length) * 1000) //every 30secs + per tracker 1sec

  function add(tracker, zite) {
    let plist

    tracker.on("peer", (addr) => {
      if (!plist) { //add async as the tracker client yields many peers sync
        plist = []
        process.nextTick(() => {
          zeronet.pool.addMany(plist, zite)
          plist = null
        })
      }
      plist.push(addr)
    })

    //tracker.on("update", console.log)

    tracker.complete()
    tracker.start()
    tracker.update()

    trackers.push(tracker)
  }

  function stop() {
    clearInterval(main)
    each(trackers, (tracker, next) => {
      tracker.once("error", next)
      tracker.once("stop", next)
      tracker.stop()
    })
  }

  self.add = add
  self.stop = stop
}
<commit_msg>Fix the tracker-reannounce-timer<commit_after>"use strict"

const each = require("async/each")

module.exports = function TrackerManager(zeronet) {
  const self = this

  let trackers = []

  let lastid = -1

  function updateNext() {
    if (!trackers.length) return
    if (lastid >= trackers.length) return (lastid = 0)
    trackers[lastid].update()
    lastid++
  }

  let main

  function updateAll() {
    if (trackers[lastid]) {
      updateNext()
      main = setTimeout(updateAll, 1000)
    } else {
      lastid = 0
      main = setTimeout(updateAll, 30 * 1000)
    }
  }

  updateAll()

  function add(tracker, zite) {
    let plist

    tracker.on("peer", (addr) => {
      if (!plist) { //add async as the tracker client yields many peers sync
        plist = []
        process.nextTick(() => {
          zeronet.pool.addMany(plist, zite)
          plist = null
        })
      }
      plist.push(addr)
    })

    //tracker.on("update", console.log)

    tracker.complete()
    tracker.start()
    tracker.update()

    trackers.push(tracker)
  }

  function stop() {
    clearInterval(main)
    each(trackers, (tracker, next) => {
      tracker.once("error", next)
      tracker.once("stop", next)
      tracker.stop()
    })
  }

  self.add = add
  self.stop = stop
}
<|endoftext|>