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

var applet = require('../jsmm-applet');
var dares = require('../dares');

module.exports = function(client) {
	client.PageHome = function() { return this.init.apply(this, arguments); };
	client.PageHome.prototype = {
		type: 'PageHome',

		init: function(delegate, $div) {
			this.delegate = delegate;
			this.$div = $div;

			this.modalUI = new applet.UI();
			this.modalUI.setCloseCallback(this.closeCallback.bind(this));

			this.$previewText = $('
<button class="btn janpaul123"> JanPaul123</button>
Welcome to the private preview of Javascript dares. My name is Jan Paul, and I\'m trying to create a platform for learning  programming. For this, I need your help!

If you know programming, please help by creating exercises, or dares. These can range from an introductory level, to complex algorithmic challenges. Right now the dares editor is very rudimentary, but I\'ll work hard to improve this.

If you don\'t know programming, you can help too! Please try the introductory dares at the bottom of this page, and give me feedback about what you did and did not like. Of course, you can also try the dares that other people make!

I truly believe that this is a great opportunity to work on an awesome project together. We can all create the next generation programming course this way. Join me, tell your friends, and let\'s change the world!

Superheroes registered so far:

');
			this.$div.append(this.$previewText);

			this.$previewText.find('.janpaul123').on('click', (function() { this.delegate.navigateTo('/superheroes/janpaul123'); }).bind(this));

			this.$superheroes = this.$previewText.find('.volunteers-superheroes');

			var navigateToUser = (function(link) {
				return (function() { this.delegate.navigateTo('/superheroes/' + link); }).bind(this);
			}).bind(this);

			this.delegate.getSync().getUsersAll((function(users) {
				if (users.length <= 1) this.$superheroes.text('none...');
				for (var i=0; i<users.length; i++) {
					var user = users[i];
					var link = user.link;
					if (user.screenname !== 'JanPaul123') {
						var $button = $('<button class="btn"> ' + user.screenname + '</button>');
						$button.on('click', navigateToUser(link));
						this.$superheroes.append($button);
					}
				}
			}).bind(this));

			this.$example = $('

Make your own games by learning Javascript programming!

Anyone can learn how to write code like this.

');
			this.$exampleGame = $('

');
			this.$example.append(this.$exampleGame);
			this.$div.append(this.$example);

			this.exampleUI = new applet.UI(this.$exampleGame, {hideTabs: true});
			var exampleText = '// Adapted from billmill.org/static/canvastutorial\nvar context = canvas.getContext("2d");\n\nvar paddleWidth = 80;\nvar paddleHeight = 12;\nvar bricks = [];\nvar bricksNumX = 7;\nvar bricksNumY = 5;\nvar brickWidth = canvas.width / bricksNumX;\nvar brickHeight = 20;\nvar brickMargin = 4;\nvar paddleX;\nvar ballX, ballY, ballVx, ballVy;\n\nfor (var y=0; y<bricksNumY; y++) {\n  bricks[y] = [];\n  for (var x=0; x<bricksNumX; x++) {\n    bricks[y][x] = true;\n  }\n}\n\nfunction init() {\n  paddleX = canvas.width/2;\n  ballX = 40;\n  ballY = 150;\n  ballVx = 7;\n  ballVy = 12;\n  for (var y=0; y<bricksNumY; y++) {\n    for (var x=0; x<bricksNumX; x++) {\n      bricks[y][x] = true;\n    }\n  }\n}\n\nfunction clear() {\n  context.clearRect(0, 0, canvas.width, canvas.height);  \n}\n\nfunction circle(x, y) {\n  context.beginPath();\n  context.arc(x, y, 10, 0, 2*Math.PI);\n  context.fill();\n}\n\nfunction drawPaddle() {\n  var x = paddleX - paddleWidth/2;\n  var y = canvas.height - paddleHeight;\n  context.fillRect(x, y, paddleWidth, paddleHeight);\n}\n\nfunction mouseMove(event) {\n  paddleX = event.layerX;\n}\n\nfunction hitHorizontal() {\n  if (ballX < 0) {\n    ballVx = -ballVx;\n  } else if (ballX >= canvas.width) {\n    ballVx = -ballVx;\n  }\n}\n\nfunction hitVertical() {\n  if (ballY < 0) {\n    ballVy = -ballVy;\n  } else if (ballY < brickHeight*bricksNumY) {\n    var bx = Math.floor(ballX/brickWidth);\n    var by = Math.floor(ballY/brickHeight);\n    \n    if (bx >= 0 && bx < bricksNumX) {\n      if (bricks[by][bx]) {\n        bricks[by][bx] = false;\n        ballVy = -ballVy;\n      }\n    }\n  } else if (ballY >= canvas.height-paddleHeight) {\n    var paddleLeft = paddleX-paddleWidth/2;\n    var paddleRight = paddleX+paddleWidth/2;\n    if (ballX >= paddleLeft && ballX <= paddleRight) {\n      ballVy = -ballVy;\n    } else {\n      init();\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction drawBricks() {\n  for (var by=0; by<bricksNumY; by++) {\n    for (var bx=0; bx<bricksNumX; bx++) {\n      if (bricks[by][bx]) {\n        var x = bx * brickWidth + brickMargin/2;\n        var y = by * brickHeight + brickMargin/2;\n        var width = brickWidth - brickMargin;\n        var height = brickHeight - brickMargin;\n        context.fillRect(x, y, width, height);\n      }\n    }\n  }\n}\n\nfunction tick() {\n  clear();\n  drawPaddle();\n  \n  ballX += ballVx;\n  ballY += ballVy;\n  \n  hitHorizontal();\n  if (hitVertical()) {\n    circle(ballX, ballY);\n    drawBricks();\n  } else {\n    clear();\n  }\n}\n\ninit();\ncanvas.onmousemove = mouseMove;\nwindow.setInterval(tick, 30);';
			this.exampleEditor = this.exampleUI.addEditor({text: exampleText});
			this.exampleUI.loadOutputs(['canvas', 'events', 'math'], { canvas: {}, events: {mouseObjects: ['canvas']}, math: {} });
			this.exampleUI.selectTab('canvas');

			$('.example-text-top').css('margin-left', -$('.example-text-top').width()/2);
			$('.example-text-bottom').css('margin-left', -$('.example-text-bottom').width()/2);

			this.$how = $('

getting started

You learn programming by completing dares. These are short puzzles in which you have to copy the example, in as few lines of code as possible. They start simple, and become more difficult as you progress.

 For now we only provide a number of examples. In the future we will provide some collections of dares to start with, and you will also be able to make and share your own dares. You can also play around in the full editor.

');
			this.$div.append(this.$how);

			this.$intro = $('

');
			this.$arrow = $('

');
			this.$intro.append(this.$arrow);
			this.$arrow.hide();

			var $collection1 = $('

');
			this.collection1 = new dares.Collection(this, $collection1);
			this.$intro.append($collection1);

			var $collection2 = $('

');
			this.collection2 = new dares.Collection(this, $collection2);
			this.$intro.append($collection2);

			this.$introButton = $('<button class="intro-full-editor btn btn-large">Open full editor</button>');
			this.$introButton.on('click', (function(event) { this.delegate.navigateTo('/full'); }).bind(this));
			this.$intro.append(this.$introButton);
			this.$div.append(this.$intro);

			this.fullEditor = null;

			this.updateCollections();
		},

		remove: function() {
			this.$previewText.remove();
			this.exampleUI.remove();
			this.collection1.remove();
			this.collection2.remove();
			this.$example.remove();
			this.$how.remove();
			this.$intro.remove();
		},

		getSync: function() {
			return this.delegate.getSync();
		},

		viewDare: function(_id) {
			this.delegate.navigateTo('/dare/' + _id);
		},

		editDare: function(_id) {
			this.delegate.navigateTo('/edit/' + _id);
		},

		updateCollections: function() {
			this.delegate.getSync().getCollectionAndDaresAndInstances('5009684ce78955fbcf405844', (function(content) {
				this.collection1.update(content, this.delegate.getUserId());
				if (!content.dares[0].instance || !content.dares[0].instance.completed) {
					if (this.$arrow !== null) this.$arrow.show();
				}
			}).bind(this));
			this.delegate.getSync().getCollectionAndDaresAndInstances('30000000078955fbcf405844', (function(content) {
				this.collection2.update(content, this.delegate.getUserId());
			}).bind(this));
		},

		closeCallback: function() {
			this.delegate.navigateTo('/');
		},

		navigateTo: function(splitUrl) {
			if (this.$arrow !== null && splitUrl[0] !== '') {
				this.$arrow.remove();
				this.$arrow = null;
			}

			window.bla = this.exampleEditor;

			if (splitUrl[0] === 'dare' || splitUrl[0] === 'edit') {
				this.exampleEditor.disable();
				this.closeModal();
			} else if (splitUrl[0] === 'full') {
				this.exampleEditor.disable();
				this.navigateFullEditor();
			} else {
				this.exampleEditor.enable();
				this.closeModal();
				this.updateCollections();
			}
		},

		navigateFullEditor: function() {
			if (localStorage.getItem('initial-code') === null) {
				localStorage.setItem('initial-code', '// ROBOT EXAMPLE\nwhile(!robot.detectGoal()) {\n  robot.turnLeft();\n  while (robot.detectWall()) {\n    robot.turnRight();\n  }\n  robot.drive();\n}\n\n//CONSOLE EXAMPLE\nconsole.setColor("#fff");\nconsole.log("A colourful multiplication table:");\nconsole.log();\n\nfunction printLine(n) {\n  var text = "";\n  for (var i=1; i<=8; i++) {\n    text += (i*n) + "\\t";\n  }\n  console.log(text);\n}\n\nfor (var i=1; i<=20; i++) { \n  console.setColor("hsla(" + i*15 + ", 75%, 50%, 1)");\n  printLine(i);\n}\n\nconsole.setColor("#ed7032");\nconsole.log();\nconsole.log(":-D");\n\n');
			}

			if (localStorage.getItem('initial-robot') === null) {
				localStorage.setItem('initial-robot', '{"columns":8,"rows":8,"initialX":3,"initialY":4,"initialAngle":90,"mazeObjects":50,"verticalActive":[[false,false,false,false,false,false,false,false],[false,false,true,true,true,false,true,false],[false,true,false,false,true,false,false,true],[false,false,true,true,false,false,true,false],[false,true,true,false,false,false,false,false],[false,false,false,true,false,true,true,false],[false,false,true,false,true,true,false,false],[false,false,false,true,true,true,true,false]],"horizontalActive":[[false,true,false,false,true,false,false,true],[false,true,false,true,false,false,true,false],[false,true,true,false,true,false,true,false],[false,true,false,false,true,true,true,false],[false,false,true,true,false,true,false,true],[false,true,false,false,true,false,false,true],[false,true,true,true,false,false,false,true],[false,true,true,false,false,false,false,false]],"blockGoal":[[false,false,false,true,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false]],"numGoals":1}');
			}

			this.modalUI.openModal();
			this.fullEditor = this.modalUI.addEditor({text: localStorage.getItem('initial-code')});
			this.fullEditor.setTextChangeCallback(function(text) {
				localStorage.setItem('initial-code', text);
			});
			this.modalUI.loadOutputs(['robot', 'canvas', 'console', 'info', 'events', 'math'], {
				robot: {state: localStorage.getItem('initial-robot')}, canvas: {}, console: {}, info: {}, events: {mouseObjects: ['canvas']}, math: {}
			});
			this.modalUI.getOutput('robot').setStateChangeCallback(function(state) {
				localStorage.setItem('initial-robot', state);
			});
			this.modalUI.selectTab('robot');
		},

		closeModal: function() {
			if (this.fullEditor !== null) {
				this.fullEditor = null;
				this.modalUI.closeModal();
			}
		}
	};
};<commit_msg>JavaScript vs Javascript<commit_after>/*jshint node:true jquery:true*/
"use strict";

var applet = require('../jsmm-applet');
var dares = require('../dares');

module.exports = function(client) {
	client.PageHome = function() { return this.init.apply(this, arguments); };
	client.PageHome.prototype = {
		type: 'PageHome',

		init: function(delegate, $div) {
			this.delegate = delegate;
			this.$div = $div;

			this.modalUI = new applet.UI();
			this.modalUI.setCloseCallback(this.closeCallback.bind(this));

			this.$previewText = $('
<button class="btn janpaul123"> JanPaul123</button>
Welcome to the private preview of JavaScript dares. My name is Jan Paul, and I\'m trying to create a platform for learning  programming. For this, I need your help!

If you know programming, please help by creating exercises, or dares. These can range from an introductory level, to complex algorithmic challenges. Right now the dares editor is very rudimentary, but I\'ll work hard to improve this.

If you don\'t know programming, you can help too! Please try the introductory dares at the bottom of this page, and give me feedback about what you did and did not like. Of course, you can also try the dares that other people make!

I truly believe that this is a great opportunity to work on an awesome project together. We can all create the next generation programming course this way. Join me, tell your friends, and let\'s change the world!

Superheroes registered so far:

');
			this.$div.append(this.$previewText);

			this.$previewText.find('.janpaul123').on('click', (function() { this.delegate.navigateTo('/superheroes/janpaul123'); }).bind(this));

			this.$superheroes = this.$previewText.find('.volunteers-superheroes');

			var navigateToUser = (function(link) {
				return (function() { this.delegate.navigateTo('/superheroes/' + link); }).bind(this);
			}).bind(this);

			this.delegate.getSync().getUsersAll((function(users) {
				if (users.length <= 1) this.$superheroes.text('none...');
				for (var i=0; i<users.length; i++) {
					var user = users[i];
					var link = user.link;
					if (user.screenname !== 'JanPaul123') {
						var $button = $('<button class="btn"> ' + user.screenname + '</button>');
						$button.on('click', navigateToUser(link));
						this.$superheroes.append($button);
					}
				}
			}).bind(this));

			this.$example = $('

Make your own games by learning JavaScript programming!

Anyone can learn how to write code like this.

');
			this.$exampleGame = $('

');
			this.$example.append(this.$exampleGame);
			this.$div.append(this.$example);

			this.exampleUI = new applet.UI(this.$exampleGame, {hideTabs: true});
			var exampleText = '// Adapted from billmill.org/static/canvastutorial\nvar context = canvas.getContext("2d");\n\nvar paddleWidth = 80;\nvar paddleHeight = 12;\nvar bricks = [];\nvar bricksNumX = 7;\nvar bricksNumY = 5;\nvar brickWidth = canvas.width / bricksNumX;\nvar brickHeight = 20;\nvar brickMargin = 4;\nvar paddleX;\nvar ballX, ballY, ballVx, ballVy;\n\nfor (var y=0; y<bricksNumY; y++) {\n  bricks[y] = [];\n  for (var x=0; x<bricksNumX; x++) {\n    bricks[y][x] = true;\n  }\n}\n\nfunction init() {\n  paddleX = canvas.width/2;\n  ballX = 40;\n  ballY = 150;\n  ballVx = 7;\n  ballVy = 12;\n  for (var y=0; y<bricksNumY; y++) {\n    for (var x=0; x<bricksNumX; x++) {\n      bricks[y][x] = true;\n    }\n  }\n}\n\nfunction clear() {\n  context.clearRect(0, 0, canvas.width, canvas.height);  \n}\n\nfunction circle(x, y) {\n  context.beginPath();\n  context.arc(x, y, 10, 0, 2*Math.PI);\n  context.fill();\n}\n\nfunction drawPaddle() {\n  var x = paddleX - paddleWidth/2;\n  var y = canvas.height - paddleHeight;\n  context.fillRect(x, y, paddleWidth, paddleHeight);\n}\n\nfunction mouseMove(event) {\n  paddleX = event.layerX;\n}\n\nfunction hitHorizontal() {\n  if (ballX < 0) {\n    ballVx = -ballVx;\n  } else if (ballX >= canvas.width) {\n    ballVx = -ballVx;\n  }\n}\n\nfunction hitVertical() {\n  if (ballY < 0) {\n    ballVy = -ballVy;\n  } else if (ballY < brickHeight*bricksNumY) {\n    var bx = Math.floor(ballX/brickWidth);\n    var by = Math.floor(ballY/brickHeight);\n    \n    if (bx >= 0 && bx < bricksNumX) {\n      if (bricks[by][bx]) {\n        bricks[by][bx] = false;\n        ballVy = -ballVy;\n      }\n    }\n  } else if (ballY >= canvas.height-paddleHeight) {\n    var paddleLeft = paddleX-paddleWidth/2;\n    var paddleRight = paddleX+paddleWidth/2;\n    if (ballX >= paddleLeft && ballX <= paddleRight) {\n      ballVy = -ballVy;\n    } else {\n      init();\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction drawBricks() {\n  for (var by=0; by<bricksNumY; by++) {\n    for (var bx=0; bx<bricksNumX; bx++) {\n      if (bricks[by][bx]) {\n        var x = bx * brickWidth + brickMargin/2;\n        var y = by * brickHeight + brickMargin/2;\n        var width = brickWidth - brickMargin;\n        var height = brickHeight - brickMargin;\n        context.fillRect(x, y, width, height);\n      }\n    }\n  }\n}\n\nfunction tick() {\n  clear();\n  drawPaddle();\n  \n  ballX += ballVx;\n  ballY += ballVy;\n  \n  hitHorizontal();\n  if (hitVertical()) {\n    circle(ballX, ballY);\n    drawBricks();\n  } else {\n    clear();\n  }\n}\n\ninit();\ncanvas.onmousemove = mouseMove;\nwindow.setInterval(tick, 30);';
			this.exampleEditor = this.exampleUI.addEditor({text: exampleText});
			this.exampleUI.loadOutputs(['canvas', 'events', 'math'], { canvas: {}, events: {mouseObjects: ['canvas']}, math: {} });
			this.exampleUI.selectTab('canvas');

			$('.example-text-top').css('margin-left', -$('.example-text-top').width()/2);
			$('.example-text-bottom').css('margin-left', -$('.example-text-bottom').width()/2);

			this.$how = $('

getting started

You learn programming by completing dares. These are short puzzles in which you have to copy the example, in as few lines of code as possible. They start simple, and become more difficult as you progress.

 For now we only provide a number of examples. In the future we will provide some collections of dares to start with, and you will also be able to make and share your own dares. You can also play around in the full editor.

');
			this.$div.append(this.$how);

			this.$intro = $('

');
			this.$arrow = $('

');
			this.$intro.append(this.$arrow);
			this.$arrow.hide();

			var $collection1 = $('

');
			this.collection1 = new dares.Collection(this, $collection1);
			this.$intro.append($collection1);

			var $collection2 = $('

');
			this.collection2 = new dares.Collection(this, $collection2);
			this.$intro.append($collection2);

			this.$introButton = $('<button class="intro-full-editor btn btn-large">Open full editor</button>');
			this.$introButton.on('click', (function(event) { this.delegate.navigateTo('/full'); }).bind(this));
			this.$intro.append(this.$introButton);
			this.$div.append(this.$intro);

			this.fullEditor = null;

			this.updateCollections();
		},

		remove: function() {
			this.$previewText.remove();
			this.exampleUI.remove();
			this.collection1.remove();
			this.collection2.remove();
			this.$example.remove();
			this.$how.remove();
			this.$intro.remove();
		},

		getSync: function() {
			return this.delegate.getSync();
		},

		viewDare: function(_id) {
			this.delegate.navigateTo('/dare/' + _id);
		},

		editDare: function(_id) {
			this.delegate.navigateTo('/edit/' + _id);
		},

		updateCollections: function() {
			this.delegate.getSync().getCollectionAndDaresAndInstances('5009684ce78955fbcf405844', (function(content) {
				this.collection1.update(content, this.delegate.getUserId());
				if (!content.dares[0].instance || !content.dares[0].instance.completed) {
					if (this.$arrow !== null) this.$arrow.show();
				}
			}).bind(this));
			this.delegate.getSync().getCollectionAndDaresAndInstances('30000000078955fbcf405844', (function(content) {
				this.collection2.update(content, this.delegate.getUserId());
			}).bind(this));
		},

		closeCallback: function() {
			this.delegate.navigateTo('/');
		},

		navigateTo: function(splitUrl) {
			if (this.$arrow !== null && splitUrl[0] !== '') {
				this.$arrow.remove();
				this.$arrow = null;
			}

			window.bla = this.exampleEditor;

			if (splitUrl[0] === 'dare' || splitUrl[0] === 'edit') {
				this.exampleEditor.disable();
				this.closeModal();
			} else if (splitUrl[0] === 'full') {
				this.exampleEditor.disable();
				this.navigateFullEditor();
			} else {
				this.exampleEditor.enable();
				this.closeModal();
				this.updateCollections();
			}
		},

		navigateFullEditor: function() {
			if (localStorage.getItem('initial-code') === null) {
				localStorage.setItem('initial-code', '// ROBOT EXAMPLE\nwhile(!robot.detectGoal()) {\n  robot.turnLeft();\n  while (robot.detectWall()) {\n    robot.turnRight();\n  }\n  robot.drive();\n}\n\n//CONSOLE EXAMPLE\nconsole.setColor("#fff");\nconsole.log("A colourful multiplication table:");\nconsole.log();\n\nfunction printLine(n) {\n  var text = "";\n  for (var i=1; i<=8; i++) {\n    text += (i*n) + "\\t";\n  }\n  console.log(text);\n}\n\nfor (var i=1; i<=20; i++) { \n  console.setColor("hsla(" + i*15 + ", 75%, 50%, 1)");\n  printLine(i);\n}\n\nconsole.setColor("#ed7032");\nconsole.log();\nconsole.log(":-D");\n\n');
			}

			if (localStorage.getItem('initial-robot') === null) {
				localStorage.setItem('initial-robot', '{"columns":8,"rows":8,"initialX":3,"initialY":4,"initialAngle":90,"mazeObjects":50,"verticalActive":[[false,false,false,false,false,false,false,false],[false,false,true,true,true,false,true,false],[false,true,false,false,true,false,false,true],[false,false,true,true,false,false,true,false],[false,true,true,false,false,false,false,false],[false,false,false,true,false,true,true,false],[false,false,true,false,true,true,false,false],[false,false,false,true,true,true,true,false]],"horizontalActive":[[false,true,false,false,true,false,false,true],[false,true,false,true,false,false,true,false],[false,true,true,false,true,false,true,false],[false,true,false,false,true,true,true,false],[false,false,true,true,false,true,false,true],[false,true,false,false,true,false,false,true],[false,true,true,true,false,false,false,true],[false,true,true,false,false,false,false,false]],"blockGoal":[[false,false,false,true,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false],[false,false,false,false,false,false,false,false]],"numGoals":1}');
			}

			this.modalUI.openModal();
			this.fullEditor = this.modalUI.addEditor({text: localStorage.getItem('initial-code')});
			this.fullEditor.setTextChangeCallback(function(text) {
				localStorage.setItem('initial-code', text);
			});
			this.modalUI.loadOutputs(['robot', 'canvas', 'console', 'info', 'events', 'math'], {
				robot: {state: localStorage.getItem('initial-robot')}, canvas: {}, console: {}, info: {}, events: {mouseObjects: ['canvas']}, math: {}
			});
			this.modalUI.getOutput('robot').setStateChangeCallback(function(state) {
				localStorage.setItem('initial-robot', state);
			});
			this.modalUI.selectTab('robot');
		},

		closeModal: function() {
			if (this.fullEditor !== null) {
				this.fullEditor = null;
				this.modalUI.closeModal();
			}
		}
	};
};<|endoftext|>


<commit_before>/* eslint-disable no-console */
import { types, flow } from 'mobx-state-tree';

const defaultSettings = {
  path: '/wp-content/plugins/onesignal-free-web-push-notifications/sdk_files/',
  wordpress: true,
  autoRegister: false,
  allowLocalhostAsSecureOrigin: true,
  httpPermissionRequest: { enable: true },
  notifyButton: { enable: false },
};

export default types
  .model('OneSignal')
  .props({
    areSupported: false,
    areEnabled: false,
  })
  .actions(self => ({
    load: flow(function* loadOneSignal() {
      // Load OneSignal SDK
      const oneSignalSDK = window.document.createElement('script');
      oneSignalSDK.src = 'https://cdn.onesignal.com/sdks/OneSignalSDK.js';
      oneSignalSDK.async = 'async';
      window.document.head.appendChild(oneSignalSDK);

      // Returns if push notifications are supported.
      self.areSupported = yield new Promise(resolve => {
        window.OneSignal = window.OneSignal || [];
        window.OneSignal.push(() => {
          const supported = window.OneSignal.isPushNotificationsSupported();
          resolve(supported);
        });
      });
    }),
    init: flow(function* initOneSignal({ defaultNotificationUrl, ...customSettings }) {
      window.OneSignal.setDefaultNotificationUrl(defaultNotificationUrl);
      window.OneSignal.SERVICE_WORKER_UPDATER_PATH = 'OneSignalSDKUpdaterWorker.js.php';
      window.OneSignal.SERVICE_WORKER_PATH = 'OneSignalSDKWorker.js.php';
      window.OneSignal.SERVICE_WORKER_PARAM = { scope: '/' };

      try {
        yield window.OneSignal.init(Object.assign(defaultSettings, customSettings));
      } catch (error) {
        console.warn('Something was wrong while initializing OneSignal:\n', error);
      }

      self.areEnabled = yield window.OneSignal.isPushNotificationsEnabled();

      window.OneSignal.on('notificationPermissionChange', permissionChange => {
        console.log('notificationPermissionChange');
        if (permissionChange.to === 'denied') self.disable();
      });
      window.OneSignal.on('customPromptClick', ({ result }) => {
        console.log('customPromptClick');
        if (result === 'denied') self.disable();
      });
    }),
    toggleEnabled: flow(function* toggleNotifications() {
      self.areEnabled = !self.areEnabled;

      if (self.areEnabled) {
        const permission = yield window.OneSignal.getNotificationPermission();
        if (permission === 'denied') {
          console.warn('Notifications denied in browser!');
          self.areEnabled = false;
          return;
        }
        window.OneSignal.registerForPushNotifications();
        yield window.OneSignal.setSubscription(true);
      } else {
        yield window.OneSignal.setSubscription(false);
      }
    }),
    disable() {
      self.areEnabled = false;
    },
  }));
<commit_msg>Removed some console.logs<commit_after>/* eslint-disable no-console */
import { types, flow } from 'mobx-state-tree';

const defaultSettings = {
  path: '/wp-content/plugins/onesignal-free-web-push-notifications/sdk_files/',
  wordpress: true,
  autoRegister: false,
  allowLocalhostAsSecureOrigin: true,
  httpPermissionRequest: { enable: true },
  notifyButton: { enable: false },
};

export default types
  .model('OneSignal')
  .props({
    areSupported: false,
    areEnabled: false,
  })
  .actions(self => ({
    load: flow(function* loadOneSignal() {
      // Load OneSignal SDK
      const oneSignalSDK = window.document.createElement('script');
      oneSignalSDK.src = 'https://cdn.onesignal.com/sdks/OneSignalSDK.js';
      oneSignalSDK.async = 'async';
      window.document.head.appendChild(oneSignalSDK);

      // Returns if push notifications are supported.
      self.areSupported = yield new Promise(resolve => {
        window.OneSignal = window.OneSignal || [];
        window.OneSignal.push(() => {
          const supported = window.OneSignal.isPushNotificationsSupported();
          resolve(supported);
        });
      });
    }),
    init: flow(function* initOneSignal({ defaultNotificationUrl, ...customSettings }) {
      window.OneSignal.setDefaultNotificationUrl(defaultNotificationUrl);
      window.OneSignal.SERVICE_WORKER_UPDATER_PATH = 'OneSignalSDKUpdaterWorker.js.php';
      window.OneSignal.SERVICE_WORKER_PATH = 'OneSignalSDKWorker.js.php';
      window.OneSignal.SERVICE_WORKER_PARAM = { scope: '/' };

      try {
        yield window.OneSignal.init(Object.assign(defaultSettings, customSettings));
      } catch (error) {
        console.warn('Something was wrong while initializing OneSignal:\n', error);
      }

      self.areEnabled = yield window.OneSignal.isPushNotificationsEnabled();

      window.OneSignal.on('notificationPermissionChange', permissionChange => {
        if (permissionChange.to === 'denied') self.disable();
      });
      window.OneSignal.on('customPromptClick', ({ result }) => {
        if (result === 'denied') self.disable();
      });
    }),
    toggleEnabled: flow(function* toggleNotifications() {
      self.areEnabled = !self.areEnabled;

      if (self.areEnabled) {
        const permission = yield window.OneSignal.getNotificationPermission();
        if (permission === 'denied') {
          console.warn('Notifications denied in browser!');
          self.areEnabled = false;
          return;
        }
        window.OneSignal.registerForPushNotifications();
        yield window.OneSignal.setSubscription(true);
      } else {
        yield window.OneSignal.setSubscription(false);
      }
    }),
    disable() {
      self.areEnabled = false;
    },
  }));
<|endoftext|>


<commit_before>var vow = require('vow');
var fs = require('enb/lib/fs/async-fs');
var bemxjst = require('bem-xjst');
var bemcompat = require('bemhtml-compat');
var XJST_SUFFIX = 'xjst';

module.exports = require('enb/lib/build-flow').create()
    .name('bem-xjst')
    .target('target', '?.bem-xjst.js')
    .methods({
        _sourceFilesProcess: function (sourceFiles, oldSyntax) {
            return vow.all(sourceFiles.map(function (file) {
                    return fs.read(file.fullname, 'utf8')
                        .then(function (source) {
                            if (oldSyntax && XJST_SUFFIX !== file.suffix.split('.').pop()) {
                                source = bemcompat.transpile(source);
                            }

                            return '/* begin: ' + file.fullname + ' *' + '/\n' +
                                source +
                                '\n/* end: ' + file.fullname + ' *' + '/';
                        });
                }))
                .then(function (sources) {
                    return this._bemxjstProcess(sources.join('\n'));
                }, this);
        },
        _bemxjstProcess: function (source) {
            var bemxjstProcessor = BemxjstProcessor.fork();

            return bemxjstProcessor.process(source, this._getOptions()).then(function (res) {
                bemxjstProcessor.dispose();
                return res;
            });
        },
        _getOptions: function () {
            var fieldNames = this._optionFieldNames;
            var options = {};

            for (var optName in fieldNames) {
                if (fieldNames.hasOwnProperty(optName)) {
                    options[optName] = this[fieldNames[optName]];
                }
            }
            return options;
        }
    })
    .createTech();

var BemxjstProcessor = require('sibling').declare({
    process: function (source, options) {
        return bemxjst.generate(source, {
            wrap: true,
            exportName: options.exportName,
            optimize: !options.devMode,
            cache: !options.devMode && options.cache
        });
    }
});
<commit_msg>Refactoring of `bem-xjst` tech: removed `_getOptions`<commit_after>var vow = require('vow');
var fs = require('enb/lib/fs/async-fs');
var bemxjst = require('bem-xjst');
var bemcompat = require('bemhtml-compat');
var XJST_SUFFIX = 'xjst';

module.exports = require('enb/lib/build-flow').create()
    .name('bem-xjst')
    .target('target', '?.bem-xjst.js')
    .methods({
        _sourceFilesProcess: function (sourceFiles, oldSyntax) {
            return vow.all(sourceFiles.map(function (file) {
                    return fs.read(file.fullname, 'utf8')
                        .then(function (source) {
                            if (oldSyntax && XJST_SUFFIX !== file.suffix.split('.').pop()) {
                                source = bemcompat.transpile(source);
                            }

                            return '/* begin: ' + file.fullname + ' *' + '/\n' +
                                source +
                                '\n/* end: ' + file.fullname + ' *' + '/';
                        });
                }))
                .then(function (sources) {
                    return this._bemxjstProcess(sources.join('\n'));
                }, this);
        },
        _bemxjstProcess: function (source) {
            var bemxjstProcessor = BemxjstProcessor.fork();

            return bemxjstProcessor.process(source, {
                wrap: true,
                exportName: this._exportName,
                optimize: !this._devMode,
                cache: !this._devMode && this._cache
            }).then(function (res) {
                bemxjstProcessor.dispose();
                return res;
            });
        }
    })
    .createTech();

var BemxjstProcessor = require('sibling').declare({
    process: function (source, options) {
        return bemxjst.generate(source, options);
    }
});
<|endoftext|>


<commit_before>'use strict'

require('extensions')
const util = require('./util.js')
const users = require('./data/users.json')

const out = {
  words: 0, // total for the day
  comments: 0,  // total for the day
  prs: { opened: 0, closed: 0, words: 0 },
  issues: { opened: 0, closed: 0, words: 0 },
  activity: {},
  users: {}
}
const getRepo = (name, open) => out.activity[name] || (out.activity[name] = {
  open: open,
  name: () => name // this is created as a function so it doesn't show in the JSON output
})
const getIssue = (repo, number) => repo[number] || (repo[number] = {
  comments: 0,
  words: 0,
  toJSON: () => `<${repo.name()}›${number}>` // add special tokens that get placed later
})
const handlers = {
  'IssuesEvent': (e, repo) => {
    var issue = require(`./data/repos/${e.repo}/issues.json`)[e.payload.issue]
    var i = getIssue(repo, e.payload.issue)
    var action = e.payload.action

    user(issue.user, e.repo, 'issues', e.payload.issue, issue.words, action)
    count.issue(issue.words, repo, i, action, issue.pr)

    i[action] = action === 'opened' ? issue.created_at : issue.closed_at
    i[action.replace('ed', 'er')] = e.actor
    if (issue.pr) i.pr = true
  },
  'PullRequestEvent': (e, repo) => {
    var issue = require(`./data/repos/${e.repo}/issues.json`)[e.payload.pull_request]
    var i = getIssue(repo, e.payload.pull_request)
    var action = e.payload.action

    user(issue.user, e.repo, 'pulls', e.payload.pull_request, issue.words, action)
    count.issue(issue.words, repo, i, action, true, e.repo)

    i.pr = true
    i[action] = action === 'opened' ? issue.created_at : issue.closed_at
    i[action.replace('ed', 'er')] = e.actor
  },
  'IssueCommentEvent': (e, repo) => {
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.comment]
    var i = getIssue(repo, e.payload.issue)
    count.comment(comment.words, repo, i, comment.pr ? true : undefined)
    user(comment.user, e.repo, comment.pr ? 'pulls' : 'issues', comment.number, comment.words, null, e.payload.comment)
  },
  'PullRequestReviewCommentEvent': (e, repo) => {
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.comment]
    var i = getIssue(repo, e.payload.pull_request)
    count.comment(comment.words, repo, i, true)
    user(comment.user, e.repo, 'pulls', comment.number, comment.words, null, e.payload.comment)
  },
  'CommitCommentEvent': (e, repo) => {
    if (!e.payload) return // initially, payloads were missed
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.id]
    var i = getIssue(repo, e.payload.commit_id)
    count.comment(comment.words, repo, i, false)
    user(comment.user, e.repo, 'comments', comment.number, comment.words, null, e.payload.id)
  }
}
const count = {
  comment: function count (words, repo, issue, pr) {
    if (typeof pr !== 'undefined') issue.pr = pr
    issue.comments++
    out.comments++
    words = words || 0
    issue.words += words
    out.words += words
    repo.words = (repo.words || 0) + words
    repo.comments = (repo.comments || 0) + 1
    out[pr ? 'prs' : 'issues'].words += words
  },
  issue: function count (words, repo, issue, action, pr) {
    words = words || 0
    out.words += words
    repo.words = (repo.words || 0) + words
    issue.words = (issue.words || 0) + words
    repo[action] = (repo[action] || 0) + 1
    var type = out[pr ? 'prs' : 'issues']
    type.words += words
    type[action]++
  }
}

function user (id, repo, type, issue, words, action, commentid) {
  var longid = `${repo}/${type}/${issue}`
  if (commentid) longid += '#' + commentid
  var user = out.users[id] || (out.users[id] = users[id].$set('words', {}))
  user.words[longid] = words
  if (action) {
    (user[action] || (user[action] = [])).push(longid)
  }
}
function existingSummary (date) {
  console.log('getting existing repos')
  try {
    return require('./data/events/' + date + '.json').activity || {}
  } catch (e) {
    return {}
  }
}

// let's get to work!...
var date = (process.argv[2] || Date.$nowISO()).substr(0, 10)
console.log('Summarizing ' + date);
(
  Date.$nowISO().substr(0, 10) === date // only get the totals for today!
  ? require('./github.js').get.all('/orgs/nodejs/repos?per_page=100')
    .then(repos =>
      repos.$keyBy('name').$mapValues(repo => getRepo(repo.name, repo.open_issues_count))
    )
  : Promise.resolve(
      existingSummary(date).$mapValues((repo, name) => getRepo(name, repo.open))
    )
)
.then(repos => {
  out.activity = repos

  util.events(date).forEach(e => {
    var handler = handlers[e.type]
    if (!handler) return
    handler(e, getRepo(e.repo))
  })

  // I want to compact some of the output, so special tokens are
  // first put in the JSON (find the toJSON function above) and
  // then those are replaced with single line JSON text below...
  const final = out.$json2
  .replace(/{\n\s+"open": \d+\n\s+}/g, x => x.replace(/\s+/g,''))
  .replace(/"<([^>]+)>"/g, function (match, path) {
    var issue = out.activity.$get(path.split('›'))
    delete issue.toJSON
    return issue.$json
  })

  require('fs').writeFileSync('./data/events/' + date + '.json', final)
})
.catch(console.error)

<commit_msg>sort repos by name<commit_after>'use strict'

require('extensions')
const util = require('./util.js')
const users = require('./data/users.json')

const out = {
  words: 0, // total for the day
  comments: 0,  // total for the day
  prs: { opened: 0, closed: 0, words: 0 },
  issues: { opened: 0, closed: 0, words: 0 },
  activity: {},
  users: {}
}
const getRepo = (name, open) => out.activity[name] || (out.activity[name] = {
  open: open,
  name: () => name // this is created as a function so it doesn't show in the JSON output
})
const getIssue = (repo, number) => repo[number] || (repo[number] = {
  comments: 0,
  words: 0,
  toJSON: () => `<${repo.name()}›${number}>` // add special tokens that get placed later
})
const handlers = {
  'IssuesEvent': (e, repo) => {
    var issue = require(`./data/repos/${e.repo}/issues.json`)[e.payload.issue]
    var i = getIssue(repo, e.payload.issue)
    var action = e.payload.action

    user(issue.user, e.repo, 'issues', e.payload.issue, issue.words, action)
    count.issue(issue.words, repo, i, action, issue.pr)

    i[action] = action === 'opened' ? issue.created_at : issue.closed_at
    i[action.replace('ed', 'er')] = e.actor
    if (issue.pr) i.pr = true
  },
  'PullRequestEvent': (e, repo) => {
    var issue = require(`./data/repos/${e.repo}/issues.json`)[e.payload.pull_request]
    var i = getIssue(repo, e.payload.pull_request)
    var action = e.payload.action

    user(issue.user, e.repo, 'pulls', e.payload.pull_request, issue.words, action)
    count.issue(issue.words, repo, i, action, true, e.repo)

    i.pr = true
    i[action] = action === 'opened' ? issue.created_at : issue.closed_at
    i[action.replace('ed', 'er')] = e.actor
  },
  'IssueCommentEvent': (e, repo) => {
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.comment]
    var i = getIssue(repo, e.payload.issue)
    count.comment(comment.words, repo, i, comment.pr ? true : undefined)
    user(comment.user, e.repo, comment.pr ? 'pulls' : 'issues', comment.number, comment.words, null, e.payload.comment)
  },
  'PullRequestReviewCommentEvent': (e, repo) => {
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.comment]
    var i = getIssue(repo, e.payload.pull_request)
    count.comment(comment.words, repo, i, true)
    user(comment.user, e.repo, 'pulls', comment.number, comment.words, null, e.payload.comment)
  },
  'CommitCommentEvent': (e, repo) => {
    if (!e.payload) return // initially, payloads were missed
    var comment = require(`./data/repos/${e.repo}/comments.json`)[e.payload.id]
    var i = getIssue(repo, e.payload.commit_id)
    count.comment(comment.words, repo, i, false)
    user(comment.user, e.repo, 'comments', comment.number, comment.words, null, e.payload.id)
  }
}
const count = {
  comment: function count (words, repo, issue, pr) {
    if (typeof pr !== 'undefined') issue.pr = pr
    issue.comments++
    out.comments++
    words = words || 0
    issue.words += words
    out.words += words
    repo.words = (repo.words || 0) + words
    repo.comments = (repo.comments || 0) + 1
    out[pr ? 'prs' : 'issues'].words += words
  },
  issue: function count (words, repo, issue, action, pr) {
    words = words || 0
    out.words += words
    repo.words = (repo.words || 0) + words
    issue.words = (issue.words || 0) + words
    repo[action] = (repo[action] || 0) + 1
    var type = out[pr ? 'prs' : 'issues']
    type.words += words
    type[action]++
  }
}

function user (id, repo, type, issue, words, action, commentid) {
  var longid = `${repo}/${type}/${issue}`
  if (commentid) longid += '#' + commentid
  var user = out.users[id] || (out.users[id] = users[id].$set('words', {}))
  user.words[longid] = words
  if (action) {
    (user[action] || (user[action] = [])).push(longid)
  }
}
function existingSummary (date) {
  console.log('getting existing repos')
  try {
    return require('./data/events/' + date + '.json').activity || {}
  } catch (e) {
    return {}
  }
}

// let's get to work!...
var date = (process.argv[2] || Date.$nowISO()).substr(0, 10)
console.log('Summarizing ' + date);
(
  Date.$nowISO().substr(0, 10) === date // only get the totals for today!
  ? require('./github.js').get.all('/orgs/nodejs/repos?per_page=100')
    .then(repos =>
      repos
      .$sortBy('name')
      .$keyBy('name')
      .$mapValues(repo => getRepo(repo.name, repo.open_issues_count))
    )
  : Promise.resolve(
      existingSummary(date).$mapValues((repo, name) => getRepo(name, repo.open))
    )
)
.then(repos => {
  out.activity = repos

  util.events(date).forEach(e => {
    var handler = handlers[e.type]
    if (!handler) return
    handler(e, getRepo(e.repo))
  })

  // I want to compact some of the output, so special tokens are
  // first put in the JSON (find the toJSON function above) and
  // then those are replaced with single line JSON text below...
  const final = out.$json2
  .replace(/{\n\s+"open": \d+\n\s+}/g, x => x.replace(/\s+/g,''))
  .replace(/"<([^>]+)>"/g, function (match, path) {
    var issue = out.activity.$get(path.split('›'))
    delete issue.toJSON
    return issue.$json
  })

  require('fs').writeFileSync('./data/events/' + date + '.json', final)
})
.catch(console.error)

<|endoftext|>


<commit_before>// Dependencies
var app = require('http').createServer(handler)
  , sio = require('socket.io').listen(app)
  , fs  = require('fs')
  , clients = {}

app.listen(8080, function() {
  var addr = app.address();
  console.log('listening on http://' + addr.address + ':' + addr.port);
});

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

sio.sockets.on('connection', function(socket) {
  var remote_addr = socket.handshake.address;
  // var id          = remote_addr.address + ':' + remote_addr.port;

  var id = 'foo';
  console.log(socket.remoteAddress);
  socket.set('id', id, function() {
    console.log(id);
    socket.emit('registered');
  });

  socket.on('message', function(socket) {
    console.log(socket.get('id'));
  });

  socket.on('disconnect', function() {

  })
});<commit_msg>first app<commit_after>// Dependencies
var app = require('http').createServer(handler)
  , sio = require('socket.io').listen(app)
  , fs  = require('fs')

app.listen(8080, function() {
  var addr = app.address();
  console.log('listening on http://' + addr.address + ':' + addr.port);
});

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

var clients = {};
sio.sockets.on('connection', function(socket) {
  var addr = socket.handshake.address.address + ':' + socket.handshake.address.port;
  socket.registered = false;

  socket.on('register', function() {
    socket.registered = true;
    if(!clients[addr]) {
      clients[addr] = socket;
      socket.emit('clients-up', clients);
      socket.broadcast.emit('clients-up', clients);
    }
  });

  socket.on('message', function(msg) {
    console.log(msg);
  })

  socket.on('disconnect', function() {
    delete clients[addr];
    socket.broadcast.emit('clients-up', clients);
  })
});<|endoftext|>


<commit_before>$(function () {
    "use strict";
    function log (x) {
        return x;
    }
    function makeEditable(o) {
        o.saveState = ko.observable('saved');
        o.editing = ko.observable(false);
        o.startEditing = function () {
            o.editing(true);
            try {
                o._backup = o.serialize();
            } catch (e) {

            }
        };
        o.stopEdit = function () {
            o.editing(false);
        };
        o.cancelEdit = function () {
            o.editing(false);
            o.cancel();
        };
        o.saveEdit = function () {
            o.editing(false);
            log(o);
            o.save();
        };
        return o;
    }
    function makeDataType(o, app) {
        var self = ko.mapping.fromJS(o),
            raw_fields = self.fields();
            self.original_tag = self.tag();
            self.original_visibility = self.is_global();
        self.fields = ko.observableArray([]);
        makeEditable(self);
        if (!o._id) {
            self._id = ko.observable();
        }
        self.view_link = ko.computed(function(){
            return TableViewUrl + "?table_id="+self._id();
        }, self);
        self.aboutToDelete = ko.observable(false);
        self.addField = function (data, event, o) {
            var i, field;
            if (o) {
                field = {
                    tag: ko.observable(o.tag),
                    with_props: ko.observable(o.with_props),
                    original_tag: ko.observable(o.tag),
                    is_new: ko.observable(false),
                    remove: ko.observable(false),
                    editing: ko.observable(false)
                };
            } else {
                field = {
                    tag: ko.observable(""),
                    with_props: ko.observable(false),
                    original_tag: ko.observable(""),
                    is_new: ko.observable(true),
                    remove: ko.observable(false),
                    editing: ko.observable(true)
                };
            }
            field.remove_if_new = function(){
                if (field.is_new() == true){
                    self.fields.remove(field);
                }
            };
            field.editTag = ko.computed({
                read: function () {
                    return field.tag();
                },
                write: function (tag) {
                    var j, noRepeats = true;
                    for (j = 0; j < self.fields().length; j += 1) {
                        if (self.fields()[j].tag === tag) {
                            noRepeats = false;
                        }
                    }
                    if (noRepeats) {
                        var oldTag = field.tag;
                        field.tag(tag);log(field);
                    }
                }
            });
            self.fields.push(field);
        };
        for (var i = 0; i < raw_fields.length; i += 1) {
            var tag = raw_fields[i].field_name();
            var with_props = (raw_fields[i].properties().length == 0) ? false : true; console.log(with_props);
            self.addField(undefined, undefined, {tag: tag, with_props: with_props});
        }

        self.save = function () {
            $.ajax({
                type: self._id() ? (self._destroy ? 'delete' : 'put') : 'post',
                url: UpdateTableUrl + (self._id() || ''),
                data: JSON.stringify(self.serialize()),
                dataType: 'json',
                success: function (data) {
                    self.saveState('saved');
                    if (!self._id()) {
                        self._id(data._id);
                    }
                    self.original_visibility = self.is_global();
                    console.log("came here");
                    var indicesToRemoveAt = [];
                    for (var i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        field.original_tag(field.tag());
                        field.is_new(false); console.log("coming here")
                        if (field.remove() == true){
                            indicesToRemoveAt.push(i);
                        }
                    }
                    for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                        var index = indicesToRemoveAt[j]
                        console.log(self.fields()[index]);
                        self.fields.remove(self.fields()[index]);
                    }
                    console.log(self);console.log("hello"); console.log(indicesToRemoveAt);
                }
            });
            self.saveState('saving');
        };
        self.cancel = function () {
            var indicesToRemoveAt = [];console.log(self);
            self.tag(self.original_tag);
            self.is_global(self.original_visibility);
            if (!o._id){ console.log("yeah delete");
                app.data_types.remove(self);
                return;
            }
            for (var i = 0; i < self.fields().length; i += 1) {
                var field = self.fields()[i];
                if (field.is_new() == true){
                    indicesToRemoveAt.push(i);
                    continue;
                }
                field.tag(field.original_tag());
                field.remove(false);
            }
            for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                var index = indicesToRemoveAt[j]
                console.log(self.fields()[index]);
                self.fields.remove(self.fields()[index]);
            }
        }
        self.serialize = function () {
            return log({
                _id: self._id(),
                tag: self.tag(),
                view_link: self.view_link(),
                is_global: self.is_global(),
                fields: (function () {
                    var fields = {}, i;
                    console.log(self.fields());
                    for (i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        var patch;
                        if (field.is_new() == true) {
                            if (field.remove() == true) continue;
                            patch = {"is_new": 1};
                            fields[field.tag()] = patch;
                        }
                        else if (field.remove() === true) {
                            patch = {"remove": 1};
                            fields[field.original_tag()] = patch;
                        }
                        else if (field.tag() !== field.original_tag()){
                            patch = {"update": field.tag()};
                            fields[field.original_tag()] = patch;
                        }
                        else {
                            patch = {};
                            fields[field.tag()] = patch;
                        }
                    }
                    return fields;
                }())
            });
        };
        return self;
    }
    function App() {
        var self = this;
        self.data_types = ko.observableArray([]);
        self.loading = ko.observable(0);
        self.selectedTables = ko.observableArray([]);

        self.updateSelectedTables = function(element, event) {
            var $elem = $(event.srcElement || event.currentTarget);
            var $checkboxes = $(".select-bulk");
            if ($elem.hasClass("toggle")){
                self.selectedTables.removeAll();
                if ($elem.data("all")) {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", true);
                        self.selectedTables.push(this.value);
                    });
                }
                else {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", false);
                    });
                }
            }
            if ($elem.hasClass("select-bulk")) {
                var table_id = $elem[0].value;
                if ($elem[0].checked) {
                    self.selectedTables.push(table_id);
                }
                else {
                    self.selectedTables.splice(self.selectedTables().indexOf(table_id), 1);
                }
            }
        };

        self.downloadExcels = function(element, event) {
            var tables = [];
            var FixtureUrl = FixtureDownloadUrl;
            if (self.selectedTables().length < 1)
                return;
            for (var i in self.selectedTables()) {
                tables.push(self.selectedTables()[i]);
                FixtureUrl = FixtureUrl + "table_id=" + self.selectedTables()[i] + "&";
            }
            $("#fixture-download").modal();
            if (tables.length > 0){
                $.ajax({
                    url: FixtureUrl,
                    dataType: 'json',
                }).success(function (response) {
                    $("#downloading").hide();
                    $("#download-complete").show();
                    $("#file-download-url").attr("href", FixtureFileDownloadUrl + "download_id=" + response.download_id);
                });
            }

        };

        self.addDataType = function () {
            var dataType = makeDataType({
                tag: "",
                fields: ko.observableArray([]),
                is_global: false,
            }, self);
            dataType.editing(true);
            self.data_types.push(dataType);
        };
        self.removeDataType = function (dataType) {
            if (confirm("Are you sure you want to delete the table '" + dataType.tag() + "'")){
                    self.data_types.destroy(dataType);
                    dataType.save();
            }
            return false;
        };
        self.loadData = function () {
            self.loading(self.loading() + 3);
            $.ajax({
                url: DataTypeUrl,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    var dataType;
                    for (var i = 0; i < data.length; i += 1) {
                        self.data_types.push(makeDataType(data[i], self));
                        dataType = self.data_types()[i];
                    }
                    self.loading(self.loading() - 1); log(data);
                }
            });
        };
    }
    function FileUpload() {
        this.file = ko.observable();
        var self = this;
        self.uploadExcels = function(element, event) {
            $("#uploadModal").modal({
                keyboard: false,
                backdrop: 'static'
            });
            $("#uploading").show();
            $("#uploadForm")[0].submit();
        };
    }

    var el = $('#fixtures-ui');
    var app = new App();
    ko.applyBindings(app, el.get(0));
    el.show();
    app.loadData();

    var uploadApp = new FileUpload();
    ko.applyBindings(uploadApp, $('#fixture-upload')[0]);

    $("#fixture-download").on("hidden", function(){
                    $("#downloading").show();
                    $("#download-complete").hide();
    });
});<commit_msg>remove console logging<commit_after>$(function () {
    "use strict";
    function log (x) {
        return x;
    }
    function makeEditable(o) {
        o.saveState = ko.observable('saved');
        o.editing = ko.observable(false);
        o.startEditing = function () {
            o.editing(true);
            try {
                o._backup = o.serialize();
            } catch (e) {

            }
        };
        o.stopEdit = function () {
            o.editing(false);
        };
        o.cancelEdit = function () {
            o.editing(false);
            o.cancel();
        };
        o.saveEdit = function () {
            o.editing(false);
            log(o);
            o.save();
        };
        return o;
    }
    function makeDataType(o, app) {
        var self = ko.mapping.fromJS(o),
            raw_fields = self.fields();
            self.original_tag = self.tag();
            self.original_visibility = self.is_global();
        self.fields = ko.observableArray([]);
        makeEditable(self);
        if (!o._id) {
            self._id = ko.observable();
        }
        self.view_link = ko.computed(function(){
            return TableViewUrl + "?table_id="+self._id();
        }, self);
        self.aboutToDelete = ko.observable(false);
        self.addField = function (data, event, o) {
            var i, field;
            if (o) {
                field = {
                    tag: ko.observable(o.tag),
                    with_props: ko.observable(o.with_props),
                    original_tag: ko.observable(o.tag),
                    is_new: ko.observable(false),
                    remove: ko.observable(false),
                    editing: ko.observable(false)
                };
            } else {
                field = {
                    tag: ko.observable(""),
                    with_props: ko.observable(false),
                    original_tag: ko.observable(""),
                    is_new: ko.observable(true),
                    remove: ko.observable(false),
                    editing: ko.observable(true)
                };
            }
            field.remove_if_new = function(){
                if (field.is_new() == true){
                    self.fields.remove(field);
                }
            };
            field.editTag = ko.computed({
                read: function () {
                    return field.tag();
                },
                write: function (tag) {
                    var j, noRepeats = true;
                    for (j = 0; j < self.fields().length; j += 1) {
                        if (self.fields()[j].tag === tag) {
                            noRepeats = false;
                        }
                    }
                    if (noRepeats) {
                        var oldTag = field.tag;
                        field.tag(tag);
                    }
                }
            });
            self.fields.push(field);
        };
        for (var i = 0; i < raw_fields.length; i += 1) {
            var tag = raw_fields[i].field_name();
            var with_props = (raw_fields[i].properties().length == 0) ? false : true;
            self.addField(undefined, undefined, {tag: tag, with_props: with_props});
        }

        self.save = function () {
            $.ajax({
                type: self._id() ? (self._destroy ? 'delete' : 'put') : 'post',
                url: UpdateTableUrl + (self._id() || ''),
                data: JSON.stringify(self.serialize()),
                dataType: 'json',
                success: function (data) {
                    self.saveState('saved');
                    if (!self._id()) {
                        self._id(data._id);
                    }
                    self.original_visibility = self.is_global();
                    var indicesToRemoveAt = [];
                    for (var i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        field.original_tag(field.tag());
                        field.is_new(false);
                        if (field.remove() == true){
                            indicesToRemoveAt.push(i);
                        }
                    }
                    for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                        var index = indicesToRemoveAt[j]
                        self.fields.remove(self.fields()[index]);
                    }
                }
            });
            self.saveState('saving');
        };
        self.cancel = function () {
            var indicesToRemoveAt = [];
            self.tag(self.original_tag);
            self.is_global(self.original_visibility);
            if (!o._id){
                app.data_types.remove(self);
                return;
            }
            for (var i = 0; i < self.fields().length; i += 1) {
                var field = self.fields()[i];
                if (field.is_new() == true){
                    indicesToRemoveAt.push(i);
                    continue;
                }
                field.tag(field.original_tag());
                field.remove(false);
            }
            for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                var index = indicesToRemoveAt[j]
                self.fields.remove(self.fields()[index]);
            }
        }
        self.serialize = function () {
            return log({
                _id: self._id(),
                tag: self.tag(),
                view_link: self.view_link(),
                is_global: self.is_global(),
                fields: (function () {
                    var fields = {}, i;
                    for (i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        var patch;
                        if (field.is_new() == true) {
                            if (field.remove() == true) continue;
                            patch = {"is_new": 1};
                            fields[field.tag()] = patch;
                        }
                        else if (field.remove() === true) {
                            patch = {"remove": 1};
                            fields[field.original_tag()] = patch;
                        }
                        else if (field.tag() !== field.original_tag()){
                            patch = {"update": field.tag()};
                            fields[field.original_tag()] = patch;
                        }
                        else {
                            patch = {};
                            fields[field.tag()] = patch;
                        }
                    }
                    return fields;
                }())
            });
        };
        return self;
    }
    function App() {
        var self = this;
        self.data_types = ko.observableArray([]);
        self.loading = ko.observable(0);
        self.selectedTables = ko.observableArray([]);

        self.updateSelectedTables = function(element, event) {
            var $elem = $(event.srcElement || event.currentTarget);
            var $checkboxes = $(".select-bulk");
            if ($elem.hasClass("toggle")){
                self.selectedTables.removeAll();
                if ($elem.data("all")) {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", true);
                        self.selectedTables.push(this.value);
                    });
                }
                else {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", false);
                    });
                }
            }
            if ($elem.hasClass("select-bulk")) {
                var table_id = $elem[0].value;
                if ($elem[0].checked) {
                    self.selectedTables.push(table_id);
                }
                else {
                    self.selectedTables.splice(self.selectedTables().indexOf(table_id), 1);
                }
            }
        };

        self.downloadExcels = function(element, event) {
            var tables = [];
            var FixtureUrl = FixtureDownloadUrl;
            if (self.selectedTables().length < 1)
                return;
            for (var i in self.selectedTables()) {
                tables.push(self.selectedTables()[i]);
                FixtureUrl = FixtureUrl + "table_id=" + self.selectedTables()[i] + "&";
            }
            $("#fixture-download").modal();
            if (tables.length > 0){
                $.ajax({
                    url: FixtureUrl,
                    dataType: 'json',
                }).success(function (response) {
                    $("#downloading").hide();
                    $("#download-complete").show();
                    $("#file-download-url").attr("href", FixtureFileDownloadUrl + "download_id=" + response.download_id);
                });
            }

        };

        self.addDataType = function () {
            var dataType = makeDataType({
                tag: "",
                fields: ko.observableArray([]),
                is_global: false,
            }, self);
            dataType.editing(true);
            self.data_types.push(dataType);
        };
        self.removeDataType = function (dataType) {
            if (confirm("Are you sure you want to delete the table '" + dataType.tag() + "'")){
                    self.data_types.destroy(dataType);
                    dataType.save();
            }
            return false;
        };
        self.loadData = function () {
            self.loading(self.loading() + 3);
            $.ajax({
                url: DataTypeUrl,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    var dataType;
                    for (var i = 0; i < data.length; i += 1) {
                        self.data_types.push(makeDataType(data[i], self));
                        dataType = self.data_types()[i];
                    }
                    self.loading(self.loading() - 1);
                }
            });
        };
    }
    function FileUpload() {
        this.file = ko.observable();
        var self = this;
        self.uploadExcels = function(element, event) {
            $("#uploadModal").modal({
                keyboard: false,
                backdrop: 'static'
            });
            $("#uploading").show();
            $("#uploadForm")[0].submit();
        };
    }

    var el = $('#fixtures-ui');
    var app = new App();
    ko.applyBindings(app, el.get(0));
    el.show();
    app.loadData();

    var uploadApp = new FileUpload();
    ko.applyBindings(uploadApp, $('#fixture-upload')[0]);

    $("#fixture-download").on("hidden", function(){
                    $("#downloading").show();
                    $("#download-complete").hide();
    });
});<|endoftext|>


<commit_before>function ddg_spice_lastfm_top_tracks(api_result) {
    Spice.render({
        data             : api_result,
        force_big_header : true,
        header1          : "Top Songs (" + api_result.toptracks["@attr"].country + ")",
        source_name      : "Last.fm",
        source_url       : "http://www.last.fm/charts/tracks/top",
        template_normal  : "top"
    });
}

Handlebars.registerHelper('list', function(items, options) {
    var out = "";
    for(var i = 0; i < items.length && i < 5; i += 1) {
        out += options.fn(items[i]);
    }
    return out;
});<commit_msg>LastfmTop: Should now point to the right template.<commit_after>function ddg_spice_lastfm_top_tracks(api_result) {
    Spice.render({
        data             : api_result,
        force_big_header : true,
        header1          : "Top Songs (" + api_result.toptracks["@attr"].country + ")",
        source_name      : "Last.fm",
        source_url       : "http://www.last.fm/charts/tracks/top",
        template_normal  : "lastfm_top_tracks"
    });
}

Handlebars.registerHelper('list', function(items, options) {
    var out = "";
    for(var i = 0; i < items.length && i < 5; i += 1) {
        out += options.fn(items[i]);
    }
    return out;
});<|endoftext|>


<commit_before>var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);
var debug = require('debug')('n2k-signalk:test:130312');
var _ = require('lodash');

var msgs = require('./130310-2.json');

describe('Temperature: ', function() {
  it("examples work", function() {
    var n2kMapper = require("../n2kMapper.js");
    var full = new(require('signalk-schema').FullSignalK)();
    _.forOwn(msgs, function(msg, key) {
      var delta = n2kMapper.toDelta(msg);
      delta.context = 'vessels.urn:mrn:imo:mmsi:230099999';
      full.addDelta(delta);
      delta.should.be.validSignalKDelta;
      delta.updates[0].values.forEach(function(pathValue) {
      })
    })
    var fullDoc = full.retrieve();
    fullDoc.vessels['urn:mrn:imo:mmsi:230099999'].mmsi = '230099999';
    fullDoc.should.be.validSignalK;
  })

  it("all 130312 mappings are valid", function() {
    var temperatureMappings = require("../n2kMappings").temperatureMappings;
    var full = new(require('signalk-schema').FullSignalK)();
    _.forOwn(temperatureMappings, function(mapping, key) {
      var delta = {
        context: 'vessels.urn:mrn:imo:mmsi:230099999',
        updates: [{
          source: {
            "label": "",
            "type": "NMEA2000",
            "pgn": 130312,
            "src": "36",
            "instance": "0"
          },
          timestamp: '',
          values: [{
            path: mapping.path,
            value: 0
          }]
        }]
      }
      full.addDelta(delta);
    })
    var fullDoc = full.retrieve();
    //console.log(JSON.stringify(fullDoc, null, 2));
    fullDoc.vessels['urn:mrn:imo:mmsi:230099999'].mmsi = '230099999';
    fullDoc.should.be.validSignalK;
  })
});
<commit_msg>Fix tests to account for signalk-schema change<commit_after>var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);
var debug = require('debug')('n2k-signalk:test:130312');
var _ = require('lodash');

var msgs = require('./130310-2.json');

describe('Temperature: ', function() {
  it("examples work", function() {
    var n2kMapper = require("../n2kMapper.js");
    var full = new(require('signalk-schema').FullSignalK)("urn:mrn:imo:mmsi:230099999");
    _.forOwn(msgs, function(msg, key) {
      var delta = n2kMapper.toDelta(msg);
      delta.context = 'vessels.urn:mrn:imo:mmsi:230099999';
      full.addDelta(delta);
      delta.should.be.validSignalKDelta;
      delta.updates[0].values.forEach(function(pathValue) {
      })
    })
    var fullDoc = full.retrieve();
    fullDoc.vessels['urn:mrn:imo:mmsi:230099999'].mmsi = '230099999';
    fullDoc.should.be.validSignalK;
  })

  it("all 130312 mappings are valid", function() {
    var temperatureMappings = require("../n2kMappings").temperatureMappings;
    var full = new(require('signalk-schema').FullSignalK)("urn:mrn:imo:mmsi:230099999");
    _.forOwn(temperatureMappings, function(mapping, key) {
      var delta = {
        context: 'vessels.urn:mrn:imo:mmsi:230099999',
        updates: [{
          source: {
            "label": "",
            "type": "NMEA2000",
            "pgn": 130312,
            "src": "36",
            "instance": "0"
          },
          timestamp: '',
          values: [{
            path: mapping.path,
            value: 0
          }]
        }]
      }
      full.addDelta(delta);
    })
    var fullDoc = full.retrieve();
    //console.log(JSON.stringify(fullDoc, null, 2));
    fullDoc.vessels['urn:mrn:imo:mmsi:230099999'].mmsi = '230099999';
    fullDoc.should.be.validSignalK;
  })
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';

class PostsIndex extends Component {
  componentDidMount() {
      this.props.fetchPosts();
  }

  renderPosts(){
    return _.map(this.props.posts, post => {
      return (

          {post.title}

      );
    });
  }

  render(){
    return (

Post

          {this.renderPosts()}

    );
  }
}

function mapStateToProps(state){
    return { posts: state.posts };
}

export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
<commit_msg>Adding new post button on root<commit_after>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';

class PostsIndex extends Component {
  componentDidMount() {
      this.props.fetchPosts();
  }

  renderPosts(){
    return _.map(this.props.posts, post => {
      return (

          {post.title}

      );
    });
  }

  render(){
    return (

          <Link className="btn btn-primary" to="/posts/new">
            Add a Post
          </Link>

Post

          {this.renderPosts()}

    );
  }
}

function mapStateToProps(state){
    return { posts: state.posts };
}

export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
<|endoftext|>


<commit_before>'use babel';

import fs from 'fs';
import path from 'path';

const uniquifySettings = (settings) => {
  const genName = (name, index) => `${name} - ${index}`;
  const newSettings = [];
  settings.forEach(setting => {
    let i = 0;
    let testName = setting.name;
    while (newSettings.find(ns => ns.name === testName)) { // eslint-disable-line no-loop-func
      testName = genName(setting.name, ++i);
    }
    newSettings.push({ ...setting, name: testName });
  });
  return newSettings;
};

const activePath = () => {
  const textEditor = atom.workspace.getActiveTextEditor();
  if (!textEditor || !textEditor.getPath()) {
    /* default to building the first one if no editor is active */
    if (0 === atom.project.getPaths().length) {
      return false;
    }

    return atom.project.getPaths()[0];
  }

  /* otherwise, build the one in the root of the active editor */
  return atom.project.getPaths().sort((a, b) => (b.length - a.length)).find(p => {
    try {
      const realpath = fs.realpathSync(p);
      return textEditor.getPath().substr(0, realpath.length) === realpath;
    } catch (err) {
      /* Path no longer available. Possible network volume has gone down */
      return false;
    }
  });
};

const getDefaultSettings = (cwd, setting) => {
  return Object.assign({}, setting, {
    env: setting.env || {},
    args: setting.args || [],
    cwd: setting.cwd || cwd,
    sh: (undefined === setting.sh) ? true : setting.sh,
    errorMatch: setting.errorMatch || ''
  });
};

const replace = (value = '', targetEnv) => {
  if (!(typeof value === 'string')) {
    return value;
  }

  const env = Object.assign({}, process.env, targetEnv);
  value = value.replace(/\$(\w+)/g, function (match, name) {
    return name in env ? env[name] : match;
  });

  const editor = atom.workspace.getActiveTextEditor();

  const projectPaths = atom.project.getPaths().map(projectPath => {
    try {
      return fs.realpathSync(projectPath);
    } catch (e) { /* Do nothing. */ }
    return null;
  });

  let projectPath = projectPaths[0];
  if (editor && (undefined !== editor.getPath())) {
    const activeFile = fs.realpathSync(editor.getPath());
    const activeFilePath = path.dirname(activeFile);
    projectPath = projectPaths.find(p => activeFilePath && activeFilePath.startsWith(p));
    value = value.replace(/{FILE_ACTIVE}/g, activeFile);
    value = value.replace(/{FILE_ACTIVE_PATH}/g, activeFilePath);
    value = value.replace(/{FILE_ACTIVE_NAME}/g, path.basename(activeFile));
    value = value.replace(/{FILE_ACTIVE_NAME_BASE}/g, path.basename(activeFile, path.extname(activeFile)));
    value = value.replace(/{SELECTION}/g, editor.getSelectedText());
  }
  value = value.replace(/{PROJECT_PATH}/g, projectPath);
  if (atom.project.getRepositories[0]) {
    value = value.replace(/{REPO_BRANCH_SHORT}/g, atom.project.getRepositories()[0].getShortHead());
  }

  return value;
};

export { uniquifySettings, activePath, getDefaultSettings, replace };
<commit_msg>Fix issue with incorrect path for text editor<commit_after>'use babel';

import fs from 'fs';
import path from 'path';

const uniquifySettings = (settings) => {
  const genName = (name, index) => `${name} - ${index}`;
  const newSettings = [];
  settings.forEach(setting => {
    let i = 0;
    let testName = setting.name;
    while (newSettings.find(ns => ns.name === testName)) { // eslint-disable-line no-loop-func
      testName = genName(setting.name, ++i);
    }
    newSettings.push({ ...setting, name: testName });
  });
  return newSettings;
};

const activePath = () => {
  const textEditor = atom.workspace.getActiveTextEditor();
  if (!textEditor || !textEditor.getPath()) {
    /* default to building the first one if no editor is active */
    if (0 === atom.project.getPaths().length) {
      return false;
    }

    return atom.project.getPaths()[0];
  }

  /* otherwise, build the one in the root of the active editor */
  return atom.project.getPaths().sort((a, b) => (b.length - a.length)).find(p => {
    try {
      const realpath = fs.realpathSync(p);
      return fs.realpathSync(textEditor.getPath()).substr(0, realpath.length) === realpath;
    } catch (err) {
      /* Path no longer available. Possible network volume has gone down */
      return false;
    }
  });
};

const getDefaultSettings = (cwd, setting) => {
  return Object.assign({}, setting, {
    env: setting.env || {},
    args: setting.args || [],
    cwd: setting.cwd || cwd,
    sh: (undefined === setting.sh) ? true : setting.sh,
    errorMatch: setting.errorMatch || ''
  });
};

const replace = (value = '', targetEnv) => {
  if (!(typeof value === 'string')) {
    return value;
  }

  const env = Object.assign({}, process.env, targetEnv);
  value = value.replace(/\$(\w+)/g, function (match, name) {
    return name in env ? env[name] : match;
  });

  const editor = atom.workspace.getActiveTextEditor();

  const projectPaths = atom.project.getPaths().map(projectPath => {
    try {
      return fs.realpathSync(projectPath);
    } catch (e) { /* Do nothing. */ }
    return null;
  });

  let projectPath = projectPaths[0];
  if (editor && (undefined !== editor.getPath())) {
    const activeFile = fs.realpathSync(editor.getPath());
    const activeFilePath = path.dirname(activeFile);
    projectPath = projectPaths.find(p => activeFilePath && activeFilePath.startsWith(p));
    value = value.replace(/{FILE_ACTIVE}/g, activeFile);
    value = value.replace(/{FILE_ACTIVE_PATH}/g, activeFilePath);
    value = value.replace(/{FILE_ACTIVE_NAME}/g, path.basename(activeFile));
    value = value.replace(/{FILE_ACTIVE_NAME_BASE}/g, path.basename(activeFile, path.extname(activeFile)));
    value = value.replace(/{SELECTION}/g, editor.getSelectedText());
  }
  value = value.replace(/{PROJECT_PATH}/g, projectPath);
  if (atom.project.getRepositories[0]) {
    value = value.replace(/{REPO_BRANCH_SHORT}/g, atom.project.getRepositories()[0].getShortHead());
  }

  return value;
};

export { uniquifySettings, activePath, getDefaultSettings, replace };
<|endoftext|>


<commit_before>"use babel";

// ----------------------------------------------------------------------------
//  auto id class
// ----------------------------------------------------------------------------
import { CompositeDisposable } from "atom";

export default {
  subscriptions: null,

  /*
   * Activate
   * Subscribe key mappings to methods
   */

  // can consume state: activate(state) {
  activate() {
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      atom.commands.add("atom-text-editor", {
        "auto-id-class:insert_id_attribute": () => this.insert_id_attribute()
      })
    );
    this.subscriptions.add(
      atom.commands.add("atom-text-editor", {
        "auto-id-class:insert_class_attribute": () =>
          this.insert_class_attribute()
      })
    );
  },

  /*
   * Insert ID attribute method
   */
  insert_id_attribute() {
    if (this.cursor_inside_html_tag() || this.cursor_inside_jsx_html_tag()) {
      return this.insert_attribute("id");
    }

    return event.abortKeyBinding();
  },

  /*
   * Insert Class attribute method
   */
  insert_class_attribute() {
    if (this.cursor_inside_html_tag()) {
      return this.insert_attribute("class");
    } else if (this.cursor_inside_jsx_html_tag()) {
      return this.insert_attribute("className");
    }

    return event.abortKeyBinding();
  },

  /*
   * Check if cursor is within an HTML tag
   * returns {Bool}
   */
  cursor_inside_html_tag() {
    const editor = atom.workspace.getActiveTextEditor();
    let cursor;
    if (!editor) {
      return false;
    }

    // Get cursor
    if (editor.cursors) {
      cursor = editor.cursors[0];
    } else {
      return false;
    }

    // Get cursor position and scope
    const cursorBufferPos = cursor.getBufferPosition();
    const cursorScopes = editor.scopeDescriptorForBufferPosition(
      cursorBufferPos
    ).scopes;

    // Checking scope strings against the scope descriptions.
    // First, check if cursor within HTML scope description:
    if (cursorScopes[0] && cursorScopes[0].search("text.html") < 0) {
      return false;
    }

    // Within tag types:
    if (cursorScopes[1] && cursorScopes[1].search("meta.tag..*.html") < 0) {
      return false;
    }

    // Invalid cursor scope positions:
    const scopesToSkip = [
      "string.quoted.double.html",
      "string.quoted.single.html",
      "entity.other.attribute-name.html"
    ];
    // iterate through every scope, check is it among forbidden-ones
    for (let i = scopesToSkip.length; i--; ) {
      if (cursorScopes.includes(scopesToSkip[i])) {
        return false;
      }
    }

    // Finally is the cursor truly within an html tag? Check for < and > chars now
    // Get the cursors current column and line of buffer for evaluation
    const cursorColumn = cursorBufferPos.column;
    const bufferLine = cursor.getCurrentBufferLine();
    const codeLeftOfColumn = bufferLine.substring(0, cursorColumn);
    const codeRightOfColumn = bufferLine.substring(
      cursorColumn,
      bufferLine.length
    );

    // Is the cursor within < and > ? Exit if not
    if (
      codeLeftOfColumn.lastIndexOf("<") <= codeLeftOfColumn.lastIndexOf(">")
    ) {
      return false;
    }
    if (
      codeRightOfColumn.lastIndexOf(">") <= codeRightOfColumn.lastIndexOf("<")
    ) {
      return false;
    }

    // TODO: check if cursor within { curly braces } within an html tag and return false
    // as this can be very annoying when trying to use . and # within Angular tags

    // Made it this far? Must be worthy of a class or id attribute
    return true;
  },

  cursor_inside_jsx_html_tag() {
    const editor = atom.workspace.getActiveTextEditor();
    let cursor;
    if (!editor) {
      return false;
    }

    // Get cursor
    if (editor.cursors) {
      cursor = editor.cursors[0];
    } else {
      return false;
    }

    // Get cursor position and scope
    const cursorBufferPos = cursor.getBufferPosition();
    const cursorScopes = editor.scopeDescriptorForBufferPosition(
      cursorBufferPos
    ).scopes;

    // Checking scope strings against the scope descriptions.
    // First, check if cursor within HTML scope description:
    if (cursorScopes[0] && cursorScopes[0].search("source.js") < 0) {
      return false;
    }

    // Within tag types:
    if (cursorScopes[3] && cursorScopes[3].search("meta.tag.jsx") < 0) {
      return false;
    }

    // Invalid cursor scope positions:
    if (cursorScopes[5]) {
      switch (cursorScopes[5]) {
        case "string.quoted.double.js":
          return false;
        case "entity.other.attribute-name.js":
          return false;
      }
    }

    // Finally is the cursor truly within an html tag? Check for < and > chars now
    // Get the cursors current column and line of buffer for evaluation
    const cursorColumn = cursorBufferPos.column;
    const bufferLine = cursor.getCurrentBufferLine();
    const codeLeftOfColumn = bufferLine.substring(0, cursorColumn);
    const codeRightOfColumn = bufferLine.substring(
      cursorColumn,
      bufferLine.length
    );

    // Is the cursor within < and > ? Exit if not
    if (
      codeLeftOfColumn.lastIndexOf("<") <= codeLeftOfColumn.lastIndexOf(">")
    ) {
      return false;
    }
    if (
      codeRightOfColumn.lastIndexOf(">") <= codeRightOfColumn.lastIndexOf("<")
    ) {
      return false;
    }

    return true;
  },

  /*
   * Insert attribute by string
   */
  insert_attribute(attrType) {
    const editor = atom.workspace.getActiveTextEditor();

    // Insert space, attribute and =""
    // TODO: Don't add space char if already present
    editor.insertText(` ${attrType}=""`);

    // Move cursor back into quotes "|"
    return atom.workspace.getActiveTextEditor().cursors[0].moveLeft(1);
  },

  /*
   * Deactivate
   */
  deactivate() {
    return this.subscriptions.dispose();
  }
};
<commit_msg>feat: disable in closing HTML tags. Fix #1<commit_after>"use babel";

// ----------------------------------------------------------------------------
//  auto id class
// ----------------------------------------------------------------------------
import { CompositeDisposable } from "atom";

export default {
  subscriptions: null,

  /*
   * Activate
   * Subscribe key mappings to methods
   */

  // can consume state: activate(state) {
  activate() {
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      atom.commands.add("atom-text-editor", {
        "auto-id-class:insert_id_attribute": () => this.insert_id_attribute()
      })
    );
    this.subscriptions.add(
      atom.commands.add("atom-text-editor", {
        "auto-id-class:insert_class_attribute": () =>
          this.insert_class_attribute()
      })
    );
  },

  /*
   * Insert ID attribute method
   */
  insert_id_attribute() {
    if (this.cursor_inside_html_tag() || this.cursor_inside_jsx_html_tag()) {
      return this.insert_attribute("id");
    }

    return event.abortKeyBinding();
  },

  /*
   * Insert Class attribute method
   */
  insert_class_attribute() {
    if (this.cursor_inside_html_tag()) {
      return this.insert_attribute("class");
    } else if (this.cursor_inside_jsx_html_tag()) {
      return this.insert_attribute("className");
    }

    return event.abortKeyBinding();
  },

  /*
   * Check if cursor is within an HTML tag
   * returns {Bool}
   */
  cursor_inside_html_tag() {
    const editor = atom.workspace.getActiveTextEditor();
    let cursor;
    if (!editor) {
      return false;
    }

    // Get cursor
    if (editor.cursors) {
      cursor = editor.cursors[0];
    } else {
      return false;
    }

    // Get cursor position and scope
    const cursorBufferPos = cursor.getBufferPosition();
    const cursorScopes = editor.scopeDescriptorForBufferPosition(
      cursorBufferPos
    ).scopes;

    // Checking scope strings against the scope descriptions.
    // First, check if cursor within HTML scope description:
    if (cursorScopes[0] && cursorScopes[0].search("text.html") < 0) {
      return false;
    }

    // Within tag types:
    if (cursorScopes[1] && cursorScopes[1].search("meta.tag..*.html") < 0) {
      return false;
    }

    // Invalid cursor scope positions:
    const scopesToSkip = [
      "string.quoted.double.html",
      "string.quoted.single.html",
      "entity.other.attribute-name.html"
    ];
    // iterate through every scope, check is it among forbidden-ones
    for (let i = scopesToSkip.length; i--; ) {
      if (cursorScopes.includes(scopesToSkip[i])) {
        return false;
      }
    }

    // Finally is the cursor truly within an html tag? Check for < and > chars now
    // Get the cursors current column and line of buffer for evaluation
    const cursorColumn = cursorBufferPos.column;
    const bufferLine = cursor.getCurrentBufferLine();
    const codeLeftOfColumn = bufferLine.substring(0, cursorColumn);
    const codeRightOfColumn = bufferLine.substring(
      cursorColumn,
      bufferLine.length
    );

    // Is the cursor within < and > ? Exit if not
    if (
      codeLeftOfColumn.lastIndexOf("<") <= codeLeftOfColumn.lastIndexOf(">")
    ) {
      return false;
    }
    if (
      codeRightOfColumn.lastIndexOf(">") <= codeRightOfColumn.lastIndexOf("<")
    ) {
      return false;
    }

    // Is cursor within a closing tag?
    if (
      codeLeftOfColumn.lastIndexOf("/") ===
      codeLeftOfColumn.lastIndexOf("<") + 1
    ) {
      return false;
    }

    // TODO: check if cursor within { curly braces } within an html tag and return false
    // as this can be very annoying when trying to use . and # within Angular tags

    // Made it this far? Must be worthy of a class or id attribute
    return true;
  },

  cursor_inside_jsx_html_tag() {
    const editor = atom.workspace.getActiveTextEditor();
    let cursor;
    if (!editor) {
      return false;
    }

    // Get cursor
    if (editor.cursors) {
      cursor = editor.cursors[0];
    } else {
      return false;
    }

    // Get cursor position and scope
    const cursorBufferPos = cursor.getBufferPosition();
    const cursorScopes = editor.scopeDescriptorForBufferPosition(
      cursorBufferPos
    ).scopes;

    // Checking scope strings against the scope descriptions.
    // First, check if cursor within HTML scope description:
    if (cursorScopes[0] && cursorScopes[0].search("source.js") < 0) {
      return false;
    }

    // Within tag types:
    if (cursorScopes[3] && cursorScopes[3].search("meta.tag.jsx") < 0) {
      return false;
    }

    // Invalid cursor scope positions:
    if (cursorScopes[5]) {
      switch (cursorScopes[5]) {
        case "string.quoted.double.js":
          return false;
        case "entity.other.attribute-name.js":
          return false;
      }
    }

    // Finally is the cursor truly within an html tag? Check for < and > chars now
    // Get the cursors current column and line of buffer for evaluation
    const cursorColumn = cursorBufferPos.column;
    const bufferLine = cursor.getCurrentBufferLine();
    const codeLeftOfColumn = bufferLine.substring(0, cursorColumn);
    const codeRightOfColumn = bufferLine.substring(
      cursorColumn,
      bufferLine.length
    );

    // Is the cursor within < and > ? Exit if not
    if (
      codeLeftOfColumn.lastIndexOf("<") <= codeLeftOfColumn.lastIndexOf(">")
    ) {
      return false;
    }
    if (
      codeRightOfColumn.lastIndexOf(">") <= codeRightOfColumn.lastIndexOf("<")
    ) {
      return false;
    }

    return true;
  },

  /*
   * Insert attribute by string
   */
  insert_attribute(attrType) {
    const editor = atom.workspace.getActiveTextEditor();

    // Insert space, attribute and =""
    // TODO: Don't add space char if already present
    editor.insertText(` ${attrType}=""`);

    // Move cursor back into quotes "|"
    return atom.workspace.getActiveTextEditor().cursors[0].moveLeft(1);
  },

  /*
   * Deactivate
   */
  deactivate() {
    return this.subscriptions.dispose();
  }
};
<|endoftext|>


<commit_before>~function(e,t,a){return a=function(e){return t.querySelector(e)},a.all=function(e){return t.querySelectorAll(e)},a.getJSON=function(t){if(e.fetch){tmp="?";for(a in t.data)tmp+=a.toString()+"="+t.data[a].toString()+"&";("&"==tmp.charAt(tmp.length-1)||"?"==tmp.charAt(tmp.length-1))&&(tmp=tmp.substring(0,tmp.length-1));var n=t.url+tmp;console.log(n);var s={method:"GET",mode:"cors",headers:{"Content-Type":"application/x-www-form-urlencoded"}};fetch(n,s).then(function(e){return e.ok?e.json().then(function(e){t.success(e)}):void console.log("Looks like the response wasn't perfect, got status",e.status)})["catch"](function(e){console.log("Fetch failed!",e)})}},a["class"]={has:function(e,t){return null!==e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))},add:function(e,t){a["class"].has(e,t)||(0===e.className.length?e.className=t:e.className+=" "+t)},remove:function(e,t){if(console.log("dom->",e),a["class"].has(e,t)){var n=e.className.split(" ");for(var s in n)if(n[s]===t){n.splice(s,1),e.className=n.join(" ");break}}},replace:function(){}},a.img={lazyload:function(t){function n(e){for(var t=e.offsetTop;e=e.offsetParent;)t+=e.offsetTop;return t}function r(){var e=a(".container").scrollTop;[].forEach.call(s,function(a){a.getAttribute("data-src")&&o+e+t>n(a)&&(a.src=a.getAttribute("data-src"),a.removeAttribute("data-src"))})}var s=document.body.querySelectorAll(".lazyload"),o=e.innerHeight,t=t||1e3;r(),a(".container").addEventListener("scroll",r)}},"undefined"==typeof $?$=a:NaN,a}(window,document);<commit_msg>clean code<commit_after>~function(e,t,a){return a=function(e){return t.querySelector(e)},a.all=function(e){return t.querySelectorAll(e)},a.getJSON=function(t){if(e.fetch){tmp="?";for(a in t.data)tmp+=a.toString()+"="+t.data[a].toString()+"&";("&"==tmp.charAt(tmp.length-1)||"?"==tmp.charAt(tmp.length-1))&&(tmp=tmp.substring(0,tmp.length-1));var n=t.url+tmp,s={method:"GET",mode:"cors",headers:{"Content-Type":"application/x-www-form-urlencoded"}};fetch(n,s).then(function(e){return e.ok?e.json().then(function(e){t.success(e)}):void console.log("Looks like the response wasn't perfect, got status",e.status)})["catch"](function(e){console.log("Fetch failed!",e)})}},a["class"]={has:function(e,t){return null!==e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))},add:function(e,t){a["class"].has(e,t)||(0===e.className.length?e.className=t:e.className+=" "+t)},remove:function(e,t){if(a["class"].has(e,t)){var n=e.className.split(" ");for(var s in n)if(n[s]===t){n.splice(s,1),e.className=n.join(" ");break}}},replace:function(){}},a.img={lazyload:function(t){function n(e){for(var t=e.offsetTop;e=e.offsetParent;)t+=e.offsetTop;return t}function o(){var e=a(".container").scrollTop;[].forEach.call(s,function(a){a.getAttribute("data-src")&&r+e+t>n(a)&&(a.src=a.getAttribute("data-src"),a.removeAttribute("data-src"))})}var s=document.body.querySelectorAll(".lazyload"),r=e.innerHeight,t=t||1e3;o(),a(".container").addEventListener("scroll",o)}},"undefined"==typeof $?$=a:NaN,a}(window,document);<|endoftext|>