<commit_before>import React from "react";
import { Container } from "reactstrap";
import './styles.scss'
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Remarkable = require('remarkable');

const md = new Remarkable();
md.set({
  breaks: true,
  linkify: true
});

const Contents = () => (
   <React.Fragment>

Welcome to the 1st Draft!

Contents

 The World Needs This Because: (v1)

The World Needs This Because: (v2)

1. Abstract

      	1.1. Background

      	1.2. Public Happiness Movement Token Introduction

2. Problem Statement

      	2.1. Issues we aim to solve

      	2.2. Primary Goal

      	2.3. Secondary Goal

      	2.4. Relation to Universal Basic Income

3. Educating the Public about Blockchain

      	3.1. Current State of Public Understanding

      	3.2. Reaching a New Audience

4. The Public Happiness Movement Token

      	4.1. Token Overview

5. Public Happiness Movement Token ICO

      	5.1. ICO Strategy

      	5.2. ICO Stages

      	5.3. Ongoing Funding for Specific Projects and Experts

      	5.4. ICO Marketing

6. Public Happiness – Background

      	6.1. Community Background

      	6.2. The Public Happiness Movement Community

7. Platform Overview

      	7.1. The Public Happiness Map (public actions for increasing human and society well-being)

      	7.2. Action Center (Microvolunteering)

      	7.3. Community News

      	7.4. Active Happiness Shop

      	7.5. Who Defines What is Accepted as ‘Public Happiness’

      	7.6. Evidence Based and Peer Reviewed Actions

      	7.7. Who can Participate on the Platform

      	7.8. Pre-existing Communities with Similar Values

      	7.9. Languages

      	7.10. Decentralised Governance and Voting

8. The Path to Decentralisation

      	8.1. Benevolent Dictatorship vs Complete Community Governance

      	8.2. Example Scenario: Outside Collusion

      	8.3. Lines of Defence

      	8.4. Conclusion

9. Security

      	9.1. Levels of Trust

      	9.2.. Community Administrators

      	9.3. Project Administrators

      	9.4. Mining Limits

      	9.5. Cold Storage and Key Holders

10. Marketing Strategy

      	10.1. A New Level of Hash Tagging

      	10.2. Bus Tour

      	10.3.. Public Happiness Channel

      	10.4. Happy Cam

      	10.5. Public Happiness Partners

      	10.6. Online Supporters

      	10.7. Contests

      	10.8. Collectables

11.  Automated Token Distribution Matrix

      	11.1. Weighted Mining

      	11.2. Hard Cap

      	11.3. Adjusting the Balancing

      	11.4. Token Release

      	11.5. Mining Table

      	11.6. Experience Multipliers

      	11.7. Token Distribution

      	11.8. Further Matrix Considerations

12. Team

      	12.1. Current Team Members

      	12.2. Positions Open

      	12.3. Remuneration

      	12.4. Facilities

13. Platform Technicals

      	13.1. Crypto Linking Bridges

      	13.2. Trello vs Wekan vs Other Solutions

      	13.3. Leaflet.js vs Google Maps API

      	13.4. Switching the Platform to the Dapps Network

14. Doomsday Protocol

      	14.1. Huge Market Crash

      	14.2. Quantum Security

      	14.3. Massive Hack

      	14.4. Zombie Apocalypse

15. Giving Back to Open-source

16. Timeline

17. White Paper Reviewed By

18. Questions to be Resolved

 </React.Fragment>
 )

const markdownSection1 = md.render(`
# Public Happiness Movement Token
# Whitepaper

**Foreword:**

I've lived about as frugal a life as is possible in the Western World because I've always disliked money.  It so often seems to have a negative effect on people and society.

The crypto-world has me intensely curious, because money can be different there. I wanted to learn more and see if it's possible to design a form of money that is intrinsically tied to creating societal value.  Something to act as a band-aid on today’s ‘profit at all costs’ capitalism which has blind-spots for large areas critical to producing healthy, happy societies. This is caused by foundations measuring all progress and success as an increase in GDP. Anything which doesn’t is, by design, an after-thought.

GDP was designed by Simon Kuznets, in 1937 as a temporary post war recovery system, but the beast got out of control. The damage caused to humanity by basing our decision making processes on measurements of GDP isn’t even contentious anymore. [Here’s a list](http://ec.europa.eu/environment/beyond_gdp/key_quotes_en.html) of global and economic leaders stating the need to move past it.

This token is an effort to create a new monetary and economic system. One which focuses energy onto these essential societal areas which are currently overlooked. An effort to create a healthier and happier world.

**Intro:**
If the right people get behind this it will have a profound effect on increasing peace, happiness, and reducing human-suffering across the world. If you’re reading this it because we believe that you have the skills to contribute, and a passion to create positive change for humanity.

> "Those who love peace must learn to organize as effectively as those who love war"  - Martin Luther King

Our community of volunteers has been gradually building a platform to host this vision for over 3 years now. The platform is for groups from around the world, anyone who is using positive actions to promote peace and wellbeing through building human and community connection.

It's provides a space for our individual networks to grow into something larger. A global movement for a world with more peace and happiness in it. We’ve reached the point where it is ready to begin hosting communities who will contribute to it governance and improving the platform. You can take a look here: [focallocal.org ](https://focallocal.org)

Note: This white paper is quite long. The most effective way to contribute is by reading the intro and why ‘the world needs this’, and then clicking the sections in the contents page which you’d most like to contribute to. To discuss a section and make suggestions, click on the red balloons.
`)

const element =
Abstract

const markdownSection2 = md.render(`

text

text
				   `)
const element =
Background

const markdownSection3 = md.render(`

text

text

`)
const markdownSection4 = md.render(` test2 INSERT SECTION 3 HEre`)
const markdownSection5 = md.render(` test4 INSERT SECTION 3 HEre`)
const markdownSection6 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection7 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection8 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection9 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection10 = md.render(` Some paragraphINSERT SECTION 3 HEre`)
const markdownSection11 = md.render(` Some paragraphINSERT SECTION 3 HEre`)
const markdownSection12 = md.render(` Some paragraph ERT SECTION 3 HEre`)
const markdownSection13 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection14 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection15 = md.render(` Some paragraph SERT SECTION 3 HEre`)
const markdownSection16 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection17 = md.render(` Some paragraph INSERT SECTION 3 HEre`)

const index = (props) => {
  return (
    <Container className="mt-5">
			<Contents />

      <DCSBalloon title="Click balloons to comment" balloonId="bal" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

    </Container>

  );
};

export default index;
<commit_msg>changed to const anchor[ ]<commit_after>import React from "react";
import { Container } from "reactstrap";
import './styles.scss'
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Remarkable = require('remarkable');

const md = new Remarkable();
md.set({
  breaks: true,
  linkify: true
});

const Contents = () => (
   <React.Fragment>

Welcome to the 1st Draft!

Contents

 The World Needs This Because: (v1)

The World Needs This Because: (v2)

1. Abstract

      	1.1. Background

      	1.2. Public Happiness Movement Token Introduction

2. Problem Statement

      	2.1. Issues we aim to solve

      	2.2. Primary Goal

      	2.3. Secondary Goal

      	2.4. Relation to Universal Basic Income

3. Educating the Public about Blockchain

      	3.1. Current State of Public Understanding

      	3.2. Reaching a New Audience

4. The Public Happiness Movement Token

      	4.1. Token Overview

5. Public Happiness Movement Token ICO

      	5.1. ICO Strategy

      	5.2. ICO Stages

      	5.3. Ongoing Funding for Specific Projects and Experts

      	5.4. ICO Marketing

6. Public Happiness – Background

      	6.1. Community Background

      	6.2. The Public Happiness Movement Community

7. Platform Overview

      	7.1. The Public Happiness Map (public actions for increasing human and society well-being)

      	7.2. Action Center (Microvolunteering)

      	7.3. Community News

      	7.4. Active Happiness Shop

      	7.5. Who Defines What is Accepted as ‘Public Happiness’

      	7.6. Evidence Based and Peer Reviewed Actions

      	7.7. Who can Participate on the Platform

      	7.8. Pre-existing Communities with Similar Values

      	7.9. Languages

      	7.10. Decentralised Governance and Voting

8. The Path to Decentralisation

      	8.1. Benevolent Dictatorship vs Complete Community Governance

      	8.2. Example Scenario: Outside Collusion

      	8.3. Lines of Defence

      	8.4. Conclusion

9. Security

      	9.1. Levels of Trust

      	9.2.. Community Administrators

      	9.3. Project Administrators

      	9.4. Mining Limits

      	9.5. Cold Storage and Key Holders

10. Marketing Strategy

      	10.1. A New Level of Hash Tagging

      	10.2. Bus Tour

      	10.3.. Public Happiness Channel

      	10.4. Happy Cam

      	10.5. Public Happiness Partners

      	10.6. Online Supporters

      	10.7. Contests

      	10.8. Collectables

11.  Automated Token Distribution Matrix

      	11.1. Weighted Mining

      	11.2. Hard Cap

      	11.3. Adjusting the Balancing

      	11.4. Token Release

      	11.5. Mining Table

      	11.6. Experience Multipliers

      	11.7. Token Distribution

      	11.8. Further Matrix Considerations

12. Team

      	12.1. Current Team Members

      	12.2. Positions Open

      	12.3. Remuneration

      	12.4. Facilities

13. Platform Technicals

      	13.1. Crypto Linking Bridges

      	13.2. Trello vs Wekan vs Other Solutions

      	13.3. Leaflet.js vs Google Maps API

      	13.4. Switching the Platform to the Dapps Network

14. Doomsday Protocol

      	14.1. Huge Market Crash

      	14.2. Quantum Security

      	14.3. Massive Hack

      	14.4. Zombie Apocalypse

15. Giving Back to Open-source

16. Timeline

17. White Paper Reviewed By

18. Questions to be Resolved

 </React.Fragment>
 )

const markdownSection1 = md.render(`
# Public Happiness Movement Token
# Whitepaper

**Foreword:**

I've lived about as frugal a life as is possible in the Western World because I've always disliked money.  It so often seems to have a negative effect on people and society.

The crypto-world has me intensely curious, because money can be different there. I wanted to learn more and see if it's possible to design a form of money that is intrinsically tied to creating societal value.  Something to act as a band-aid on today’s ‘profit at all costs’ capitalism which has blind-spots for large areas critical to producing healthy, happy societies. This is caused by foundations measuring all progress and success as an increase in GDP. Anything which doesn’t is, by design, an after-thought.

GDP was designed by Simon Kuznets, in 1937 as a temporary post war recovery system, but the beast got out of control. The damage caused to humanity by basing our decision making processes on measurements of GDP isn’t even contentious anymore. [Here’s a list](http://ec.europa.eu/environment/beyond_gdp/key_quotes_en.html) of global and economic leaders stating the need to move past it.

This token is an effort to create a new monetary and economic system. One which focuses energy onto these essential societal areas which are currently overlooked. An effort to create a healthier and happier world.

**Intro:**
If the right people get behind this it will have a profound effect on increasing peace, happiness, and reducing human-suffering across the world. If you’re reading this it because we believe that you have the skills to contribute, and a passion to create positive change for humanity.

> "Those who love peace must learn to organize as effectively as those who love war"  - Martin Luther King

Our community of volunteers has been gradually building a platform to host this vision for over 3 years now. The platform is for groups from around the world, anyone who is using positive actions to promote peace and wellbeing through building human and community connection.

It's provides a space for our individual networks to grow into something larger. A global movement for a world with more peace and happiness in it. We’ve reached the point where it is ready to begin hosting communities who will contribute to it governance and improving the platform. You can take a look here: [focallocal.org ](https://focallocal.org)

Note: This white paper is quite long. The most effective way to contribute is by reading the intro and why ‘the world needs this’, and then clicking the sections in the contents page which you’d most like to contribute to. To discuss a section and make suggestions, click on the red balloons.
`)

const anchor2 =
Abstract

const markdownSection2 = md.render(`

text

text
				   `)
const anchor3 =
Background

const markdownSection3 = md.render(`

text

text

`)
const markdownSection4 = md.render(` test2 INSERT SECTION 3 HEre`)
const markdownSection5 = md.render(` test4 INSERT SECTION 3 HEre`)
const markdownSection6 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection7 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection8 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection9 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection10 = md.render(` Some paragraphINSERT SECTION 3 HEre`)
const markdownSection11 = md.render(` Some paragraphINSERT SECTION 3 HEre`)
const markdownSection12 = md.render(` Some paragraph ERT SECTION 3 HEre`)
const markdownSection13 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection14 = md.render(` Some paragraph NSERT SECTION 3 HEre`)
const markdownSection15 = md.render(` Some paragraph SERT SECTION 3 HEre`)
const markdownSection16 = md.render(` Some paragraph INSERT SECTION 3 HEre`)
const markdownSection17 = md.render(` Some paragraph INSERT SECTION 3 HEre`)

const index = (props) => {
  return (
    <Container className="mt-5">
			<Contents />

      <DCSBalloon title="Click balloons to comment" balloonId="bal" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

    </Container>

  );
};

export default index;
<|endoftext|>


<commit_before>module.exports = {
  up(queryInterface, Sequelize) {
    return queryInterface.createTable('Messages', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      content: {
        allowNull: false,
        type: Sequelize.STRING
      },
      priority: {
      allowNull: false,
      type: Sequelize.STRING,
     },
      groupId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        references: {
          model: 'Groups',
          key: 'id',
          as: 'groupId'
        }
      },
      isRead: {
        type: Sequelize.BOOLEAN,
        defaultValue: false
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down(queryInterface) {
    return queryInterface.dropTable('Messages');
  }
};
<commit_msg>fix bug in message model<commit_after>module.exports = {
  up(queryInterface, Sequelize) {
    return queryInterface.createTable('Messages', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      content: {
        type: Sequelize.STRING
      },
      priority: {
      type: Sequelize.STRING,
      defaultValue: 'normal',
     },
      groupId: {
        type: Sequelize.INTEGER,
        onDelete: 'CASCADE',
        references: {
          model: 'Groups',
          key: 'id',
          as: 'groupId'
        }
      },
      isRead: {
        type: Sequelize.BOOLEAN,
        defaultValue: false
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down(queryInterface) {
    return queryInterface.dropTable('Messages');
  }
};
<|endoftext|>


<commit_before>define([
	'../../moduleDef',
	'angular',
	'text!./userFilter.tpl.html',
	'text!./userFilterNode.tpl.html',
	'text!./booleanValueEditor.tpl.html',
	'text!./dateValueEditor.tpl.html',
	'text!./textValueEditor.tpl.html'
], function (module, angular, tpl, nodeTpl, booleanEditorTpl, dateEditorTpl, textEditorTpl) {

	var editorTpls = { };
	module.directive('userFilter', ['$compile', function($compile) {
		angular.extend(editorTpls, {
			boolean: $compile(booleanEditorTpl),
			date: $compile(dateEditorTpl),
			text: $compile(textEditorTpl)
		});

		return {
			replace: true,
			template: tpl,
			scope: {
				rootNode: '=filterNgModel',
				meta: '='
			},
			controller: ['$scope', '$rootScope', function($scope, $rootScope) {
				angular.extend($scope, {
					i18n: $rootScope.i18n,

					addNode: function() {
						$scope.rootNode.items.push({ op: '&&', items: [ ] });
					},

					clear: function() {
						$scope.rootNode.items = [ ];
					},

					decorateRootNode: function() {
						$scope.rootNode.op = '&&';
						delete $scope.rootNode.path;
						delete $scope.rootNode.value;
						delete $scope.rootNode.not;
						$scope.rootNode.items = $scope.rootNode.items || [ ];
					}
				});

				$scope.$watch('rootNode', function(value) {
					if(!value) {
						$scope.rootNode = { };
					}
					$scope.decorateRootNode();
				}, true);
			}]
		};
	}
])
.directive('userFilterNode', ['$filter', 'filteringService', 'metadataService', 'apinetService',
	function($filter, $filteringService, metadataService, apinetService) {
		return {
			replace: true,
			scope: {
				node: '=',
				rootNode: '='
			},
			template: nodeTpl,
			controller: ['$scope', '$rootScope', function($scope, $rootScope) {
				$scope.typeNode = $filteringService.ensurePropertyTypeNode($scope.node);
				$scope.valueNode = $filteringService.ensurePropertyValueNode($scope.node);
				$scope.editingTypeNode = angular.extend({ }, $scope.typeNode);
				$scope.editingValueNode = angular.extend({ }, $scope.valueNode);

				angular.extend($scope, {
					i18n: $rootScope.i18n,
					context: { },

					typeNodeUpdated: function() {
						if($scope.editingTypeNode.value && !angular.isObject($scope.editingTypeNode.value)) {
							return;
						}

						$scope.getTypeMetadata(function(typeMetadata) {
							var ctx = $scope.context = {
								typeValidation: {
									path: [],
									op: [],
									value: [],
									valid: true
								},
								valueValidation: {
									path: [],
									op: [],
									value: [],
									valid: true
								},
								path: {
									visible: true
								},
								op: {
									visible: false
								},
								value: {
									visible: false,
									editorType: 'text'
								}
							};

							if ($filteringService.validateNode($scope.editingTypeNode, typeMetadata, ctx.typeValidation)) {
								$scope.typeNode = $scope.node.items[0] = angular.extend({ }, $scope.editingTypeNode);
								if(angular.isObject($scope.typeNode.value)) {
									$scope.typeNode.value = $scope.typeNode.value.id;
								}
							}

							$scope.editingValueNode.path = undefined;
							$scope.editingValueNode.op = undefined;
							$scope.editingValueNode.value = undefined;
							$scope.tempValue = undefined;

							if(!$scope.editingTypeNode.value || !$scope.editingTypeNode.value.id) {
								return;
							}

							apinetService.getModel({
								method: 'core/dictionary/getCustomPropertyType',
								id: $scope.editingTypeNode.value.id
							}, function(result) {
								if(!result || !result.ValueType) {
									return;
								}

								$scope.nodeUpdated('path', result.ValueType + 'Value');
							});
						});
					},

					nodeUpdated: function(property, value) {
						var forceMetadata = false;
						if(property && $scope.context.hasOwnProperty(property)) {
							$scope.editingValueNode[property] = value;

							if(property === 'path') {
								delete $scope.context.op.options;
								$scope.editingValueNode.op = '';
								forceMetadata = true;
							}
						}

						$scope.getValueMetadata(function(valueMetadata) {
							$filteringService.afterNodeEdit($scope.editingValueNode, valueMetadata);

							var ctx = $scope.context;
							var i;
							if(!ctx.op.options || !ctx.op.options.length) {
								ctx.op.options = $filter('applicableOps')($filteringService.allOps(), valueMetadata);
								if(!$scope.editingValueNode.op && ctx.op.options.length) {
									$scope.editingValueNode.op = ctx.op.options[0];
								}
								for (i = 0; i < ctx.op.options.length; i++) {
									ctx.op.options[i] = {
										value: ctx.op.options[i],
										label: $filteringService.opDisplayName(ctx.op.options[i])
									};
								}
							}

							ctx.value.editorType = 'text';
							if(valueMetadata.PropertyType) {
								ctx.op.visible = true;
								ctx.value.visible = !$filteringService.isUnaryNode($scope.editingValueNode);
								if (valueMetadata.PropertyType === 'date' || valueMetadata.PropertyType === 'datetime' ||
										valueMetadata.PropertyType === 'boolean' || valueMetadata.PropertyType === 'enum') {
									ctx.value.editorType = valueMetadata.PropertyType;
								}
							}

							if ($filteringService.validateNode($scope.editingValueNode, valueMetadata, ctx.validation)) {
								$scope.valueNode = $scope.node.items[1] = angular.extend({ }, $scope.editingValueNode);
							}
							$filteringService.beforeNodeEdit($scope.editingValueNode);

							ctx.op.displayValue = $filteringService.opDisplayName(
								$scope.editingValueNode.op, $scope.editingValueNode.not, $scope.node.path);
							ctx.value.displayValue = $filteringService.valueDisplayName(
								$scope.editingValueNode.value, valueMetadata);

						}, forceMetadata);
					},

					getTypeMetadata: function(callback) {
						if(!$scope.typeMetadata) {
							metadataService.modelMetadata('core/dictionary/customPropertyMetadata',
								'AGO.Core.Model.Dictionary.CustomPropertyTypeModel', function(typeMetadata) {
									$scope.typeMetadata = typeMetadata;
									callback($scope.typeMetadata);
								});
							return;
						}
						callback($scope.typeMetadata);
					},

					getValueMetadata: function(callback, forceRefresh) {
						if(forceRefresh || !$scope.valueMetadata) {
							metadataService.modelMetadata('core/dictionary/customPropertyMetadata',
								'AGO.Core.Model.Dictionary.CustomPropertyInstanceModel', function(parentMeta) {
									$filteringService.getNodeMetadata('core/dictionary/customPropertyMetadata',
										$scope.editingValueNode, parentMeta, function(typeMetadata) {
											$scope.valueMetadata = typeMetadata;
											callback($scope.valueMetadata);
										});
								});
							return;
						}
						callback($scope.valueMetadata);
					},

					deleteNode: function() {
						var index = $scope.rootNode.items.indexOf($scope.node);
						if(index === -1) {
							return;
						}
						$scope.rootNode.items.splice(index, 1);
					}
				});

				$scope.$watch('editingTypeNode.value', $scope.typeNodeUpdated, true);
			}]
		};
	}]);
});<commit_msg>Issue refs #1768: fix user filter (all api method will contains project in signature, if may be project-specific)<commit_after>define([
	'../../moduleDef',
	'angular',
	'text!./userFilter.tpl.html',
	'text!./userFilterNode.tpl.html',
	'text!./booleanValueEditor.tpl.html',
	'text!./dateValueEditor.tpl.html',
	'text!./textValueEditor.tpl.html'
], function (module, angular, tpl, nodeTpl, booleanEditorTpl, dateEditorTpl, textEditorTpl) {

	var editorTpls = { };
	module.directive('userFilter', ['$compile', function($compile) {
		angular.extend(editorTpls, {
			boolean: $compile(booleanEditorTpl),
			date: $compile(dateEditorTpl),
			text: $compile(textEditorTpl)
		});

		return {
			replace: true,
			template: tpl,
			scope: {
				rootNode: '=filterNgModel',
				meta: '='
			},
			controller: ['$scope', '$rootScope', function($scope, $rootScope) {
				angular.extend($scope, {
					i18n: $rootScope.i18n,

					addNode: function() {
						$scope.rootNode.items.push({ op: '&&', items: [ ] });
					},

					clear: function() {
						$scope.rootNode.items = [ ];
					},

					decorateRootNode: function() {
						$scope.rootNode.op = '&&';
						delete $scope.rootNode.path;
						delete $scope.rootNode.value;
						delete $scope.rootNode.not;
						$scope.rootNode.items = $scope.rootNode.items || [ ];
					}
				});

				$scope.$watch('rootNode', function(value) {
					if(!value) {
						$scope.rootNode = { };
					}
					$scope.decorateRootNode();
				}, true);
			}]
		};
	}
])
.directive('userFilterNode', ['$filter', 'filteringService', 'metadataService', 'apinetService', '$stateParams',
	function($filter, $filteringService, metadataService, apinetService, $stateParams) {
		return {
			replace: true,
			scope: {
				node: '=',
				rootNode: '='
			},
			template: nodeTpl,
			controller: ['$scope', '$rootScope', function($scope, $rootScope) {
				$scope.typeNode = $filteringService.ensurePropertyTypeNode($scope.node);
				$scope.valueNode = $filteringService.ensurePropertyValueNode($scope.node);
				$scope.editingTypeNode = angular.extend({ }, $scope.typeNode);
				$scope.editingValueNode = angular.extend({ }, $scope.valueNode);

				angular.extend($scope, {
					i18n: $rootScope.i18n,
					context: { },

					typeNodeUpdated: function() {
						if($scope.editingTypeNode.value && !angular.isObject($scope.editingTypeNode.value)) {
							return;
						}

						$scope.getTypeMetadata(function(typeMetadata) {
							var ctx = $scope.context = {
								typeValidation: {
									path: [],
									op: [],
									value: [],
									valid: true
								},
								valueValidation: {
									path: [],
									op: [],
									value: [],
									valid: true
								},
								path: {
									visible: true
								},
								op: {
									visible: false
								},
								value: {
									visible: false,
									editorType: 'text'
								}
							};

							if ($filteringService.validateNode($scope.editingTypeNode, typeMetadata, ctx.typeValidation)) {
								$scope.typeNode = $scope.node.items[0] = angular.extend({ }, $scope.editingTypeNode);
								if(angular.isObject($scope.typeNode.value)) {
									$scope.typeNode.value = $scope.typeNode.value.id;
								}
							}

							$scope.editingValueNode.path = undefined;
							$scope.editingValueNode.op = undefined;
							$scope.editingValueNode.value = undefined;
							$scope.tempValue = undefined;

							if(!$scope.editingTypeNode.value || !$scope.editingTypeNode.value.id) {
								return;
							}

							apinetService.getModel({
								method: 'core/dictionary/getCustomPropertyType',
								project: $stateParams.project,//needs refactoring - must be provided for directive from out (artem1 2014-03-16)
								id: $scope.editingTypeNode.value.id
							}, function(result) {
								if(!result || !result.ValueType) {
									return;
								}

								$scope.nodeUpdated('path', result.ValueType + 'Value');
							});
						});
					},

					nodeUpdated: function(property, value) {
						var forceMetadata = false;
						if(property && $scope.context.hasOwnProperty(property)) {
							$scope.editingValueNode[property] = value;

							if(property === 'path') {
								delete $scope.context.op.options;
								$scope.editingValueNode.op = '';
								forceMetadata = true;
							}
						}

						$scope.getValueMetadata(function(valueMetadata) {
							$filteringService.afterNodeEdit($scope.editingValueNode, valueMetadata);

							var ctx = $scope.context;
							var i;
							if(!ctx.op.options || !ctx.op.options.length) {
								ctx.op.options = $filter('applicableOps')($filteringService.allOps(), valueMetadata);
								if(!$scope.editingValueNode.op && ctx.op.options.length) {
									$scope.editingValueNode.op = ctx.op.options[0];
								}
								for (i = 0; i < ctx.op.options.length; i++) {
									ctx.op.options[i] = {
										value: ctx.op.options[i],
										label: $filteringService.opDisplayName(ctx.op.options[i])
									};
								}
							}

							ctx.value.editorType = 'text';
							if(valueMetadata.PropertyType) {
								ctx.op.visible = true;
								ctx.value.visible = !$filteringService.isUnaryNode($scope.editingValueNode);
								if (valueMetadata.PropertyType === 'date' || valueMetadata.PropertyType === 'datetime' ||
										valueMetadata.PropertyType === 'boolean' || valueMetadata.PropertyType === 'enum') {
									ctx.value.editorType = valueMetadata.PropertyType;
								}
							}

							if ($filteringService.validateNode($scope.editingValueNode, valueMetadata, ctx.validation)) {
								$scope.valueNode = $scope.node.items[1] = angular.extend({ }, $scope.editingValueNode);
							}
							$filteringService.beforeNodeEdit($scope.editingValueNode);

							ctx.op.displayValue = $filteringService.opDisplayName(
								$scope.editingValueNode.op, $scope.editingValueNode.not, $scope.node.path);
							ctx.value.displayValue = $filteringService.valueDisplayName(
								$scope.editingValueNode.value, valueMetadata);

						}, forceMetadata);
					},

					getTypeMetadata: function(callback) {
						if(!$scope.typeMetadata) {
							metadataService.modelMetadata('core/dictionary/customPropertyMetadata',
								'AGO.Core.Model.Dictionary.CustomPropertyTypeModel', function(typeMetadata) {
									$scope.typeMetadata = typeMetadata;
									callback($scope.typeMetadata);
								});
							return;
						}
						callback($scope.typeMetadata);
					},

					getValueMetadata: function(callback, forceRefresh) {
						if(forceRefresh || !$scope.valueMetadata) {
							metadataService.modelMetadata('core/dictionary/customPropertyMetadata',
								'AGO.Core.Model.Dictionary.CustomPropertyInstanceModel', function(parentMeta) {
									$filteringService.getNodeMetadata('core/dictionary/customPropertyMetadata',
										$scope.editingValueNode, parentMeta, function(typeMetadata) {
											$scope.valueMetadata = typeMetadata;
											callback($scope.valueMetadata);
										});
								});
							return;
						}
						callback($scope.valueMetadata);
					},

					deleteNode: function() {
						var index = $scope.rootNode.items.indexOf($scope.node);
						if(index === -1) {
							return;
						}
						$scope.rootNode.items.splice(index, 1);
					}
				});

				$scope.$watch('editingTypeNode.value', $scope.typeNodeUpdated, true);
			}]
		};
	}]);
});<|endoftext|>


<commit_before>/**
 * Pass the ComboBox an element like this:
 *
 ** var element = document.getElementsByClassName('ComboBox')[0];
 ** var cb = new ComboBox(element, false);
 *
 * the second argument (true/false) is optional, when set to true, the styling of the elements is all yours.
 * Find the project on Github for more information:
 * https://github.com/ThibaultJanBeyer/ComboBox.js
 */

var ComboBox = function(container, customStyles) {
  this.container = container;
  this.container.className += ' cb--container';
  this.input = container.getElementsByTagName('input')[0];
  this.input.className += ' cb--input';
  this.select = container.getElementsByTagName('select')[0];
  this.select.className += ' cb--select';

  var optionZero = document.createElement('option');
  optionZero.innerHTML = '---';
  this.select.insertBefore(optionZero, this.select.options[0]);

  this.options = this.select.options;
  this.select.value = this.options[0].innerHTML;
  this.select.value = [];

  this.input.setAttribute('aria-label', 'Special inputfield with '+this.options.length+' prefilled options available, use the down arrow key to chose one or write your own text.');
  this.select.setAttribute('aria-hidden', 'true');

  this.hideSelect();
  this.addEventListeners();
  this.createVisualHint();

  if(!customStyles) this.setStyles();
};

ComboBox.prototype.addEventListeners = function() {
  this.input.addEventListener('focus', this.showSelect.bind(this));
  this.input.addEventListener('blur', this.hideSelect.bind(this));
  this.input.addEventListener('keyup', this.handleInput.bind(this));
  this.select.addEventListener('focus', this.showSelect.bind(this));
  this.select.addEventListener('blur', this.hideSelect.bind(this));
  this.select.addEventListener('change', this.handleSelection.bind(this));
  this.select.addEventListener('keypress', this.handleSelection.bind(this));
  this.select.addEventListener('click', this.handleSelection.bind(this));

  return this;
};

ComboBox.prototype.handleInput = function(e) {
  var code = this.getKey(e);
  if(code === 'ArrowDown') {
    this.select.focus();
  } else if(code === 'Escape') {
    this.hideSelect();
  } else if(code === 'Enter') {
    this.input.value = this.select.value;
    this.hideSelect();
  } else {
    this.handleWriting(e.target.value);
  }

  return this;
};

ComboBox.prototype.handleWriting = function(text) {
  var option = this.isTextInOptions(text, this.options);
  if(option && text != '') {
    this.select.value = option;
  } else {
    var setText = (text != '') ? '--- ' + text : '---';
    this.options[0].innerHTML = setText;
    this.select.value = setText;
    this.select.value = [];
  }

  return this;
};

ComboBox.prototype.isTextInOptions = function(text, options) {
  for(var i = 1, il = options.length; i < il; i++) {
    if(text.toLowerCase() == options[i].value.substring(0, text.length).toLowerCase()) {
      return options[i].innerHTML;
    }
  }
  return false;
};

ComboBox.prototype.handleSelection = function(e) {
  var code = this.getKey(e);
  if(code === 'Escape') {
    this.select.blur();
    this.input.focus();
  } else if(e.target.value.substring(0,3) != '---' && e.target.value != '') {
    this.input.value = e.target.value;
  } else if(e.target.value != '') {
    this.input.value = e.target.value.substring(4, e.target.value.length);
  }
  if(code === 'Enter') {
    this.select.blur();
    this.input.focus();
  }

  return this;
};

ComboBox.prototype.getKey = function(e) {
  if(e.key === 'Enter' || e.code === 'Enter' || e.keyCode === 13) {
    return 'Enter';
  } else if(e.key === 'Escape' || e.code === 'Escape' || e.keyCode === 27) {
    return 'Escape';
  } else if(e.key === 'ArrowDown' || e.code === 'ArrowDown' || e.keyCode === 40) {
    return 'ArrowDown';
  }
};

ComboBox.prototype.hideSelect = function() {
  this.select.setAttribute('aria-hidden', 'true');
  this.select.style.pointerEvents = 'none';
  this.select.style.opacity = 0;
  this.select.tabIndex = -1;
  return this;
};

ComboBox.prototype.showSelect = function() {
  this.select.setAttribute('aria-hidden', 'false');
  this.select.style.pointerEvents = 'all';
  this.select.style.opacity = 1;
  this.select.tabIndex = 0;
  return this;
};

ComboBox.prototype.createVisualHint = function() {
  this.hint = document.createElement('span');
  this.hint.setAttribute('aria-hidden', 'true');
  this.hint.className = 'cb--hint';
  this.hint.innerHTML = '▼';
  this.container.insertBefore(this.hint, this.input);
};

ComboBox.prototype.setStyles = function() {
  this.container.style.display = 'inline-block';
  this.container.style.position = 'relative';
  this.input.style.boxSizing = 'border-box';
  this.input.style.height = '100%';
  this.input.style.width = '100%';
  this.select.style.border = '1px solid lightgrey';
  this.select.style.borderTop = '0';
  this.select.style.left = '0';
  this.select.style.opacity = '0';
  this.select.style.pointerEvents = '0';
  this.select.style.position = 'absolute';
  this.select.style.top = '100%';
  this.select.style.width = '100%';
  this.hint.style.fontSize = '8px';
  this.hint.style.pointerEvents = 'none';
  this.hint.style.position = 'absolute';
  this.hint.style.right = '5%';
  this.hint.style.top = '25%';

  // this is inportant to get a list instead of a dropdown
  this.select.size = 4;
};
<commit_msg>add classes to options & prevent enter reset if no options is found<commit_after>/**
 * Pass the ComboBox an element like this:
 *
 ** var element = document.getElementsByClassName('ComboBox')[0];
 ** var cb = new ComboBox(element, false);
 *
 * the second argument (true/false) is optional, when set to true, the styling of the elements is all yours.
 * Find the project on Github for more information:
 * https://github.com/ThibaultJanBeyer/ComboBox.js
 */

var ComboBox = function(container, customStyles) {
  this.container = container;
  this.container.className += ' cb--container';
  this.input = container.getElementsByTagName('input')[0];
  this.input.className += ' cb--input';
  this.select = container.getElementsByTagName('select')[0];
  this.select.className += ' cb--select';

  var optionZero = document.createElement('option');
  optionZero.innerHTML = '---';
  this.select.insertBefore(optionZero, this.select.options[0]);

  this.options = this.select.options;
  this.select.value = this.options[0].innerHTML;
  this.select.value = [];
  for (var i = 0; i < this.options.length; i++) {
    var element = this.options[i];
    element.className += ' cb--option';
  }

  this.input.setAttribute('aria-label', 'Special inputfield with '+this.options.length+' prefilled options available, use the down arrow key to chose one or write your own text.');
  this.select.setAttribute('aria-hidden', 'true');

  this.hideSelect();
  this.addEventListeners();
  this.createVisualHint();

  if(!customStyles) this.setStyles();
};

ComboBox.prototype.addEventListeners = function() {
  this.input.addEventListener('focus', this.showSelect.bind(this));
  this.input.addEventListener('blur', this.hideSelect.bind(this));
  this.input.addEventListener('keyup', this.handleInput.bind(this));
  this.select.addEventListener('focus', this.showSelect.bind(this));
  this.select.addEventListener('blur', this.hideSelect.bind(this));
  this.select.addEventListener('change', this.handleSelection.bind(this));
  this.select.addEventListener('keypress', this.handleSelection.bind(this));
  this.select.addEventListener('click', this.handleSelection.bind(this));

  return this;
};

ComboBox.prototype.handleInput = function(e) {
  var code = this.getKey(e);
  if(code === 'ArrowDown') {
    this.select.focus();
  } else if(code === 'Escape') {
    this.hideSelect();
  } else if(code === 'Enter') {
    if (this.select.value != '') {
      e.preventDefault();
      this.input.value = this.select.value;
      this.hideSelect();
    }
  } else {
    this.handleWriting(e.target.value);
  }

  return this;
};

ComboBox.prototype.handleWriting = function(text) {
  var option = this.isTextInOptions(text, this.options);
  if(option && text != '') {
    this.select.value = option;
  } else {
    var setText = (text != '') ? '--- ' + text : '---';
    this.options[0].innerHTML = setText;
    this.select.value = setText;
    this.select.value = [];
  }

  return this;
};

ComboBox.prototype.isTextInOptions = function(text, options) {
  for(var i = 1, il = options.length; i < il; i++) {
    if(text.toLowerCase() == options[i].value.substring(0, text.length).toLowerCase()) {
      return options[i].innerHTML;
    }
  }
  return false;
};

ComboBox.prototype.handleSelection = function(e) {
  var code = this.getKey(e);
  if(code === 'Escape') {
    this.select.blur();
    this.input.focus();
  } else if(e.target.value.substring(0,3) != '---' && e.target.value != '') {
    this.input.value = e.target.value;
  } else if(e.target.value != '') {
    this.input.value = e.target.value.substring(4, e.target.value.length);
  }
  if(code === 'Enter') {
    this.select.blur();
    this.input.focus();
  }

  return this;
};

ComboBox.prototype.getKey = function(e) {
  if(e.key === 'Enter' || e.code === 'Enter' || e.keyCode === 13) {
    return 'Enter';
  } else if(e.key === 'Escape' || e.code === 'Escape' || e.keyCode === 27) {
    return 'Escape';
  } else if(e.key === 'ArrowDown' || e.code === 'ArrowDown' || e.keyCode === 40) {
    return 'ArrowDown';
  }
};

ComboBox.prototype.hideSelect = function() {
  this.select.setAttribute('aria-hidden', 'true');
  this.select.style.pointerEvents = 'none';
  this.select.style.opacity = 0;
  this.select.tabIndex = -1;
  return this;
};

ComboBox.prototype.showSelect = function() {
  this.select.setAttribute('aria-hidden', 'false');
  this.select.style.pointerEvents = 'all';
  this.select.style.opacity = 1;
  this.select.tabIndex = 0;
  return this;
};

ComboBox.prototype.createVisualHint = function() {
  this.hint = document.createElement('span');
  this.hint.setAttribute('aria-hidden', 'true');
  this.hint.className = 'cb--hint';
  this.hint.innerHTML = '▼';
  this.container.insertBefore(this.hint, this.input);
};

ComboBox.prototype.setStyles = function() {
  this.container.style.display = 'inline-block';
  this.container.style.position = 'relative';
  this.input.style.boxSizing = 'border-box';
  this.input.style.height = '100%';
  this.input.style.width = '100%';
  this.select.style.border = '1px solid lightgrey';
  this.select.style.borderTop = '0';
  this.select.style.left = '0';
  this.select.style.opacity = '0';
  this.select.style.pointerEvents = '0';
  this.select.style.position = 'absolute';
  this.select.style.top = '100%';
  this.select.style.width = '100%';
  this.hint.style.fontSize = '8px';
  this.hint.style.pointerEvents = 'none';
  this.hint.style.position = 'absolute';
  this.hint.style.right = '5%';
  this.hint.style.top = '25%';

  // this is inportant to get a list instead of a dropdown
  this.select.size = 4;
};
<|endoftext|>


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

import AxiomError from 'axiom/core/error';

import OpenContextBinding from 'axiom/bindings/fs/open_context';
import domfsUtil from 'axiom/fs/domfs_util';

import Path from 'axiom/fs/path';

/** @typedef DomFileSystem$$module$axiom$fs$dom_file_system */
var DomFileSystem;

/**
 * @constructor
 * Construct a new context that can be used to open a file.
 *
 * @param {DomFileSystem} domfs
 * @param {Path} path
 * @param {Object} arg
 */
var DomOpenContext = function(domfs, path, arg) {
  this.domfs = domfs;
  this.path = path;
  this.arg = arg;

  this.onFileError_ = domfsUtil.rejectFileError.bind(null, path.spec);

  // The current read/write position.
  this.position_ = 0;

  // The DOM FileEntry we're operation on.
  this.entry_ = null;

  // THe DOM file we're operating on.
  this.file_ = null;

  this.binding = new OpenContextBinding(domfs.binding, path.spec, arg);
  this.binding.bind(this, {
    open: this.open_,
    seek: this.seek_,
    read: this.read_,
    write: this.write_
  });
};

export {DomOpenContext};
export default DomOpenContext;

/**
 * If the arg object does not have a 'whence' property, this call succeeds
 * with no side effects.
 *
 * @param {Object} arg An object containing 'whence' and 'offset' arguments
 *  describing the seek operation.
 */
DomOpenContext.prototype.seek_ = function(arg) {
  var fileSize = this.file_.size;
  var start = this.position_;

  if (!arg['whence'])
    return Promise.resolve(true);

  if (arg['whence'] == 'begin') {
    start = arg['offset'];

  } else if (arg['whence'] == 'current') {
    start += arg['offset'];

  } else if (arg['whence'] == 'end') {
    start = fileSize + arg['offset'];
  }

  if (start > fileSize) {
    //onError(wam.mkerr('wam.FileSystem.Error.EndOfFile', []));
    return Promise.reject(new AxiomError.Runtime('reached end of file.'));
  }

  if (start < 0) {
    return Promise.reject(new AxiomError.Runtime(
        'Invalid file offset: ' + this.path.spec));
  }

  this.position_ = start;
  return Promise.resolve({position: this.position});
};

DomOpenContext.prototype.open_ = function() {
  var mode = this.arg;
  return new Promise(function(resolve, reject) {
    var onFileError = this.onFileError_.bind(null, reject);
    var onStat = function(stat) {
      this.entry_.file(function(f) {
          this.file_ = f;
          this.binding.ready(stat);
          resolve();
      }.bind(this), onFileError);
    }.bind(this);

    var onFileFound = function(entry) {
      this.entry_ = entry;
      if (mode.write && mode.truncate) {
        this.entry_.createWriter(
            function(writer) {
              writer.truncate(0);
              domfsUtil.statEntry(entry).then(onStat).catch(onFileError);
            },
            reject);
        return;
      }

      domfsUtil.statEntry(entry).then(function(value) {
        onStat(value);
      }).catch(function(e) {
        reject(e);
      });
    }.bind(this);

    this.domfs.fileSystem.root.getFile(
        this.path.spec,
        {create: mode.create,
         exclusive: mode.exclusive
        },
        onFileFound, onFileError);
  }.bind(this));
};

/**
 * Handle a read event from the binding.
 */
DomOpenContext.prototype.read_ = function(arg) {
  if (!arg) {
    arg = {
       dataType: 'utf8-string',
       count: 0
    };
  }
  return new Promise(function(resolve, reject) {
    this.seek_(arg).then(function(rv) {
      if (!rv) {
        return reject();
      }

      var fileSize = this.file_.size;
      var end;
      if (arg.count) {
        end = this.position_ + arg.count;
      } else {
        end = fileSize;
      }

      var dataType = arg.dataType || 'utf8-string';
      var reader = new FileReader();

      reader.onload = function(e) {
        this.position_ = end + 1;
        var data = reader.result;

        //if (dataType == 'base64-string') {
          // TODO: By the time we read this into a string the data may already
          // have been munged.  We need an ArrayBuffer->Base64 string
          // implementation to make this work for real.
          //data = btoa(data);
          //}
        resolve({dataType: dataType, data: data});
      }.bind(this);

      reader.onerror = function(error) {
        return this.onFileError_(reject, error);
      };

      var slice = this.file_.slice(this.position_, end);
      if (dataType == 'blob') {
        resolve({dataType: dataType, data: slice});
      }   else if (dataType == 'arraybuffer') {
        reader.readAsArrayBuffer(slice);
      } else {
        reader.readAsText(slice);
      }
    }.bind(this));
  }.bind(this));
};

/**
 * Handle a write event from the binding.
 */
DomOpenContext.prototype.write_ = function(arg) {
  if (!arg) {
    return Promise.reject(new AxiomError.Missing('arg'));
  }
  var dataType = arg.dataType || 'utf8-string';
  return new Promise(function(resolve, reject) {
    var onWriterReady = function(writer) {
      var blob;
      if (arg.data instanceof Blob) {
        blob = arg.data;
      } else if (arg.data instanceof ArrayBuffer) {
        blob = new Blob([arg.data], {type: 'application/octet-stream'});
      } else if (dataType == 'base64-string') {
        // TODO: Once we turn this into a string the data may already have
        // been munged.  We need an ArrayBuffer->Base64 string implementation to
        // make this work for real.
        blob = new Blob([arg.data],  {type: 'application/octet-stream'});
      } else if (dataType == 'utf8-string') {
        blob = new Blob([arg.data],  {type: 'text/plain'});
      } else if (dataType == 'value') {
        blob = new Blob([JSON.stringify(arg.data)],  {type: 'text/json'});
      }

      writer.onerror = function(error) {
        return this.onFileError_(reject, error);
      }.bind(this);

      writer.onwrite = function() {
        this.position_ = this.position_ + blob.size;
        resolve(null);
      }.bind(this);

      writer.seek(this.position_);
      writer.write(blob);
    }.bind(this);

    this.seek_(arg).then(function(rv) {
      if (!rv) {
        return reject();
      }
      this.entry_.createWriter(
          onWriterReady,
          this.onFileError_.bind(null, reject));
    }.bind(this));
  }.bind(this));
};
<commit_msg>add btoa/atob back in<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import AxiomError from 'axiom/core/error';

import OpenContextBinding from 'axiom/bindings/fs/open_context';
import domfsUtil from 'axiom/fs/domfs_util';

import Path from 'axiom/fs/path';

/** @typedef DomFileSystem$$module$axiom$fs$dom_file_system */
var DomFileSystem;

/**
 * @constructor
 * Construct a new context that can be used to open a file.
 *
 * @param {DomFileSystem} domfs
 * @param {Path} path
 * @param {Object} arg
 */
var DomOpenContext = function(domfs, path, arg) {
  this.domfs = domfs;
  this.path = path;
  this.arg = arg;

  this.onFileError_ = domfsUtil.rejectFileError.bind(null, path.spec);

  // The current read/write position.
  this.position_ = 0;

  // The DOM FileEntry we're operation on.
  this.entry_ = null;

  // THe DOM file we're operating on.
  this.file_ = null;

  this.binding = new OpenContextBinding(domfs.binding, path.spec, arg);
  this.binding.bind(this, {
    open: this.open_,
    seek: this.seek_,
    read: this.read_,
    write: this.write_
  });
};

export {DomOpenContext};
export default DomOpenContext;

/**
 * If the arg object does not have a 'whence' property, this call succeeds
 * with no side effects.
 *
 * @param {Object} arg An object containing 'whence' and 'offset' arguments
 *  describing the seek operation.
 */
DomOpenContext.prototype.seek_ = function(arg) {
  var fileSize = this.file_.size;
  var start = this.position_;

  if (!arg['whence'])
    return Promise.resolve(true);

  if (arg['whence'] == 'begin') {
    start = arg['offset'];

  } else if (arg['whence'] == 'current') {
    start += arg['offset'];

  } else if (arg['whence'] == 'end') {
    start = fileSize + arg['offset'];
  }

  if (start > fileSize) {
    //onError(wam.mkerr('wam.FileSystem.Error.EndOfFile', []));
    return Promise.reject(new AxiomError.Runtime('reached end of file.'));
  }

  if (start < 0) {
    return Promise.reject(new AxiomError.Runtime(
        'Invalid file offset: ' + this.path.spec));
  }

  this.position_ = start;
  return Promise.resolve({position: this.position});
};

DomOpenContext.prototype.open_ = function() {
  var mode = this.arg;
  return new Promise(function(resolve, reject) {
    var onFileError = this.onFileError_.bind(null, reject);
    var onStat = function(stat) {
      this.entry_.file(function(f) {
          this.file_ = f;
          this.binding.ready(stat);
          resolve();
      }.bind(this), onFileError);
    }.bind(this);

    var onFileFound = function(entry) {
      this.entry_ = entry;
      if (mode.write && mode.truncate) {
        this.entry_.createWriter(
            function(writer) {
              writer.truncate(0);
              domfsUtil.statEntry(entry).then(onStat).catch(onFileError);
            },
            reject);
        return;
      }

      domfsUtil.statEntry(entry).then(function(value) {
        onStat(value);
      }).catch(function(e) {
        reject(e);
      });
    }.bind(this);

    this.domfs.fileSystem.root.getFile(
        this.path.spec,
        {create: mode.create,
         exclusive: mode.exclusive
        },
        onFileFound, onFileError);
  }.bind(this));
};

/**
 * Handle a read event from the binding.
 */
DomOpenContext.prototype.read_ = function(arg) {
  if (!arg) {
    arg = {
       dataType: 'utf8-string',
       count: 0
    };
  }
  return new Promise(function(resolve, reject) {
    this.seek_(arg).then(function(rv) {
      if (!rv) {
        return reject();
      }

      var fileSize = this.file_.size;
      var end;
      if (arg.count) {
        end = this.position_ + arg.count;
      } else {
        end = fileSize;
      }

      var dataType = arg.dataType || 'utf8-string';
      var reader = new FileReader();

      reader.onload = function(e) {
        this.position_ = end + 1;
        var data = reader.result;

        if (dataType == 'base64-string' && typeof data == 'string') {
          // TODO: By the time we read this into a string the data may already
          // have been munged.  We need an ArrayBuffer->Base64 string
          // implementation to make this work for real.
          data = window.btoa(data);
        }
        resolve({dataType: dataType, data: data});
      }.bind(this);

      reader.onerror = function(error) {
        return this.onFileError_(reject, error);
      };

      var slice = this.file_.slice(this.position_, end);
      if (dataType == 'blob') {
        resolve({dataType: dataType, data: slice});
      }  else if (dataType == 'arraybuffer') {
        reader.readAsArrayBuffer(slice);
      } else {
        reader.readAsText(slice);
      }
    }.bind(this));
  }.bind(this));
};

/**
 * Handle a write event from the binding.
 */
DomOpenContext.prototype.write_ = function(arg) {
  if (!arg) {
    return Promise.reject(new AxiomError.Missing('arg'));
  }
  var dataType = arg.dataType || 'utf8-string';
  return new Promise(function(resolve, reject) {
    var onWriterReady = function(writer) {
      var blob;
      if (arg.data instanceof Blob) {
        blob = arg.data;
      } else if (arg.data instanceof ArrayBuffer) {
        blob = new Blob([arg.data], {type: 'application/octet-stream'});
      } else if (dataType == 'base64-string' && typeof arg.data == 'string') {
        // TODO: Once we turn this into a string the data may already have
        // been munged.  We need an ArrayBuffer->Base64 string implementation to
        // make this work for real.
        blob = new Blob([window.atob(arg.data)],
                        {type: 'application/octet-stream'});
      } else if (dataType == 'utf8-string') {
        blob = new Blob([arg.data],  {type: 'text/plain'});
      } else if (dataType == 'value') {
        blob = new Blob([JSON.stringify(arg.data)],  {type: 'text/json'});
      }

      writer.onerror = function(error) {
        return this.onFileError_(reject, error);
      }.bind(this);

      writer.onwrite = function() {
        this.position_ = this.position_ + blob.size;
        resolve(null);
      }.bind(this);

      writer.seek(this.position_);
      writer.write(blob);
    }.bind(this);

    this.seek_(arg).then(function(rv) {
      if (!rv) {
        return reject();
      }
      this.entry_.createWriter(
          onWriterReady,
          this.onFileError_.bind(null, reject));
    }.bind(this));
  }.bind(this));
};
<|endoftext|>


<commit_before>var std = require('std'),
	events = require('events'),
	Client = require('./Client')

module.exports = std.Class(Client, function(supr) {

	var defaults = {
		pollInterval: 2000
	}

	this._init = function(opts) {
		supr(this, '_init', arguments)
		std.extend(opts, defaults)
		this._pollInterval = opts.pollInterval
		events.EventEmitter.call(this)
	}

	this.connect = function(callback) {
		var onConnected = std.bind(this, '_onConnected', callback)
		return supr(this, 'connect', [onConnected])
	}

	this._onConnected = function(callback) {
		callback()
		this._intervalID = setInterval(std.bind(this, '_pollForMessages'), this._pollInterval)
	}

	this.close = function() {
		supr(this, 'close')
		clearInterval(this._intervalID)
		delete this._intervalID
	}

	this._pollForMessages = function() {
		console.log("TODO: Send a consumer poll request")
	}

	this._onMessage = function(messageBytes) {
		this.emit('Message', 'TODO: Actually decode messageBytes')
	}
})
<commit_msg>The callback may be null, if the connector did not care about when we get connected (might simply be listening for the "message" event emitting<commit_after>var std = require('std'),
	events = require('events'),
	Client = require('./Client')

module.exports = std.Class(Client, function(supr) {

	var defaults = {
		pollInterval: 2000
	}

	this._init = function(opts) {
		supr(this, '_init', arguments)
		std.extend(opts, defaults)
		this._pollInterval = opts.pollInterval
		events.EventEmitter.call(this)
	}

	this.connect = function(callback) {
		var onConnected = std.bind(this, '_onConnected', callback)
		return supr(this, 'connect', [onConnected])
	}

	this._onConnected = function(callback) {
		if (callback) { callback() }
		this._intervalID = setInterval(std.bind(this, '_pollForMessages'), this._pollInterval)
	}

	this.close = function() {
		supr(this, 'close')
		clearInterval(this._intervalID)
		delete this._intervalID
	}

	this._pollForMessages = function() {
		console.log("TODO: Send a consumer poll request")
	}

	this._onMessage = function(messageBytes) {
		this.emit('Message', 'TODO: Actually decode messageBytes')
	}
})
<|endoftext|>


<commit_before>import React from "react";
import { Container } from "reactstrap";
import './styles.scss'
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Remarkable = require('remarkable');

const md = new Remarkable();
md.set({
  breaks: true,
  linkify: true
});

const Contents = () => (
   <React.Fragment>

Welcome to the 1st Draft!

Contents

The World Needs This Because: (v1)

The World Needs This Because: (v2)

1. Abstract

1.1. Background

	1.2. Public Happiness Movement Token Introduction

2. Problem Statement

	2.1. Issues we aim to solve

	2.2. Primary Goal

	2.3. Secondary Goal

	2.4. Relation to Universal Basic Income

3. Educating the Public about Blockchain

	3.1. Current State of Public Understanding

	3.2. Reaching a New Audience

4. The Public Happiness Movement Token

	4.1. Token Overview

5. Public Happiness Movement Token ICO

	5.1. ICO Strategy

	5.2. ICO Stages

	5.3. Ongoing Funding for Specific Projects and Experts

	5.4. ICO Marketing

6. Public Happiness – Background

	6.1. Community Background

	6.2. The Public Happiness Movement Community

7. Platform Overview

	7.1. The Public Happiness Map (public actions for increasing human and society well-being)

	7.2. Action Center (Microvolunteering)

	7.3. Community News

	7.4. Active Happiness Shop

	7.5. Who Defines What is Accepted as ‘Public Happiness’

	7.6. Evidence Based and Peer Reviewed Actions

	7.7. Who can Participate on the Platform

	7.8. Pre-existing Communities with Similar Values

	7.9. Languages

	7.10. Decentralised Governance and Voting

8. The Path to Decentralisation

	8.1. Benevolent Dictatorship vs Complete Community Governance

	8.2. Example Scenario: Outside Collusion

	8.3. Lines of Defence

	8.4. Conclusion

9. Security

	9.1. Levels of Trust

	9.2.. Community Administrators

	9.3. Project Administrators

	9.4. Mining Limits

	9.5. Cold Storage and Key Holders

10. Marketing Strategy

	10.1. A New Level of Hash Tagging

	10.2. Bus Tour

	10.3.. Public Happiness Channel

	10.4. Happy Cam

	10.5. Public Happiness Partners

	10.6. Online Supporters

	10.7. Contests

	10.8. Collectables

11.  Automated Token Distribution Matrix

      	11.1. Weighted Mining

      	11.2. Hard Cap

      	11.3. Adjusting the Balancing

      	11.4. Token Release

      	11.5. Mining Table

      	11.6. Experience Multipliers

     	11.7. Token Distribution

     11.8. Further Matrix Considerations

12. Team

	12.1. Current Team Members

	12.2. Positions Open

	12.3. Remuneration

	12.4. Facilities

13. Platform Technicals

	13.1. Crypto Linking Bridges

	13.2. Trello vs Wekan vs Other Solutions

	13.3. Leaflet.js vs Google Maps API

	13.4. Switching the Platform to the Dapps Network

14. Doomsday Protocol

	14.1. Huge Market Crash

	14.2. Quantum Security

	14.3. Massive Hack

	14.4. Zombie Apocalypse

15. Giving Back to Open-source

16. Timeline

17. White Paper Reviewed By

18. Questions to be Resolved

 </React.Fragment>
 )

const markdownSection1 = md.render(`

# Public Happiness Movement Token

# Whitepaper

**Foreword:**

I've lived about as frugal a life as is possible in the Western World because I've always disliked money.  It so often seems to have a negative effect on people and society.

The crypto-world has me intensely curious, because money can be different there. I wanted to learn more and see if it's possible to design a form of money that is intrinsically tied to creating societal value.  Something to act as a band-aid on today’s ‘profit at all costs’ capitalism which has blind-spots for large areas critical to producing healthy, happy societies. This is caused by foundations measuring all progress and success as an increase in GDP. Anything which doesn’t is, by design, an after-thought.

GDP was designed by Simon Kuznets, in 1937 as a temporary post war recovery system, but the beast got out of control. The damage caused to humanity by basing our decision making processes on measurements of GDP isn’t even contentious anymore. [Here’s a list](http://ec.europa.eu/environment/beyond_gdp/key_quotes_en.html) of global and economic leaders stating the need to move past it.

This token is an effort to create a new monetary and economic system. One which focuses energy onto these essential societal areas which are currently overlooked. An effort to create a healthier and happier world.

**Intro:**
If the right people get behind this it will have a profound effect on increasing peace, happiness, and reducing human-suffering across the world. If you’re reading this it because we believe that you have the skills to contribute, and a passion to create positive change for humanity.

> "Those who love peace must learn to organize as effectively as those who love war"  - Martin Luther King

Our community of volunteers has been gradually building a platform to host this vision for over 3 years now. The platform is for groups from around the world, anyone who is using positive actions to promote peace and wellbeing through building human and community connection.

It's provides a space for our individual networks to grow into something larger. A global movement for a world with more peace and happiness in it. We’ve reached the point where it is ready to begin hosting communities who will contribute to it governance and improving the platform. You can take a look here: [focallocal.org ](https://focallocal.org)

Note: This white paper is quite long. The most effective way to contribute is by reading the intro and why ‘the world needs this’, and then clicking the sections in the contents page which you’d most like to contribute to. To discuss a section and make suggestions, click on the red balloons.
`)

const markdownSection2 = md.render(`
# Markdown contents

The World Needs This Because
1. [Abstract](#test)
	1.1. [Background](#test2)
	1.2. [Public Happiness Movement Token Introduction](#test3)

2. [Problem Statement](#test4)
	2.1. Issues we aim to solv
	2.2. Primary Goa
	2.3. Secondary Goa
	2.4. Relation to Universal Basic Income

3. Educating the Public about Blockchain
	3.1. Current State of Public Understanding
				   `)

const markdownSection3 = md.render(`## test INSERT SECTION 3 HEre`)
const markdownSection4 = md.render(`## test2 INSERT SECTION 3 HEre`)
const markdownSection5 = md.render(`## test4 INSERT SECTION 3 HEre`)
const markdownSection6 = md.render(`## Some paragraph <a name="test5"></a>INSERT SECTION 3 HEre`)
const markdownSection7 = md.render(`## Some paragraph <a name="test6"></a>INSERT SECTION 3 HEre`)
const markdownSection8 = md.render(`## Some paragraph <a name="test7"></a>INSERT SECTION 3 HEre`)
const markdownSection9 = md.render(`## Some paragraph <a name="test8"></a>INSERT SECTION 3 HEre`)
const markdownSection10 = md.render(`## Some paragraph <a name="test9"></a>INSERT SECTION 3 HEre`)
const markdownSection11 = md.render(`## Some paragraph <a name="test10"></a>INSERT SECTION 3 HEre`)
const markdownSection12 = md.render(`## Some paragraph <a name="test11"></a>INSERT SECTION 3 HEre`)
const markdownSection13 = md.render(`## Some paragraph <a name="test12"></a>INSERT SECTION 3 HEre`)
const markdownSection14 = md.render(`## Some paragraph <a name="test13"></a>INSERT SECTION 3 HEre`)
const markdownSection15 = md.render(`## Some paragraph <a name="test14"></a>INSERT SECTION 3 HEre`)
const markdownSection16 = md.render(`## Some paragraph <a name="test15"></a>INSERT SECTION 3 HEre`)
const markdownSection17 = md.render(`## Some paragraph <a name="test16"></a>INSERT SECTION 3 HEre`)

const index = (props) => {
  return (
    <Container className="mt-5">
			<Contents />

      <DCSBalloon title="The World Needs This Because V1" balloonId="bal" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

    </Container>

  );
};

export default index;
<commit_msg>adding standard anchor links<commit_after>import React from "react";
import { Container } from "reactstrap";
import './styles.scss'
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Remarkable = require('remarkable');

const md = new Remarkable();
md.set({
  breaks: true,
  linkify: true
});

const Contents = () => (
   <React.Fragment>

Welcome to the 1st Draft!

Contents

The World Needs This Because: (v1)

The World Needs This Because: (v2)

1. Abstract

1.1. Background

	1.2. Public Happiness Movement Token Introduction

2. Problem Statement

	2.1. Issues we aim to solve

	2.2. Primary Goal

	2.3. Secondary Goal

	2.4. Relation to Universal Basic Income

3. Educating the Public about Blockchain

	3.1. Current State of Public Understanding

	3.2. Reaching a New Audience

4. The Public Happiness Movement Token

	4.1. Token Overview

5. Public Happiness Movement Token ICO

	5.1. ICO Strategy

	5.2. ICO Stages

	5.3. Ongoing Funding for Specific Projects and Experts

	5.4. ICO Marketing

6. Public Happiness – Background

	6.1. Community Background

	6.2. The Public Happiness Movement Community

7. Platform Overview

	7.1. The Public Happiness Map (public actions for increasing human and society well-being)

	7.2. Action Center (Microvolunteering)

	7.3. Community News

	7.4. Active Happiness Shop

	7.5. Who Defines What is Accepted as ‘Public Happiness’

	7.6. Evidence Based and Peer Reviewed Actions

	7.7. Who can Participate on the Platform

	7.8. Pre-existing Communities with Similar Values

	7.9. Languages

	7.10. Decentralised Governance and Voting

8. The Path to Decentralisation

	8.1. Benevolent Dictatorship vs Complete Community Governance

	8.2. Example Scenario: Outside Collusion

	8.3. Lines of Defence

	8.4. Conclusion

9. Security

	9.1. Levels of Trust

	9.2.. Community Administrators

	9.3. Project Administrators

	9.4. Mining Limits

	9.5. Cold Storage and Key Holders

10. Marketing Strategy

	10.1. A New Level of Hash Tagging

	10.2. Bus Tour

	10.3.. Public Happiness Channel

	10.4. Happy Cam

	10.5. Public Happiness Partners

	10.6. Online Supporters

	10.7. Contests

	10.8. Collectables

11.  Automated Token Distribution Matrix

      	11.1. Weighted Mining

      	11.2. Hard Cap

      	11.3. Adjusting the Balancing

      	11.4. Token Release

      	11.5. Mining Table

      	11.6. Experience Multipliers

     	11.7. Token Distribution

     11.8. Further Matrix Considerations

12. Team

	12.1. Current Team Members

	12.2. Positions Open

	12.3. Remuneration

	12.4. Facilities

13. Platform Technicals

	13.1. Crypto Linking Bridges

	13.2. Trello vs Wekan vs Other Solutions

	13.3. Leaflet.js vs Google Maps API

	13.4. Switching the Platform to the Dapps Network

14. Doomsday Protocol

	14.1. Huge Market Crash

	14.2. Quantum Security

	14.3. Massive Hack

	14.4. Zombie Apocalypse

15. Giving Back to Open-source

16. Timeline

17. White Paper Reviewed By

18. Questions to be Resolved

 </React.Fragment>
 )

const markdownSection1 = md.render(`

# Public Happiness Movement Token

# Whitepaper

**Foreword:**

I've lived about as frugal a life as is possible in the Western World because I've always disliked money.  It so often seems to have a negative effect on people and society.

The crypto-world has me intensely curious, because money can be different there. I wanted to learn more and see if it's possible to design a form of money that is intrinsically tied to creating societal value.  Something to act as a band-aid on today’s ‘profit at all costs’ capitalism which has blind-spots for large areas critical to producing healthy, happy societies. This is caused by foundations measuring all progress and success as an increase in GDP. Anything which doesn’t is, by design, an after-thought.

GDP was designed by Simon Kuznets, in 1937 as a temporary post war recovery system, but the beast got out of control. The damage caused to humanity by basing our decision making processes on measurements of GDP isn’t even contentious anymore. [Here’s a list](http://ec.europa.eu/environment/beyond_gdp/key_quotes_en.html) of global and economic leaders stating the need to move past it.

This token is an effort to create a new monetary and economic system. One which focuses energy onto these essential societal areas which are currently overlooked. An effort to create a healthier and happier world.

**Intro:**
If the right people get behind this it will have a profound effect on increasing peace, happiness, and reducing human-suffering across the world. If you’re reading this it because we believe that you have the skills to contribute, and a passion to create positive change for humanity.

> "Those who love peace must learn to organize as effectively as those who love war"  - Martin Luther King

Our community of volunteers has been gradually building a platform to host this vision for over 3 years now. The platform is for groups from around the world, anyone who is using positive actions to promote peace and wellbeing through building human and community connection.

It's provides a space for our individual networks to grow into something larger. A global movement for a world with more peace and happiness in it. We’ve reached the point where it is ready to begin hosting communities who will contribute to it governance and improving the platform. You can take a look here: [focallocal.org ](https://focallocal.org)

Note: This white paper is quite long. The most effective way to contribute is by reading the intro and why ‘the world needs this’, and then clicking the sections in the contents page which you’d most like to contribute to. To discuss a section and make suggestions, click on the red balloons.
`)

const markdownSection2 = md.render(`

Abstract
text

text

text
				   `)

const markdownSection3 = md.render(`

Background
text

text

text

`)
const markdownSection4 = md.render(`## test2 INSERT SECTION 3 HEre`)
const markdownSection5 = md.render(`## test4 INSERT SECTION 3 HEre`)
const markdownSection6 = md.render(`## Some paragraph <a name="test5"></a>INSERT SECTION 3 HEre`)
const markdownSection7 = md.render(`## Some paragraph <a name="test6"></a>INSERT SECTION 3 HEre`)
const markdownSection8 = md.render(`## Some paragraph <a name="test7"></a>INSERT SECTION 3 HEre`)
const markdownSection9 = md.render(`## Some paragraph <a name="test8"></a>INSERT SECTION 3 HEre`)
const markdownSection10 = md.render(`## Some paragraph <a name="test9"></a>INSERT SECTION 3 HEre`)
const markdownSection11 = md.render(`## Some paragraph <a name="test10"></a>INSERT SECTION 3 HEre`)
const markdownSection12 = md.render(`## Some paragraph <a name="test11"></a>INSERT SECTION 3 HEre`)
const markdownSection13 = md.render(`## Some paragraph <a name="test12"></a>INSERT SECTION 3 HEre`)
const markdownSection14 = md.render(`## Some paragraph <a name="test13"></a>INSERT SECTION 3 HEre`)
const markdownSection15 = md.render(`## Some paragraph <a name="test14"></a>INSERT SECTION 3 HEre`)
const markdownSection16 = md.render(`## Some paragraph <a name="test15"></a>INSERT SECTION 3 HEre`)
const markdownSection17 = md.render(`## Some paragraph <a name="test16"></a>INSERT SECTION 3 HEre`)

const index = (props) => {
  return (
    <Container className="mt-5">
			<Contents />

      <DCSBalloon title="The World Needs This Because V1" balloonId="bal" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

      <DCSBalloon title="Insert title" subtitle="Insert subtitle" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />

    </Container>

  );
};

export default index;
<|endoftext|>


<commit_before>
// nodej bits
var util          = require('util')
var Stream        = require('stream')
var EventEmitter  = require('events').EventEmitter
var Dispatcher    = process.binding('Dispatcher')
var vertx         = require('vertx')

// netty bits
var ChannelFactory  = org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory
var ChannelGroup    = org.jboss.netty.channel.group.DefaultChannelGroup
var ChannelHandler  = org.jboss.netty.channel.SimpleChannelHandler
var PipelineFactory = org.jboss.netty.channel.ChannelPipelineFactory
var ServerBootstrap = org.jboss.netty.bootstrap.ServerBootstrap
var ClientBootstrap = org.jboss.netty.bootstrap.ClientBootstrap
var Channels        = org.jboss.netty.channel.Channels

// java bits
var SocketAddress   = java.net.InetSocketAddress
var Executor        = java.util.concurrent.Executor
var Executors       = java.util.concurrent.Executors

var Server = function( listener ) {

  that = this;
  this.server = vertx.createNetServer().connectHandler( function(sock) {
    if (listener) {
      // TODO: Create a node.js compatible socket
      // to pass to the node-like listener
      listener(sock);
    }
  });

  this.connectionListener = listener
  this.address = {}

  this.log = function(msg) {
    return Dispatcher.submit( function() {
      java.lang.System.err.println(msg)
    } )
  }

  this.listen = function(port, host, callback) {
    if (typeof(host) == 'function') {
      callback = host;
      host = 'localhost';
    } else if (host == null || host == undefined) {
      host = "localhost";
    }
    this.server.listen(port, host);
    that.address.port = port;
    that.address.host = host;
    // TODO: Vert.x does not provide bind address information?
    // server.address.family = (address.address.address.length) == 4 ? 'IPv4' : 'IPv6'
    // server.address.address = address.address.canonicalHostName

    // TODO: Vert.x does not provide notification
    // for a 'listening' event whent the server
    // has been bound.
    if (callback) {
      that.addListener('listening', callback);
      that.emit('listening');
    }
  }

  this.close = function(callback) {
    this.server.close(function() {
      if (callback) { that.addListener('close', callback); }
      that.emit('close');
    });
  }
}

var Socket = function(context, evnt) {
  this.factory = new ChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool())
  this.context  = context
  this.evnt     = evnt
  this.encoding = 'utf8'
  this.writable = true

  this.connect = function(port, host, connectListener) {
    this.type = 'tcp4'
    if (!host) {
      host = 'localhost'
    }
    bootstrap = new ClientBootstrap(this.factory)
    bootstrap.setPipelineFactory(ClientPipeline(this))
    bootstrap.setOption("keepAlive", false)
    bootstrap.setOption("tcpNoDelay", true)
    address = new SocketAddress(host, port)
    if (connectListener) {
      this.on('connect', connectListener)
    }
    this.emit('connect')
  }

  this.setEncoding = function(encoding) {
    this.encoding = encoding
  }

  this.write = function(string, encoding, callback) {
    return Dispatcher.submit(function(socket) {
      channel = socket.evnt.getChannel()
      future = channel.write(string)
      if (callback) {
        future.awaitUninterruptibly()
        callback.apply(callback)
      }
    }, this )
  }

  this.destroy = function() {
    return Dispatcher.submit(function(socket) {
      socket.evnt.getChannel().close()
      socket.writable = false
      socket.emit('close')
    }, this)
  }

  this.end = function(data) {
    return Dispatcher.submit(function(socket) {
      if (data) {
        future = socket.write(data)
        future.awaitUninterruptibly()
      }
      future = socket.evnt.getChannel().close()
      future.awaitUninterruptibly()
      socket.writable = false
      socket.emit('end')
    }, this)
  }
  this.destroySoon = this.end

  this.pause = function() { }
  this.resume = function() { }
  this.setTimeout = function() { }
  this.setNoDelay = function() { }
  this.setKeepAlive = function() { }
  this.address = function() { }
  this.bytesRead = 0
  this.bytesWritten = 0
}
// Inheriting from Stream automatically makes
// us an EventEmitter too. Yay.
util.inherits(Socket, Stream)

var ClientHandler = function(client) {
}

var ServerHandler = function(server) {

  return new ChannelHandler( {
    messageReceived: function(context, evnt) {
      callback = server.connectionListener
      if (callback) {
        // Create a new socket object and give it
        // to the connection listener
        callback.apply( callback, new Socket(context, evnt) )
      }
    },

    channelOpen: function(context, evnt) {
      server.channels.add( evnt.getChannel() )
      server.emit('connection')
    },

    exceptionCaught: function(context, evnt) {
      evnt.cause.printStackTrace()
      evnt.channel.close()
      server.emit('error', true)
      server.close()
    }
  } )
}

var ClientPipeline = function(client) {
  return new PipelineFactory( {
    getPipeline: function() {
      handler = ClientHandler(client)
      return Channels.pipeline(handler)
    }
  } )
}

var ServerPipeline = function(server) {
  return new PipelineFactory( {
    getPipeline: function() {
      handler = ServerHandler(server)
    server.log("SERVER: " + server.toString())
      return Channels.pipeline(handler)
    }
  } )
}

util.inherits(Server, EventEmitter)

module.exports.Socket = Socket
module.exports.Server = Server
module.exports.createServer = function(listener) {
  return new Server(listener)
}

<commit_msg>Remove all the netty bits in net.js and replace with vert.x bits.<commit_after>
// nodej bits
var util          = require('util')
var Stream        = require('stream')
var EventEmitter  = require('events').EventEmitter
var Dispatcher    = process.binding('Dispatcher')
var vertx         = require('vertx')

// java bits
var SocketAddress   = java.net.InetSocketAddress
var Executor        = java.util.concurrent.Executor
var Executors       = java.util.concurrent.Executors

var Server = function( connectionListener ) {

  var that = this;
  that.address = {}
  that.server = vertx.createNetServer();

  if (connectionListener) {
      that.on('connection', connectionListener);
  }

  that.listen = function(port, host, callback) {
    // TODO: This is ugly
    if (!host) {
      host = 'localhost';
    } else if (typeof(host) == 'function') {
      callback = host;
      host = 'localhost';
    }

    // activate the 'listening' callback
    if (callback) { that.on('listening', callback); }

    // setup a connection handler in vert.x
    that.server.connectHandler( function(sock) {
      nodeSocket = new Socket();
      nodeSocket.setProxy(sock);
      sock.dataHandler( function(buffer) {
        // TODO: Make this a node.js compatible buffer
        nodeSocket.emit('data', buffer);
      });
      that.emit('connection', nodeSocket);
    });

    // listen for incoming connections
    that.server.listen(port, host);

    // TODO: Vert.x does not provide bind address information?
    // server.address.family = (address.address.address.length) == 4 ? 'IPv4' : 'IPv6'
    // server.address.address = address.address.canonicalHostName
    that.address.port = port;
    that.address.host = host;

    // TODO: Vert.x does not provide notification
    // for a 'listening' event whent the server
    // has been bound, so we'll just emit the event
    // now, once we've set everything up.
    that.emit('listening');
  }

  that.close = function(callback) {
    that.server.close(function() {
      if (callback) { that.on('close', callback); }
      that.emit('close');
    });
  }
}

var Socket = function() {
  var that = this;
  that.encoding = 'utf8';
  that.writable = true;

  that.setProxy = function(proxy) {
    that.proxy = proxy;
  }

  that.connect = function(port, host, connectListener) {
    if (!host) { host = 'localhost'; }
    if (connectListener) { that.on('connect', connectListener); }

    client = vertx.createNetClient();
    client.connect( port, host, function(sock) {
      that.setProxy(sock);
      that.emit('connect');
    });
  }

  that.write = function(string, encoding, callback) {
    proxy.write(data, encoding, function() {
      if (callback) { callback.apply(callback); }
    });
  }

  that.destroy = function() {
    proxy.close(function() {
      that.writable = false;
      that.emit('close');
    });
  }

  that.end = function(data) {
    that.write(data, function() {
      that.destroy();
      that.emit('end');
    });
  }

  that.destroySoon = that.end;

  that.setEncoding = function(encoding) {
    that.encoding = encoding;
  }

  that.pause = function() { }
  that.resume = function() { }
  that.setTimeout = function() { }
  that.setNoDelay = function() { }
  that.setKeepAlive = function() { }
  that.address = function() { }
  that.bytesRead = 0;
  that.bytesWritten = 0;
}

// Inheriting from Stream automatically makes
// us an EventEmitter too. Yay.
util.inherits(Socket, Stream);
util.inherits(Server, EventEmitter);

module.exports.Socket = Socket;
module.exports.Server = Server;
module.exports.createServer = function(connectionListener) {
  return new Server(connectionListener);
}

<|endoftext|>


<commit_before>/* * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
 *
 * http://www.gnu.org/licenses/lgpl.html
 *
 * @description: This class provide additional format to numbers by extending Ext.form.field.Number
 *
 * @author: Greivin Britton
 * @email: brittongr@gmail.com
 * @version: 2 compatible with ExtJS 4 (And ExtJS 5 - chamacs)
 */
Ext.define('Ext.ux.form.field.Currency', {
    extend: 'Ext.form.field.Number',//Extending the NumberField
    xtype: [
        'currencyfield',
        'numericfield'
    ],
    alternateClassName: ['Ext.ux.form.field.Numeric', 'Ext.ux.form.NumericField'],
    currencySymbol: '$ ',
    useThousandSeparator: true,
    thousandSeparator: '.',
    alwaysDisplayDecimals: true,
    // MOD - chamacs
    // @private
    isCurrency: false,

    // MOD - pmiguelmartins
    currencySymbolPos: 'left', // left , right

    // MOD - chamacs
    //fieldStyle: 'text-align: right;',

    // MOD - chamacs
    allowExponential: false,

    /**
     * initComponent
     */
    initComponent: function () {
        if (this.useThousandSeparator && this.decimalSeparator == ',' && this.thousandSeparator == ',') {
            this.thousandSeparator = '.';
        }
        else if (this.allowDecimals && this.thousandSeparator == '.' && this.decimalSeparator == '.') {
            this.decimalSeparator = ',';
        }

        // MOD - chamacs
        this.isCurrency = !Ext.isEmpty(this.currencySymbol);

        this.callParent(arguments);
    },

    /**
     * setValue
     */
    setValue: function (value) {
        var me = this,
            bind, valueBind;

        // This portion of the code is to prevent a binding from stomping over
        // the typed value. Say we have decimalPrecision 4 and the user types
        // 1.23456. The value of the field will be set as 1.2346 and published to
        // the viewmodel, which will trigger the binding to fire and setValue to
        // be called on the field, which would then set the value (and rawValue) to
        // 1.2346. Instead, if we have focus and the value is the same, just leave
        // the rawValue alone
        if (me.hasFocus) {
            bind = me.getBind();
            valueBind = bind && bind.value;
            if (valueBind && valueBind.syncing && value === me.value) {
                return me;
            }
        }

        // MOD - chamacs
        Ext.ux.form.field.Currency.superclass.setValue.apply(this, [value != null ? value.toString().replace('.', this.decimalSeparator) : value]);

        this.setRawValue(this.getFormattedValue(this.getValue()));
    },

    /**
     * getFormattedValue
     */
    getFormattedValue: function (value) {
        if (Ext.isEmpty(value) || !this.hasFormat()) {
            return value;
        }
        else {
            var neg = null;

            value = (neg = value < 0) ? value * -1 : value;
            value = this.allowDecimals && this.alwaysDisplayDecimals ? value.toFixed(this.decimalPrecision) : value;

            if (this.useThousandSeparator) {
                if (this.useThousandSeparator && Ext.isEmpty(this.thousandSeparator)) {
                    throw ('NumberFormatException: invalid thousandSeparator, property must has a valid character.');
                }
                if (this.thousandSeparator == this.decimalSeparator) {
                    throw ('NumberFormatException: invalid thousandSeparator, thousand separator must be different from decimalSeparator.');
                }

                value = value.toString();

                var ps = value.split('.');
                ps[1] = ps[1] ? ps[1] : null;

                var whole = ps[0];

                var r = /(\d+)(\d{3})/;

                var ts = this.thousandSeparator;

                while (r.test(whole)) {
                    whole = whole.replace(r, '$1' + ts + '$2');
                }

                value = whole + (ps[1] ? this.decimalSeparator + ps[1] : '');
            }

            // MOD - pmiguelmartins - updated by chamacs
            var position1 = this.isCurrency ? this.currencySymbol + ' ' : '';
            var position2 = value;
            if (this.currencySymbolPos === 'right') {
                position1 = value;
                position2 = this.isCurrency ? ' ' + this.currencySymbol : '';
            }
            return Ext.String.format('{0}{1}{2}', position1, (neg ? '-' : ''), position2);
        }
    },

    /**
     * overrides parseValue to remove the format applied by this class
     */
    parseValue: function (value) {
        // MOD - chamacs
        //Replace the currency symbol and thousand separator
        return Ext.ux.form.field.Currency.superclass.parseValue.apply(this, [this.removeFormat(value)]);
    },

    /**
     * Remove only the format added by this class to let the superclass validate with it's rules.
     * @param {Object} value
     */
    removeFormat: function (value) {
        // MOD - chamacs
        if (Ext.isEmpty(value)) {
            return '';
        }
        else if (!this.hasFormat()) {
            return value;
        }
        else {
            // MOD - bhaidaya
            value = Ext.String.trim(value.toString().replace(this.currencySymbol, ''));

            value = this.useThousandSeparator ? value.replace(new RegExp('[' + this.thousandSeparator + ']', 'g'), '') : value;
            return value;
        }
    },

    /** * Remove the format before validating the the value.
     * @param {Number} value
     */
    getErrors: function (value) {
        //FIX data binding by antiplaka
        value = arguments.length > 0 ? value : this.processRawValue(this.getRawValue());
        return this.callParent([this.removeFormat(value)]);
    },

    /**
     * hasFormat
     */
    hasFormat: function () {
        return this.decimalSeparator != '.' || (this.useThousandSeparator == true && this.getRawValue() != null) || !Ext.isEmpty(this.currencySymbol) || this.alwaysDisplayDecimals;
    },

    /**
     * Display the numeric value with the fixed decimal precision and without the format using the setRawValue, don't need to do a setValue because we don't want a double
     * formatting and process of the value because beforeBlur perform a getRawValue and then a setValue.
     */
    onFocus: function () {
        this.setRawValue(this.removeFormat(this.getRawValue()));

        this.callParent(arguments);
    },

    /**
     * MOD - Jeff.Evans
     */
    processRawValue: function (value) {
        return this.removeFormat(value);
    }
});
<commit_msg>add contributor<commit_after>/* * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
 *
 * http://www.gnu.org/licenses/lgpl.html
 *
 * @description: This class provide additional format to numbers by extending Ext.form.field.Number
 *
 * @author: Greivin Britton
 * @contributor: Wemerson Januario (wemerson.januario@gmail.com)
 * @email: brittongr@gmail.com
 * @version: 2 compatible with ExtJS 4 (And ExtJS 5 - chamacs)
 *
 */
Ext.define('Ext.ux.form.field.Currency', {
    extend: 'Ext.form.field.Number',//Extending the NumberField
    xtype: [
        'currencyfield',
        'numericfield'
    ],
    alternateClassName: ['Ext.ux.form.field.Numeric', 'Ext.ux.form.NumericField'],
    currencySymbol: '$ ',
    useThousandSeparator: true,
    thousandSeparator: '.',
    alwaysDisplayDecimals: true,
    // MOD - chamacs
    // @private
    isCurrency: false,

    // MOD - pmiguelmartins
    currencySymbolPos: 'left', // left , right

    // MOD - chamacs
    //fieldStyle: 'text-align: right;',

    // MOD - chamacs
    allowExponential: false,

    /**
     * initComponent
     */
    initComponent: function () {
        if (this.useThousandSeparator && this.decimalSeparator == ',' && this.thousandSeparator == ',') {
            this.thousandSeparator = '.';
        }
        else if (this.allowDecimals && this.thousandSeparator == '.' && this.decimalSeparator == '.') {
            this.decimalSeparator = ',';
        }

        // MOD - chamacs
        this.isCurrency = !Ext.isEmpty(this.currencySymbol);

        this.callParent(arguments);
    },

    /**
     * setValue
     */
    setValue: function (value) {
        var me = this,
            bind, valueBind;

        // This portion of the code is to prevent a binding from stomping over
        // the typed value. Say we have decimalPrecision 4 and the user types
        // 1.23456. The value of the field will be set as 1.2346 and published to
        // the viewmodel, which will trigger the binding to fire and setValue to
        // be called on the field, which would then set the value (and rawValue) to
        // 1.2346. Instead, if we have focus and the value is the same, just leave
        // the rawValue alone
        if (me.hasFocus) {
            bind = me.getBind();
            valueBind = bind && bind.value;
            if (valueBind && valueBind.syncing && value === me.value) {
                return me;
            }
        }

        // MOD - chamacs
        Ext.ux.form.field.Currency.superclass.setValue.apply(this, [value != null ? value.toString().replace('.', this.decimalSeparator) : value]);

        this.setRawValue(this.getFormattedValue(this.getValue()));
    },

    /**
     * getFormattedValue
     */
    getFormattedValue: function (value) {
        if (Ext.isEmpty(value) || !this.hasFormat()) {
            return value;
        }
        else {
            var neg = null;

            value = (neg = value < 0) ? value * -1 : value;
            value = this.allowDecimals && this.alwaysDisplayDecimals ? value.toFixed(this.decimalPrecision) : value;

            if (this.useThousandSeparator) {
                if (this.useThousandSeparator && Ext.isEmpty(this.thousandSeparator)) {
                    throw ('NumberFormatException: invalid thousandSeparator, property must has a valid character.');
                }
                if (this.thousandSeparator == this.decimalSeparator) {
                    throw ('NumberFormatException: invalid thousandSeparator, thousand separator must be different from decimalSeparator.');
                }

                value = value.toString();

                var ps = value.split('.');
                ps[1] = ps[1] ? ps[1] : null;

                var whole = ps[0];

                var r = /(\d+)(\d{3})/;

                var ts = this.thousandSeparator;

                while (r.test(whole)) {
                    whole = whole.replace(r, '$1' + ts + '$2');
                }

                value = whole + (ps[1] ? this.decimalSeparator + ps[1] : '');
            }

            // MOD - pmiguelmartins - updated by chamacs
            var position1 = this.isCurrency ? this.currencySymbol + ' ' : '';
            var position2 = value;
            if (this.currencySymbolPos === 'right') {
                position1 = value;
                position2 = this.isCurrency ? ' ' + this.currencySymbol : '';
            }
            return Ext.String.format('{0}{1}{2}', position1, (neg ? '-' : ''), position2);
        }
    },

    /**
     * overrides parseValue to remove the format applied by this class
     */
    parseValue: function (value) {
        // MOD - chamacs
        //Replace the currency symbol and thousand separator
        return Ext.ux.form.field.Currency.superclass.parseValue.apply(this, [this.removeFormat(value)]);
    },

    /**
     * Remove only the format added by this class to let the superclass validate with it's rules.
     * @param {Object} value
     */
    removeFormat: function (value) {
        // MOD - chamacs
        if (Ext.isEmpty(value)) {
            return '';
        }
        else if (!this.hasFormat()) {
            return value;
        }
        else {
            // MOD - bhaidaya
            value = Ext.String.trim(value.toString().replace(this.currencySymbol, ''));

            value = this.useThousandSeparator ? value.replace(new RegExp('[' + this.thousandSeparator + ']', 'g'), '') : value;
            return value;
        }
    },

    /** * Remove the format before validating the the value.
     * @param {Number} value
     */
    getErrors: function (value) {
        //FIX data binding by antiplaka
        value = arguments.length > 0 ? value : this.processRawValue(this.getRawValue());
        return this.callParent([this.removeFormat(value)]);
    },

    /**
     * hasFormat
     */
    hasFormat: function () {
        return this.decimalSeparator != '.' || (this.useThousandSeparator == true && this.getRawValue() != null) || !Ext.isEmpty(this.currencySymbol) || this.alwaysDisplayDecimals;
    },

    /**
     * Display the numeric value with the fixed decimal precision and without the format using the setRawValue, don't need to do a setValue because we don't want a double
     * formatting and process of the value because beforeBlur perform a getRawValue and then a setValue.
     */
    onFocus: function () {
        this.setRawValue(this.removeFormat(this.getRawValue()));

        this.callParent(arguments);
    },

    /**
     * MOD - Jeff.Evans
     */
    processRawValue: function (value) {
        return this.removeFormat(value);
    }
});
<|endoftext|>