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

'use strict';

var color = require('ansi-color').set;
var hex = require('hexer');
var TypedError = require('error/typed');
var util = require('util');

var ShortReadError = TypedError({
    type: 'short-read',
    message: 'short read, {remaining} byte left over after consuming {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var ShortWriteError = TypedError({
    type: 'short-write',
    message: 'short write, {remaining} byte left over after writing {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var emptyBuffer = Buffer(0);

function fromBuffer(struct, buffer, offset) {
    var tup = fromBufferTuple(struct, buffer, offset);
    var err = tup[0];
    var value = tup[1];
    if (err) throw err;
    else return value;
}

function byteLength(struct, value) {
    var tup = byteLengthTuple(struct, value);
    var err = tup[0];
    var length = tup[1];
    if (err) throw err;
    else return length;
}

function toBuffer(struct, value) {
    var tup = toBufferTuple(struct, value);
    var err = tup[0];
    var buffer = tup[1];
    if (err) throw err;
    else return buffer;
}

function intoBuffer(struct, buffer, value) {
    var tup = intoBufferTuple(struct, buffer, value);
    var err = tup[0];
    buffer = tup[1];
    if (err) throw err;
    else return buffer;
}

function fromBufferTuple(struct, buffer, offset) {
    offset = offset || 0;
    var res = struct.readFrom(buffer, offset);
    offset = res.offset;
    var err = res.err;
    if (!err && offset !== buffer.length) {
        err = ShortReadError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        });
    }
    if (err) {
        if (err.offset === undefined) err.offset = offset;
        if (err.buffer === undefined) err.buffer = buffer;
    }
    return [err, res.value];
}

function byteLengthTuple(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return [lenRes.err, 0];
    else return [null, lenRes.length];
}

function toBufferTuple(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return [lenRes.err, emptyBuffer];
    var length = lenRes.length;
    var buffer = new Buffer(length);
    // buffer.fill(0); TODO option
    return intoBufferTuple(struct, buffer, value);
}

function intoBufferTuple(struct, buffer, value) {
    var writeRes = struct.writeInto(value, buffer, 0);
    if (writeRes.err) {
        // istanbul ignore else
        if (!Buffer.isBuffer(writeRes.err.buffer)) writeRes.err.buffer = buffer;
        if (typeof writeRes.err.offset !== 'number') writeRes.err.offset = writeRes.offset;
        return [writeRes.err, buffer];
    }
    var offset = writeRes.offset;
    if (offset !== buffer.length) {
        return [ShortWriteError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        }), buffer];
    }
    return [null, buffer];
}

// istanbul ignore next TODO
function formatError(err, options) {
    options = options || {};
    var name = err.name || err.constructor.name;
    var str = util.format('%s: %s\n', name, err.message);
    if (Buffer.isBuffer(err.buffer)) {
        if (options.color) {
            str += formatBufferColored(err, options);
        } else {
            str += formatBufferUncolored(err, options);
        }
        str += '\n';
    }
    return str;
}

// istanbul ignore next TODO
function formatBufferColored(err, options) {
    options = options || {};
    var markColor = options.markColor || 'red+bold';

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var within = false;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        if (hasEnd) {
        opts.decorateHexen = decorateRangedError;
        opts.decorateHuman = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
            opts.decorateHuman = decorateError;
        }
    }
    return hex(err.buffer, opts);

    function decorateRangedError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            within = totalOffset !== err.endOffset-1;
            return color(str, markColor);
        } else if (totalOffset === err.endOffset-1) {
            within = false;
            return color(str, markColor);
        } else if (within) {
            return color(str, markColor);
        } else {
            return str;
        }
    }

    function decorateError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            return color(str, markColor);
        } else {
            return str;
        }
    }
}

// istanbul ignore next TODO
function formatBufferUncolored(err, options) {
    options = options || {};

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var markStart = options.markStart || '>';
    var markEnd = options.markEnd || '<';
    var accum = 0;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        opts.groupSeparator = '';
        if (hasEnd) {
            opts.decorateHexen = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
        }
    }
    return hex(err.buffer, opts);

    // TODO: suspected broken across lines, should either test and complete or
    // use some sort of alternate notation such as interstitial lines
    function decorateRangedError(totalOffset, screenOffset, hexen) {
        var s;
        if (totalOffset === err.offset) {
            accum = 1;
            s = markStart + hexen;
            if (totalOffset === err.endOffset-1) {
                s += markEnd;
                accum = 0;
            } else {
                s = ' ' + s;
            }
            return s;
        } else if (totalOffset === err.endOffset-1) {
            s = hexen + markEnd;
            while (accum-- > 0) s += ' ';
            accum = 0;
            return s;
        } else if (accum) {
            accum += 2;
            return hexen;
        } else {
            return ' ' + hexen + ' ';
        }
    }

    function decorateError(totalOffset, screenOffset, hexen) {
        if (totalOffset === err.offset) {
            return markStart + hexen + markEnd;
        } else {
            return ' ' + hexen + ' ';
        }
    }
}

module.exports.fromBuffer = fromBuffer;
module.exports.byteLength = byteLength;
module.exports.toBuffer = toBuffer;
module.exports.intoBuffer = intoBuffer;
module.exports.fromBufferTuple = fromBufferTuple;
module.exports.byteLengthTuple = byteLengthTuple;
module.exports.toBufferTuple = toBufferTuple;
module.exports.intoBufferTuple = intoBufferTuple;
module.exports.formatError = formatError;
<commit_msg>formatError: allow callers to specify their own marking function<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var color = require('ansi-color').set;
var hex = require('hexer');
var TypedError = require('error/typed');
var util = require('util');

var ShortReadError = TypedError({
    type: 'short-read',
    message: 'short read, {remaining} byte left over after consuming {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var ShortWriteError = TypedError({
    type: 'short-write',
    message: 'short write, {remaining} byte left over after writing {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var emptyBuffer = Buffer(0);

function fromBuffer(struct, buffer, offset) {
    var tup = fromBufferTuple(struct, buffer, offset);
    var err = tup[0];
    var value = tup[1];
    if (err) throw err;
    else return value;
}

function byteLength(struct, value) {
    var tup = byteLengthTuple(struct, value);
    var err = tup[0];
    var length = tup[1];
    if (err) throw err;
    else return length;
}

function toBuffer(struct, value) {
    var tup = toBufferTuple(struct, value);
    var err = tup[0];
    var buffer = tup[1];
    if (err) throw err;
    else return buffer;
}

function intoBuffer(struct, buffer, value) {
    var tup = intoBufferTuple(struct, buffer, value);
    var err = tup[0];
    buffer = tup[1];
    if (err) throw err;
    else return buffer;
}

function fromBufferTuple(struct, buffer, offset) {
    offset = offset || 0;
    var res = struct.readFrom(buffer, offset);
    offset = res.offset;
    var err = res.err;
    if (!err && offset !== buffer.length) {
        err = ShortReadError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        });
    }
    if (err) {
        if (err.offset === undefined) err.offset = offset;
        if (err.buffer === undefined) err.buffer = buffer;
    }
    return [err, res.value];
}

function byteLengthTuple(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return [lenRes.err, 0];
    else return [null, lenRes.length];
}

function toBufferTuple(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return [lenRes.err, emptyBuffer];
    var length = lenRes.length;
    var buffer = new Buffer(length);
    // buffer.fill(0); TODO option
    return intoBufferTuple(struct, buffer, value);
}

function intoBufferTuple(struct, buffer, value) {
    var writeRes = struct.writeInto(value, buffer, 0);
    if (writeRes.err) {
        // istanbul ignore else
        if (!Buffer.isBuffer(writeRes.err.buffer)) writeRes.err.buffer = buffer;
        if (typeof writeRes.err.offset !== 'number') writeRes.err.offset = writeRes.offset;
        return [writeRes.err, buffer];
    }
    var offset = writeRes.offset;
    if (offset !== buffer.length) {
        return [ShortWriteError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        }), buffer];
    }
    return [null, buffer];
}

// istanbul ignore next TODO
function formatError(err, options) {
    options = options || {};
    var name = err.name || err.constructor.name;
    var str = util.format('%s: %s\n', name, err.message);
    if (Buffer.isBuffer(err.buffer)) {
        if (options.color) {
            str += formatBufferColored(err, options);
        } else {
            str += formatBufferUncolored(err, options);
        }
        str += '\n';
    }
    return str;
}

// istanbul ignore next TODO
function formatBufferColored(err, options) {
    options = options || {};
    var markColor = options.markColor || 'red+bold';
    var errColor = typeof markColor === 'function' ? markColor : function(str) {
        return color(str, markColor);
    };

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var within = false;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        if (hasEnd) {
        opts.decorateHexen = decorateRangedError;
        opts.decorateHuman = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
            opts.decorateHuman = decorateError;
        }
    }
    return hex(err.buffer, opts);

    function decorateRangedError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            within = totalOffset !== err.endOffset-1;
            return errColor(str);
        } else if (totalOffset === err.endOffset-1) {
            within = false;
            return errColor(str);
        } else if (within) {
            return errColor(str);
        } else {
            return str;
        }
    }

    function decorateError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            return errColor(str);
        } else {
            return str;
        }
    }
}

// istanbul ignore next TODO
function formatBufferUncolored(err, options) {
    options = options || {};

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var markStart = options.markStart || '>';
    var markEnd = options.markEnd || '<';
    var accum = 0;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        opts.groupSeparator = '';
        if (hasEnd) {
            opts.decorateHexen = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
        }
    }
    return hex(err.buffer, opts);

    // TODO: suspected broken across lines, should either test and complete or
    // use some sort of alternate notation such as interstitial lines
    function decorateRangedError(totalOffset, screenOffset, hexen) {
        var s;
        if (totalOffset === err.offset) {
            accum = 1;
            s = markStart + hexen;
            if (totalOffset === err.endOffset-1) {
                s += markEnd;
                accum = 0;
            } else {
                s = ' ' + s;
            }
            return s;
        } else if (totalOffset === err.endOffset-1) {
            s = hexen + markEnd;
            while (accum-- > 0) s += ' ';
            accum = 0;
            return s;
        } else if (accum) {
            accum += 2;
            return hexen;
        } else {
            return ' ' + hexen + ' ';
        }
    }

    function decorateError(totalOffset, screenOffset, hexen) {
        if (totalOffset === err.offset) {
            return markStart + hexen + markEnd;
        } else {
            return ' ' + hexen + ' ';
        }
    }
}

module.exports.fromBuffer = fromBuffer;
module.exports.byteLength = byteLength;
module.exports.toBuffer = toBuffer;
module.exports.intoBuffer = intoBuffer;
module.exports.fromBufferTuple = fromBufferTuple;
module.exports.byteLengthTuple = byteLengthTuple;
module.exports.toBufferTuple = toBufferTuple;
module.exports.intoBufferTuple = intoBufferTuple;
module.exports.formatError = formatError;
<|endoftext|>


<commit_before>'use strict'

import React from 'react'
import Link from 'next/link'
import { style } from 'next/css'

import Meta from '../components/meta'
import Header from '../components/header'
import Footer from '../components/footer'
import { isLogged } from './../services/auth'

const styles = {
  row: {
    maxWidth: '900px',
    marginLeft: 'auto',
    marginRight: 'auto',

    '@media (max-width: 750px)': {
      paddingLeft: '20px',
      paddingRight: '20px'
    }
  },

  title: {
    color: '#333',
    fontWeight: '300',
    fontSize: '3rem',
    textAlign: 'center',
    marginTop: '50px'
  },

  subtitle: {
    color: '#ccc',
    fontWeight: '300',
    fontSize: '1.15rem',
    textAlign: 'center',
    marginBottom: '50px',
    marginTop: '5px'
  },

  exhibit: {
    fontWeight: '600',
    color: '#333',
    fontSize: '1.25rem',
    marginBottom: '15px'
  },

  text: {
    fontSize: '1rem',
    lineHeight: '1.75rem',
    color: '#777',
    marginBottom: '25px',
    fontWeight: '400'
  },

  notice: {
    lineHeight: '1.75rem',
    color: '#777',
    marginBottom: '25px',
    fontWeight: '400',
    fontSize: '.9rem',
    marginTop: '50px',
    textAlign: 'center',
    paddingLeft: '50px',
    paddingRight: '50px'
  },

  linked: {
    color: '#333',
    fontWeight: '600'
  }
}

const Terms = () => {
  let items

  if (isLogged()) {
    items = [
      {name: 'Rankings', link: 'rankings', type: 'item'},
      {name: 'Profile', link: 'profile', type: 'button'}
    ]
  } else {
    items = [
      {name: 'Rankings', link: 'rankings', type: 'item'},
      {name: 'Login', link: 'login', type: 'button'}
    ]
  }

  return (

      <Meta/>

Privacy Policy

Last updated: Jan 18, 2017

Our Policy

Welcome to the web site (the "Site") of Ritoplz. ("Ritoplz", "we", "us" and/or "our"). This Site is operated by Ritoplz and has been created to provide information about our company and services [Confirm description of your services] (together with the Site, the "Services") to our Service visitors ("you", "your"). This Privacy Policy sets forth Ritoplz's policy with respect to information including personally identifiable data ("Personal Data") and other information that is collected from visitors to the Site and Services.

Information We Collect

When you interact with us through the Services, we may collect Personal Data and other information from you, as further described below:

Personal Data That You Provide Through the Services

We collect Personal Data from you when you voluntarily provide such information, such as when you contact us with inquiries, respond to one of our surveys, register for access to the Services or use certain Services. Wherever Ritoplz collects Personal Data we make an effort to provide a link to this Privacy Policy.

By voluntarily providing us with Personal Data, you are consenting to our use of it in accordance with this Privacy Policy. If you provide Personal Data to the Services, you acknowledge and agree that such Personal Data may be transferred from your current location to the offices and servers of Ritoplz and the authorized third parties referred to herein located in the United States.

Our Use of Your Personal Data and Other Information

Ritoplz uses the Personal Data you provide in a manner that is consistent with this Privacy Policy. If you provide Personal Data for a certain reason, we may use the Personal Data in connection with the reason for which it was provided. For instance, if you contact us by email, we will use the Personal Data you provide to answer your question or resolve your problem. Also, if you provide Personal Data in order to obtain access to the Services, we will use your Personal Data to provide you with access to such services and to monitor your use of such services. Ritoplz and its subsidiaries and affiliates (the "Related Companies") may also use your Personal Data and other personally non-identifiable information collected through the Services to help us improve the content and functionality of the Services, to better understand our users and to improve the Services. Ritoplz and its affiliates may use this information to contact you in the future to tell you about services we believe will be of interest to you. If we do so, each marketing communication we send you will contain instructions permitting you to "opt-out" of receiving future marketing communications. In addition, if at any time you wish not to receive any future marketing communications or you wish to have your name deleted from our mailing lists, please contact us as indicated below.

If Ritoplz intends on using any Personal Data in any manner that is not consistent with this Privacy Policy, you will be informed of such anticipated use prior to or at the time at which the Personal Data is collected.

Our Disclosure of Your Personal Data and Other Information

Ritoplz is not in the business of selling your information. We consider this information to be a vital part of our relationship with you. There are, however, certain circumstances in which we may share your Personal Data with certain third parties without further notice to you, as set forth below:

Business Transfers:

As we develop our business, we might sell or buy businesses or assets. In the event of a corporate sale, merger, reorganization, dissolution or similar event, Personal Data may be part of the transferred assets.

Related Companies:

We may also share your Personal Data with our Related Companies for purposes consistent with this Privacy Policy.

Agents, Consultants and Related Third Parties:

Ritoplz, like many businesses, sometimes hires other companies to perform certain business-related functions. Examples of such functions include mailing information, maintaining databases and processing payments. When we employ another entity to perform a function of this nature, we only provide them with the information that they need to perform their specific function.

Your Choices

You can visit the Site without providing any Personal Data. If you choose not to provide any Personal Data, you may not be able to use certain Services.

Exclusions

This Privacy Policy does not apply to any Personal Data collected by Ritoplz other than Personal Data collected through the Services. This Privacy Policy shall not apply to any unsolicited information you provide to Ritoplz through the Services or through any other means. This includes, but is not limited to, information posted to any public areas of the Services, such as forums, any ideas for new products or modifications to existing products, and other unsolicited submissions (collectively, "Unsolicited Information"). All Unsolicited Information shall be deemed to be non-confidential and Ritoplz shall be free to reproduce, use, disclose, and distribute such Unsolicited Information to others without limitation or attribution.

Children

Ritoplz does not knowingly collect Personal Data from children under the age of 13. If you are under the age of 13, please do not submit any Personal Data through the Services. We encourage parents and legal guardians to monitor their children's Internet usage and to help enforce our Privacy Policy by instructing their children never to provide Personal Data on the Services without their permission. If you have reason to believe that a child under the age of 13 has provided Personal Data to Ritoplz through the Services, please contact us, and we will endeavor to delete that information from our databases.

Links to Other Web Sites

This Privacy Policy applies only to the Services. The Services may contain links to other web sites not operated or controlled by Ritoplz (the "Third Party Sites"). The policies and procedures we described here do not apply to the Third Party Sites. The links from the Services do not imply that Ritoplz endorses or has reviewed the Third Party Sites. We suggest contacting those sites directly for information on their privacy policies.

Security

Ritoplz takes reasonable steps to protect the Personal Data provided via the Services from loss, misuse, and unauthorized access, disclosure, alteration, or destruction. However, no Internet or email transmission is ever fully secure or error free. In particular, email sent to or from the Services may not be secure. Therefore, you should take special care in deciding what information you send to us via email. Please keep this in mind when disclosing any Personal Data to Ritoplz via the Internet.

Other Terms and Conditions

Your access to and use of the Services is subject to the Terms of Service.

Changes to Ritoplz's Privacy Policy

The Services and our business may change from time to time. As a result, at times it may be necessary for Ritoplz to make changes to this Privacy Policy. Ritoplz reserves the right to update or modify this Privacy Policy at any time and from time to time without prior notice. Please review this policy periodically, and especially before you provide any Personal Data. This Privacy Policy was last updated on the date indicated above. Your continued use of the Services after any changes or revisions to this Privacy Policy shall indicate your agreement with the terms of such revised Privacy Policy.

Contacting Us

To keep your Personal Data accurate, current, and complete, please contact us as specified below. We will take reasonable steps to update or correct Personal Data in our possession that you have previously submitted via the Services.

Please also feel free to contact us if you have any questions about Ritoplz's Privacy Policy or the information practices of the Services You may contact us as follows ritoplzteam@gmail.com

  )
}

export default Terms
<commit_msg>Upgrade privacy<commit_after>'use strict'

import React from 'react'
import Link from 'next/link'

import Meta from '../components/meta'
import Header from '../components/header'
import Footer from '../components/footer'
import { isLogged } from './../services/auth'

const Terms = () => {
  let items

  if (isLogged()) {
    items = [
      {name: 'Rankings', link: 'rankings', type: 'item'},
      {name: 'Profile', link: 'profile', type: 'button'}
    ]
  } else {
    items = [
      {name: 'Rankings', link: 'rankings', type: 'item'},
      {name: 'Login', link: 'login', type: 'button'}
    ]
  }

  return (

      <Meta/>

Privacy Policy

Last updated: Jan 18, 2017

Our Policy

Welcome to the web site (the "Site") of Ritoplz. ("Ritoplz", "we", "us" and/or "our"). This Site is operated by Ritoplz and has been created to provide information about our company and services [Confirm description of your services] (together with the Site, the "Services") to our Service visitors ("you", "your"). This Privacy Policy sets forth Ritoplz's policy with respect to information including personally identifiable data ("Personal Data") and other information that is collected from visitors to the Site and Services.

Information We Collect

When you interact with us through the Services, we may collect Personal Data and other information from you, as further described below:

Personal Data That You Provide Through the Services

We collect Personal Data from you when you voluntarily provide such information, such as when you contact us with inquiries, respond to one of our surveys, register for access to the Services or use certain Services. Wherever Ritoplz collects Personal Data we make an effort to provide a link to this Privacy Policy.

By voluntarily providing us with Personal Data, you are consenting to our use of it in accordance with this Privacy Policy. If you provide Personal Data to the Services, you acknowledge and agree that such Personal Data may be transferred from your current location to the offices and servers of Ritoplz and the authorized third parties referred to herein located in the United States.

Our Use of Your Personal Data and Other Information

Ritoplz uses the Personal Data you provide in a manner that is consistent with this Privacy Policy. If you provide Personal Data for a certain reason, we may use the Personal Data in connection with the reason for which it was provided. For instance, if you contact us by email, we will use the Personal Data you provide to answer your question or resolve your problem. Also, if you provide Personal Data in order to obtain access to the Services, we will use your Personal Data to provide you with access to such services and to monitor your use of such services. Ritoplz and its subsidiaries and affiliates (the "Related Companies") may also use your Personal Data and other personally non-identifiable information collected through the Services to help us improve the content and functionality of the Services, to better understand our users and to improve the Services. Ritoplz and its affiliates may use this information to contact you in the future to tell you about services we believe will be of interest to you. If we do so, each marketing communication we send you will contain instructions permitting you to "opt-out" of receiving future marketing communications. In addition, if at any time you wish not to receive any future marketing communications or you wish to have your name deleted from our mailing lists, please contact us as indicated below.

If Ritoplz intends on using any Personal Data in any manner that is not consistent with this Privacy Policy, you will be informed of such anticipated use prior to or at the time at which the Personal Data is collected.

Our Disclosure of Your Personal Data and Other Information

Ritoplz is not in the business of selling your information. We consider this information to be a vital part of our relationship with you. There are, however, certain circumstances in which we may share your Personal Data with certain third parties without further notice to you, as set forth below:

Business Transfers:

As we develop our business, we might sell or buy businesses or assets. In the event of a corporate sale, merger, reorganization, dissolution or similar event, Personal Data may be part of the transferred assets.

Related Companies:

We may also share your Personal Data with our Related Companies for purposes consistent with this Privacy Policy.

Agents, Consultants and Related Third Parties:

Ritoplz, like many businesses, sometimes hires other companies to perform certain business-related functions. Examples of such functions include mailing information, maintaining databases and processing payments. When we employ another entity to perform a function of this nature, we only provide them with the information that they need to perform their specific function.

Your Choices

You can visit the Site without providing any Personal Data. If you choose not to provide any Personal Data, you may not be able to use certain Services.

Exclusions

This Privacy Policy does not apply to any Personal Data collected by Ritoplz other than Personal Data collected through the Services. This Privacy Policy shall not apply to any unsolicited information you provide to Ritoplz through the Services or through any other means. This includes, but is not limited to, information posted to any public areas of the Services, such as forums, any ideas for new products or modifications to existing products, and other unsolicited submissions (collectively, "Unsolicited Information"). All Unsolicited Information shall be deemed to be non-confidential and Ritoplz shall be free to reproduce, use, disclose, and distribute such Unsolicited Information to others without limitation or attribution.

Children

Ritoplz does not knowingly collect Personal Data from children under the age of 13. If you are under the age of 13, please do not submit any Personal Data through the Services. We encourage parents and legal guardians to monitor their children's Internet usage and to help enforce our Privacy Policy by instructing their children never to provide Personal Data on the Services without their permission. If you have reason to believe that a child under the age of 13 has provided Personal Data to Ritoplz through the Services, please contact us, and we will endeavor to delete that information from our databases.

Links to Other Web Sites

This Privacy Policy applies only to the Services. The Services may contain links to other web sites not operated or controlled by Ritoplz (the "Third Party Sites"). The policies and procedures we described here do not apply to the Third Party Sites. The links from the Services do not imply that Ritoplz endorses or has reviewed the Third Party Sites. We suggest contacting those sites directly for information on their privacy policies.

Security

Ritoplz takes reasonable steps to protect the Personal Data provided via the Services from loss, misuse, and unauthorized access, disclosure, alteration, or destruction. However, no Internet or email transmission is ever fully secure or error free. In particular, email sent to or from the Services may not be secure. Therefore, you should take special care in deciding what information you send to us via email. Please keep this in mind when disclosing any Personal Data to Ritoplz via the Internet.

Other Terms and Conditions

Your access to and use of the Services is subject to the Terms of Service.

Changes to Ritoplz's Privacy Policy

The Services and our business may change from time to time. As a result, at times it may be necessary for Ritoplz to make changes to this Privacy Policy. Ritoplz reserves the right to update or modify this Privacy Policy at any time and from time to time without prior notice. Please review this policy periodically, and especially before you provide any Personal Data. This Privacy Policy was last updated on the date indicated above. Your continued use of the Services after any changes or revisions to this Privacy Policy shall indicate your agreement with the terms of such revised Privacy Policy.

Contacting Us

To keep your Personal Data accurate, current, and complete, please contact us as specified below. We will take reasonable steps to update or correct Personal Data in our possession that you have previously submitted via the Services.

Please also feel free to contact us if you have any questions about Ritoplz's Privacy Policy or the information practices of the Services You may contact us as follows ritoplzteam@gmail.com

  )
}

export default Terms
<|endoftext|>


<commit_before><commit_msg>add alerto phone call<commit_after><|endoftext|>


<commit_before>define(['js/data/Entity', 'flow'], function(Entity, flow) {

    var Image = Entity.inherit('sprd.entity.Image', {
        defaults: {
            name: null,
            size: null,
            type: null,
            lastModifiedDate: null,
            src: null,

            width: null,
            height: null
        },

        getDimension: function(callback) {
            var self = this;

            Image.getDimension(this.src, function(err, dimension) {
                if (!err && dimension) {
                    // set width and height
                    self.set(dimension);
                }

                callback(err, dimension);
            });
        }
    }, {
        getDimension: function(src, callback) {
            if (typeof window !== "undefined") {
                var img = new window.Image();
                img.onload = function(e) {
                    callback(null, {
                        width: img.width,
                        height: img.height
                    });
                };
                img.src = src;
            } else {
                callback("Cannot determinate dimension, window not defined");
            }
        },

        greyScale: function(img, shrinkFactor) {
            if (typeof document !== "undefined") {
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                canvas.width = img.width * (shrinkFactor || 1);
                canvas.height = img.height * (shrinkFactor || 1);

                var i, avg;
                var filtersSupported = "filter" in ctx;

                var opacity = 0.2;
                if (filtersSupported) {
                    ctx.filter = "grayscale(100%) opacity(" + (opacity * 100) + "%)";
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                } else {
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    for (i = 0; i < imgData.data.length; i += 4) {
                        avg = (imgData.data[i] + imgData.data[i + 1] + imgData.data[i + 2]) / 3;
                        imgData.data[i] = avg;
                        imgData.data[i + 1] = avg;
                        imgData.data[i + 2] = avg;
                    }

                    for (i = 3; i < imgData.data.length; i += 4) {
                        imgData.data[i] *= opacity;
                    }

                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.putImageData(imgData, 0, 0);
                }

                return canvas.toDataURL();
            } else {
                console.log("Global object document is not defined.");
            }

        },

        greyScaleImage: function(input, shrinkFactor, callback) {
            var factor = 1;
            if (typeof shrinkFactor === 'function') {
                callback = shrinkFactor;
            } else if (typeof shrinkFactor === 'number') {
                factor = shrinkFactor;
            }

            if (!callback) {
                return;
            }

            if (!input) {
                callback(new Error('No source supplied for greyscale conversion.'));
            }

            if (typeof window !== "undefined") {

                flow()
                    .seq('originalImg', function(cb) {
                        if (!(input instanceof window.Image)) {
                            var originalImg = new window.Image();
                            originalImg.onerror = cb;
                            originalImg.onload = function() {
                                cb(null, originalImg);
                            };

                            originalImg.src = input;
                        } else {
                            cb(null, input);
                        }
                    })
                    .seq('greyScaleImg', function(cb) {
                        var greyScale = new window.Image();
                        greyScale.onerror = cb;
                        greyScale.onload = function() {
                            cb(null, greyScale);
                        };

                        greyScale.src = Image.greyScale(this.vars.originalImg, factor);
                    })
                    .exec(function(err, results) {
                        if (!err) {
                            callback(null, results.greyScaleImg);
                        } else {
                            callback(err);
                        }
                    });
            }

            else {
                callback("Cannot create grey scale image, window not defined");
            }
        }
    });
    return Image;
});<commit_msg>[DEV-104842]  Moved greyscaling to own helper function.<commit_after>define(['js/data/Entity', 'flow'], function(Entity, flow) {

    var Image = Entity.inherit('sprd.entity.Image', {
        defaults: {
            name: null,
            size: null,
            type: null,
            lastModifiedDate: null,
            src: null,

            width: null,
            height: null
        },

        getDimension: function(callback) {
            var self = this;

            Image.getDimension(this.src, function(err, dimension) {
                if (!err && dimension) {
                    // set width and height
                    self.set(dimension);
                }

                callback(err, dimension);
            });
        }
    }, {
        getDimension: function(src, callback) {
            if (typeof window !== "undefined") {
                var img = new window.Image();
                img.onload = function(e) {
                    callback(null, {
                        width: img.width,
                        height: img.height
                    });
                };
                img.src = src;
            } else {
                callback("Cannot determinate dimension, window not defined");
            }
        }
    });
    return Image;
});<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var eventListener = require('eventlistener');

var PropTypes = React.PropTypes;

var ElementPan = React.createClass({
    displayName: 'ElementPan',

    propTypes: {
        className: PropTypes.string,
        onPanStart: PropTypes.func,
        onPan: PropTypes.func,
        onPanStop: PropTypes.func,
        startX: PropTypes.number,
        startY: PropTypes.number,
        width: PropTypes.number,
        height: PropTypes.number
    },

    getDefaultProps: function() {
        return {
            className: 'element-pan'
        };
    },

    getInitialState: function() {
        return {
            dragging: false
        };
    },

    onDragStart: function(e) {
        e.preventDefault();

        // We want to be able to pan around inside the container even when the
        // mouse is on the outside of the element (as long as the mouse button
        // is still being pressed) - this is why we're attaching to the window
        eventListener.add(window, 'mousemove', this.onDragMove);
        eventListener.add(window, 'touchmove', this.onDragMove);
        eventListener.add(window, 'mouseup', this.onDragStop);
        eventListener.add(window, 'touchend', this.onDragStop);

        // If we have multiple child nodes, use the scroll[Height/Width]
        // If we have no child-nodes, use bounds to find size of inner content
        var bounds, target = e.currentTarget || e.target;
        if (target.childNodes.length > 1) {
            bounds = { width: target.scrollWidth, height: target.scrollHeight };
        } else {
            bounds = e.target.getBoundingClientRect();
        }

        // Find start position of drag based on touch/mouse coordinates
        var startX = typeof e.clientX === 'undefined' ? e.changedTouches[0].clientX : e.clientX,
            startY = typeof e.clientY === 'undefined' ? e.changedTouches[0].clientY : e.clientY;

        var state = {
            dragging: true,

            elHeight: this.el.clientHeight,
            elWidth: this.el.clientWidth,

            startX: startX,
            startY: startY,

            scrollX: this.el.scrollLeft,
            scrollY: this.el.scrollTop,

            maxX: bounds.width,
            maxY: bounds.height
        };

        this.setState(state);

        if (this.props.onPanStart) {
            this.props.onPanStart(state);
        }
    },

    onDragMove: function(e) {
        if (!this.state.dragging) {
            return;
        }

        var x = typeof e.clientX === 'undefined' ? e.changedTouches[0].clientX : e.clientX,
            y = typeof e.clientY === 'undefined' ? e.changedTouches[0].clientY : e.clientY;

        // Letting the browser automatically stop on scrollHeight
        // gives weird bugs where some extra pixels are showing.
        // Substracting the height/width of the container from the
        // inner content seems to do the trick.
        this.el.scrollLeft = Math.min(
            this.state.maxX - this.state.elWidth,
            this.state.scrollX - (x - this.state.startX)
        );

        this.el.scrollTop = Math.min(
            this.state.maxY - this.state.elHeight,
            this.state.scrollY - (y - this.state.startY)
        );

        if (this.props.onPan) {
            this.props.onPan({ x: this.el.scrollLeft, y: this.el.scrollTop });
        }
    },

    onDragStop: function() {
        this.setState({ dragging: false });

        eventListener.remove(window, 'mousemove', this.onDragMove);
        eventListener.remove(window, 'touchmove', this.onDragMove);
        eventListener.remove(window, 'mouseup', this.onDragStop);
        eventListener.remove(window, 'touchend', this.onDragStop);

        if (this.props.onPanStop) {
            this.props.onPanStop({ x: this.el.scrollLeft, y: this.el.scrollTop });
        }
    },

    componentDidMount: function() {
        // Cached for faster lookup
        this.el = this.refs.container;

        // Old versions of React doesn't return the raw DOM node
        if (!(this.el instanceof window.Node)) {
            this.el = this.el.getDOMNode();
        }

        if (this.props.startX) {
            this.el.scrollLeft = this.props.startX;
        }

        if (this.props.startY) {
            this.el.scrollTop = this.props.startY;
        }
    },

    getContainerStyles: function() {
        var style = {
            overflow: 'hidden',
            cursor: 'move'
        }

        if (this.props.width) {
            style.width = this.props.width;
        }

        if (this.props.height) {
            style.height = this.props.height;
        }

        return style;
    },

    render: function() {
        return (
            React.DOM.div({
                ref: 'container',
                className: this.props.className,
                style: this.getContainerStyles(),
                onMouseDown: this.onDragStart,
                onTouchStart: this.onDragStart
            }, this.props.children)
        );
    }
});

module.exports = ElementPan;
<commit_msg>commenting getDomNode() call temporarily<commit_after>'use strict';

var React = require('react');
var eventListener = require('eventlistener');

var PropTypes = React.PropTypes;

var ElementPan = React.createClass({
    displayName: 'ElementPan',

    propTypes: {
        className: PropTypes.string,
        onPanStart: PropTypes.func,
        onPan: PropTypes.func,
        onPanStop: PropTypes.func,
        startX: PropTypes.number,
        startY: PropTypes.number,
        width: PropTypes.number,
        height: PropTypes.number
    },

    getDefaultProps: function() {
        return {
            className: 'element-pan'
        };
    },

    getInitialState: function() {
        return {
            dragging: false
        };
    },

    onDragStart: function(e) {
        e.preventDefault();

        // We want to be able to pan around inside the container even when the
        // mouse is on the outside of the element (as long as the mouse button
        // is still being pressed) - this is why we're attaching to the window
        eventListener.add(window, 'mousemove', this.onDragMove);
        eventListener.add(window, 'touchmove', this.onDragMove);
        eventListener.add(window, 'mouseup', this.onDragStop);
        eventListener.add(window, 'touchend', this.onDragStop);

        // If we have multiple child nodes, use the scroll[Height/Width]
        // If we have no child-nodes, use bounds to find size of inner content
        var bounds, target = e.currentTarget || e.target;
        if (target.childNodes.length > 1) {
            bounds = { width: target.scrollWidth, height: target.scrollHeight };
        } else {
            bounds = e.target.getBoundingClientRect();
        }

        // Find start position of drag based on touch/mouse coordinates
        var startX = typeof e.clientX === 'undefined' ? e.changedTouches[0].clientX : e.clientX,
            startY = typeof e.clientY === 'undefined' ? e.changedTouches[0].clientY : e.clientY;

        var state = {
            dragging: true,

            elHeight: this.el.clientHeight,
            elWidth: this.el.clientWidth,

            startX: startX,
            startY: startY,

            scrollX: this.el.scrollLeft,
            scrollY: this.el.scrollTop,

            maxX: bounds.width,
            maxY: bounds.height
        };

        this.setState(state);

        if (this.props.onPanStart) {
            this.props.onPanStart(state);
        }
    },

    onDragMove: function(e) {
        if (!this.state.dragging) {
            return;
        }

        var x = typeof e.clientX === 'undefined' ? e.changedTouches[0].clientX : e.clientX,
            y = typeof e.clientY === 'undefined' ? e.changedTouches[0].clientY : e.clientY;

        // Letting the browser automatically stop on scrollHeight
        // gives weird bugs where some extra pixels are showing.
        // Substracting the height/width of the container from the
        // inner content seems to do the trick.
        this.el.scrollLeft = Math.min(
            this.state.maxX - this.state.elWidth,
            this.state.scrollX - (x - this.state.startX)
        );

        this.el.scrollTop = Math.min(
            this.state.maxY - this.state.elHeight,
            this.state.scrollY - (y - this.state.startY)
        );

        if (this.props.onPan) {
            this.props.onPan({ x: this.el.scrollLeft, y: this.el.scrollTop });
        }
    },

    onDragStop: function() {
        this.setState({ dragging: false });

        eventListener.remove(window, 'mousemove', this.onDragMove);
        eventListener.remove(window, 'touchmove', this.onDragMove);
        eventListener.remove(window, 'mouseup', this.onDragStop);
        eventListener.remove(window, 'touchend', this.onDragStop);

        if (this.props.onPanStop) {
            this.props.onPanStop({ x: this.el.scrollLeft, y: this.el.scrollTop });
        }
    },

    componentDidMount: function() {
        // Cached for faster lookup
        this.el = this.refs.container;

        // Old versions of React doesn't return the raw DOM node
       // if (!(this.el instanceof window.Node)) {
       //     this.el = this.el.getDOMNode();
       // }

        if (this.props.startX) {
            this.el.scrollLeft = this.props.startX;
        }

        if (this.props.startY) {
            this.el.scrollTop = this.props.startY;
        }
    },

    getContainerStyles: function() {
        var style = {
            overflow: 'hidden',
            cursor: 'move'
        }

        if (this.props.width) {
            style.width = this.props.width;
        }

        if (this.props.height) {
            style.height = this.props.height;
        }

        return style;
    },

    render: function() {
        return (
            React.DOM.div({
                ref: 'container',
                className: this.props.className,
                style: this.getContainerStyles(),
                onMouseDown: this.onDragStart,
                onTouchStart: this.onDragStart
            }, this.props.children)
        );
    }
});

module.exports = ElementPan;
<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(
            ["lodash/lang/clone", "lodash/lang/isFunction", "lodash/object/assign",
             "lodash/object/pick", "lodash/object/omit", "lodash/collection/map",
             "lodash/collection/forEach", "lodash/collection/forEachRight",
             "lodash/collection/includes", "lodash/collection/reduce",
             "lodash/collection/reject", "lodash/array/slice", "lodash/array/first",
             "lodash/array/rest", "lodash/array/without", "lodash/array/flatten"],
            factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(
            require("lodash/lang/clone"),
            require("lodash/lang/isFunction"),
            require("lodash/object/assign"),
            require("lodash/object/pick"),
            require("lodash/object/omit"),
            require("lodash/collection/map"),
            require("lodash/collection/forEach"),
            require("lodash/collection/forEachRight"),
            require("lodash/collection/includes"),
            require("lodash/collection/reduce"),
            require("lodash/collection/reject"),
            require("lodash/array/slice"),
            require("lodash/array/first"),
            require("lodash/array/rest"),
            require("lodash/array/without"),
            require("lodash/array/flatten")
        );
    } else {
        // Browser globals (root is window)
        if (typeof _ == "undefined") throw "_ not defined in global namespace";
        root.encapsulate = factory(
            _.clone, _.isFunction, _.assign, _.pick, _.omit, _.map, _.forEach,
            _.forEachRight, _.includes, _.reduce, _.reject, _.slice, _.first,
            _.rest, _.without, _.flatten
        );
    }
}(this, function (clone, isFunction, assign, pick, omit, map, forEach, forEachRight,
                  includes, reduce, reject, slice, first, rest, without, flatten) {
    var instantiatorCount = 0,
        instanceCount = 0;

    /*
     Begin C3 Linearization implementation.

     This version of C3 Linearization is based on the OCaml version implemented
     at https://xivilization.net/~marek/blog/2014/12/08/implementing-c3-linearization/

     The only difference here is that, similar to the C3 Implementation used in
     Ring.js (http://ringjs.neoname.eu/), the linearize function will attempt to
     use a pre-calculated linearization defined on a given item to be linearized
     in order to allow us to avoid re-calculating the linearization of items
     that have already been linearized.
     */
    /**
     *
     * @param {*} value
     * @param {Array[Array]} lists
     * @returns {Array[Array]}
     */
    function remove(value, lists) {
        return reject(
            map(lists, function (list) {
                return without(list, value);
            }),
            {
                length: 0
            });
    }

    function headNotInTails() {
        var heads = map(arguments, first),
            tails = flatten(map(arguments, rest));
        return reduce(heads, function (selectedHead, head) {
            if (selectedHead !== null) return selectedHead;
            if (includes(tails, head)) return null;
            return head;
        }, null);
    }

    function mergeLinearizations() {
        var args = slice(arguments),
            head = headNotInTails.apply(this, args),
            filteredArgs = head ? remove(head, args) : null;
        if (head) {
            if (filteredArgs.length == 0) return [head];
            return [head].concat(mergeLinearizations.apply(this, filteredArgs));
        }
        throw "No linearization possible";
    }

    function linearize(instantiator) {
        if (instantiator.__bases__.length == 0) return [instantiator];
        else if (instantiator.__mro__.length > 0) return instantiator.__mro__;
        return [instantiator].concat(
            mergeLinearizations.apply(
                this,
                map(instantiator.__bases__, linearize)
                    .concat([instantiator.__bases__])));
    }
    /*
     End C3 Linearization implementation
     */

    /**
     *
     * @param {Array} memberGenerators
     * @param {Array} [bases=[]]
     * @returns {Function}
     */
    function generateInstantiator(memberGenerators, bases) {
        var bases = bases || [],
            mro = [],
            instantiator = function () {
                var args = slice(arguments),
                    instance = function () {
                        if (isFunction(instance.__call__)) return instance.__call__.apply(instance, arguments);
                        throw "NotImplemented";
                    };
                Object.defineProperties(instance, {
                    __id__: {
                        value: "encapsulateInstance" + instanceCount++
                    },
                    isEncapsulateInstance: {
                        value: true
                    },
                    instanceOf: {
                        value: function (target) {
                            return includes(instantiator.__mro__, target);
                        }
                    }
                });
                // Bind Members
                forEachRight(instantiator.__mro__, function (instantiator) {
                    var members = reduce(
                            instantiator.__members__,
                            function (members, membersGenerator) {
                                return assign(members, membersGenerator());
                            },
                            {}),
                        functionMembers = pick(members, isFunction),
                        nonFunctionMembers = omit(members, isFunction);
                    assign(instance, nonFunctionMembers);
                    forEach(functionMembers, function (functionMember, functionName) {
                        if (isFunction(instance[functionName])) {
                            functionMember.super = instance[functionName].bind(instance);
                        }
                        instance[functionName] = functionMember;
                    });
                });
                // Call constructor
                if(typeof instance.__init__ == "function")
                    instance.__init__.apply(instance, args);
                return instance;
        };

        Object.defineProperties(instantiator, {
            __id__: {
                value: "encapsulateInstantiator" + instantiatorCount++
            },
            __bases__: {
                get: function () {
                    return slice(bases);
                }
            },
            __members__: {
                get: function () {
                    return slice(memberGenerators);
                }
            },
            __mro__: {
                get: function () {
                    return slice(mro);
                }
            },
            isEncapsulateInstantiator: {
                value: true
            },
            extends: {
                value: function () {
                    var args = slice(arguments);
                    forEach(args, function (base) {
                        if (!base.isEncapsulateInstantiator)
                            throw base + " is not an Encapsulate Instantiator";
                    });
                    return generateInstantiator(memberGenerators, args);
                }
            }
        });
        mro.push.apply(mro, linearize(instantiator));
        return instantiator;
    }

    function wrapMembersOrMembersGenerator(membersOrMembersGenerator) {
        if (typeof membersOrMembersGenerator == "function" && !membersOrMembersGenerator.isEncapsulateInstantiator)
            return membersOrMembersGenerator;
        else if (typeof membersOrMembersGenerator == "object") return function () {
            return clone(membersOrMembersGenerator, true);
        };
        throw "Unsupported argument type";
    }

    /**
     *
     * @param membersOrMembersGeneratorOrInstantiator
     * @returns {Function}
     */
    function encapsulate(membersOrMembersGeneratorOrInstantiator) {
        var args = slice(arguments);

        function parentAccumulator(membersOrMembersGeneratorOrInstantiator) {
            var arguments = slice(arguments);
            if (membersOrMembersGeneratorOrInstantiator.isEncapsulateInstantiator) {
                args.push.apply(args, arguments);
                return parentAccumulator;
            } else {
                var instantiator = encapsulate.apply(this, arguments);
                return instantiator.extends.apply(instantiator, args);
            }
        }

        if (typeof membersOrMembersGeneratorOrInstantiator == "undefined")
            throw "encapsulate requires parameters!";

        if (membersOrMembersGeneratorOrInstantiator.isEncapsulateInstantiator) {
            return parentAccumulator;
        } else return generateInstantiator(map(args, wrapMembersOrMembersGenerator));
    }

    return encapsulate;
}));

<commit_msg>Tweaked implementation to allow instanceOf to be enhanced to support checking of Traits in addition to Instantiators. Function traits are now called with this bound to the new instance and the arguments supplied to the Instantiator to produce the object. Instantiator.__members__ renamed to Instantiator.__traits__. .<commit_after>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(
            ["lodash/lang/clone", "lodash/lang/isFunction", "lodash/lang/isPlainObject", "lodash/object/assign",
             "lodash/object/pick", "lodash/object/omit", "lodash/collection/map",
             "lodash/collection/forEach", "lodash/collection/forEachRight",
             "lodash/collection/includes", "lodash/collection/reduce",
             "lodash/collection/reject", "lodash/collection/some", "lodash/array/slice", "lodash/array/first",
             "lodash/array/rest", "lodash/array/without", "lodash/array/flatten"],
            factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(
            require("lodash/lang/clone"),
            require("lodash/lang/isFunction"),
            require("lodash/lang/isPlainObject"),
            require("lodash/object/assign"),
            require("lodash/object/pick"),
            require("lodash/object/omit"),
            require("lodash/collection/map"),
            require("lodash/collection/forEach"),
            require("lodash/collection/forEachRight"),
            require("lodash/collection/includes"),
            require("lodash/collection/reduce"),
            require("lodash/collection/reject"),
            require("lodash/collection/some"),
            require("lodash/array/slice"),
            require("lodash/array/first"),
            require("lodash/array/rest"),
            require("lodash/array/without"),
            require("lodash/array/flatten")
        );
    } else {
        // Browser globals (root is window)
        if (typeof _ == "undefined") throw "_ not defined in global namespace";
        root.encapsulate = factory(
            _.clone, _.isFunction, _.isPlainObject, _.assign, _.pick, _.omit, _.map, _.forEach,
            _.forEachRight, _.includes, _.reduce, _.reject, _.some, _.slice, _.first,
            _.rest, _.without, _.flatten
        );
    }
}(this, function (clone, isFunction, isPlainObject, assign, pick, omit, map, forEach, forEachRight,
                  includes, reduce, reject, some, slice, first, rest, without, flatten) {
    var instantiatorCount = 0,
        instanceCount = 0;

    /*
     Begin C3 Linearization implementation.

     This version of C3 Linearization is based on the OCaml version implemented
     at https://xivilization.net/~marek/blog/2014/12/08/implementing-c3-linearization/

     The only difference here is that, similar to the C3 Implementation used in
     Ring.js (http://ringjs.neoname.eu/), the linearize function will attempt to
     use a pre-calculated linearization defined on a given item to be linearized
     in order to allow us to avoid re-calculating the linearization of items
     that have already been linearized.
     */
    /**
     *
     * @param {*} value
     * @param {Array[Array]} lists
     * @returns {Array[Array]}
     */
    function remove(value, lists) {
        return reject(
            map(lists, function (list) {
                return without(list, value);
            }),
            {
                length: 0
            });
    }

    function headNotInTails() {
        var heads = map(arguments, first),
            tails = flatten(map(arguments, rest));
        return reduce(heads, function (selectedHead, head) {
            if (selectedHead !== null) return selectedHead;
            if (includes(tails, head)) return null;
            return head;
        }, null);
    }

    function mergeLinearizations() {
        var args = slice(arguments),
            head = headNotInTails.apply(this, args),
            filteredArgs = head ? remove(head, args) : null;
        if (head) {
            if (filteredArgs.length == 0) return [head];
            return [head].concat(mergeLinearizations.apply(this, filteredArgs));
        }
        throw "No linearization possible";
    }

    function linearize(instantiator) {
        if (instantiator.__bases__.length == 0) return [instantiator];
        else if (instantiator.__mro__.length > 0) return instantiator.__mro__;
        return [instantiator].concat(
            mergeLinearizations.apply(
                this,
                map(instantiator.__bases__, linearize)
                    .concat([instantiator.__bases__])));
    }
    /*
     End C3 Linearization implementation
     */

    /**
     *
     * @param {Array} traits
     * @param {Array} [bases=[]]
     * @returns {Function}
     */
    function generateInstantiator(traits, bases) {
        var bases = bases || [],
            mro = [],
            instantiator = function () {
                var args = slice(arguments),
                    instance = function () {
                        if (isFunction(instance.__call__)) return instance.__call__.apply(instance, arguments);
                        throw "NotImplemented";
                    };
                Object.defineProperties(instance, {
                    __id__: {
                        value: "encapsulateInstance" + instanceCount++
                    },
                    isEncapsulateInstance: {
                        value: true
                    },
                    instanceOf: {
                        value: function (traitOrInstantiator) {
                            if (traitOrInstantiator.isEncapsulateInstantiator) return includes(instantiator.__mro__, traitOrInstantiator);
                            else if (isFunction(traitOrInstantiator) || isPlainObject(isPlainObject)) {
                                //TODO: Implement instanceOf checking for Traits
                            }
                            throw "Unsupported argument type. Argument must be a Plain Object, Function or Encapsulate Instantiator";
                        }
                    }
                });
                // Bind Members
                forEachRight(instantiator.__mro__, function (instantiator) {
                    var members = reduce(
                            instantiator.__traits__,
                            function (members, trait) {
                                if (isFunction(trait)) return assign(members, trait.apply(instance, args));
                                if (isPlainObject(trait)) return assign(members, clone(trait, true));
                                throw "Traits must be either Plain Objects or Functions";
                            },
                            {}),
                        functionMembers = pick(members, isFunction),
                        nonFunctionMembers = omit(members, isFunction);
                    assign(instance, nonFunctionMembers);
                    forEach(functionMembers, function (functionMember, functionName) {
                        if (isFunction(instance[functionName])) {
                            functionMember.super = instance[functionName].bind(instance);
                        }
                        instance[functionName] = functionMember;
                    });
                });
                // Call constructor
                if(typeof instance.__init__ == "function")
                    instance.__init__.apply(instance, args);
                return instance;
        };

        Object.defineProperties(instantiator, {
            __id__: {
                value: "encapsulateInstantiator" + instantiatorCount++
            },
            __bases__: {
                get: function () {
                    return slice(bases);
                }
            },
            __traits__: {
                get: function () {
                    return slice(traits);
                }
            },
            __mro__: {
                get: function () {
                    return slice(mro);
                }
            },
            isEncapsulateInstantiator: {
                value: true
            },
            extends: {
                value: function () {
                    var args = slice(arguments);
                    if (some(args, function (arg) { return !arg.isEncapsulateInstantiator; })) {
                        throw "Unsupported argument type. Arguments must be Encapsulate Instantiator";
                    }
                    return generateInstantiator(traits, args);
                }
            }
        });
        mro.push.apply(mro, linearize(instantiator));
        return instantiator;
    }

    /**
     *
     * @param {Object|Function} traitOrInstantiator
     * @returns {Function}
     */
    function encapsulate(traitOrInstantiator) {
        var args = slice(arguments);

        function parentAccumulator(traitOrInstantiator) {
            var arguments = slice(arguments);
            if (traitOrInstantiator.isEncapsulateInstantiator) {
                args.push.apply(args, arguments);
                //TODO: This needs to return a new parentAccumulator in order to make this a non-mutating operation
                return parentAccumulator;
            } else {
                var instantiator = encapsulate.apply(this, arguments);
                return instantiator.extends.apply(instantiator, args);
            }
        }

        if (typeof traitOrInstantiator == "undefined")
            throw "encapsulate requires parameters!";
        else if (some(args, function (arg) { return !isFunction(arg) && !isPlainObject(arg); })) {
            throw "Unsupported argument type. Arguments must be either Plain Objects or Functions";
        }

        if (traitOrInstantiator.isEncapsulateInstantiator) {
            return parentAccumulator;
        } else return generateInstantiator(args);
    }

    return encapsulate;
}));

<|endoftext|>


<commit_before>
var Color = {
    White: 0,
    Silver: 1,
    Gray: 2,
    Black: 3,
    Red: 4,
    Maroon: 5,
    Yellow: 6,
    Olive: 7,
    Lime: 8,
    Green: 9,
    Aqua: 10,
    Teal: 11,
    Blue: 12,
    Navy: 13,
    Fuchsia: 14,
    Purple: 15
};

var Options = {
    None: 0x0000,
    Capitalized: 0x0001,
    DefiniteArticles: 0x0002,
    IfNotLast: 0x0040,
    Highlighted: 0x0800
};

Array.prototype.add = function(array) {

    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        this[i] += array[i];
    }
    return this;
};

Array.prototype.angle = function(other) {

    var x1 = this[0], y1 = this[1], z1 = this[2],
        x2 = other[0], y2 = other[1], z2 = other[2];
    return Math.acos((x1 * x2 + y1 * y2 + z1 * z2) /
                     (Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1) *
                      Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2)));
};

Array.prototype.append = function(value) {

    if (value instanceof Array) {
        for (var i = 0, l = value.length; i < l; i++) {
            this.push(value[i]);
        }
    } else {
        return this.push(value);
    }
};

Array.prototype.clear = function() {

    return this.splice(0, this.length);
};

Array.prototype.clone = function() {

    return this.slice(0);
};

Array.prototype.contains = function(element) {

    return this.indexOf(element) > -1;
};

Array.prototype.containsAny = function(array) {

    return this.findFirstAmong(array) !== null;
};

Array.prototype.equals = function(array) {

    if (this.length !== array.length) {
        return false;
    }
    for (var i = 0; i < this.length; i++) {
        if (this[i] !== array[i]) {
            return false;
        }
    }
    return true;
};

Array.prototype.findFirstAmong = function(array) {

    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < array.length; j++) {
            if (this[i] === array[j]) {
                return this[i];
            }
        }
    }
    return null;
};

Array.prototype.first = function() {

    return this[0];
};

Array.prototype.firstItemIsPlural = function() {

    if (this.length > 0) {
        if (this[0].flags.split("|").indexOf("ImpliedPlural") > -1) {
            return true;
        } else {
            for (var i = 1; i < this.length; i++) {
                if (this[i].name === this[0].name) {
                    return true;
                }
            }
        }
    }
    return false;
};

Array.prototype.insert = function(element) {

    if (!this.contains(element)) {
        this.push(element);
    }
};

Array.prototype.isEmpty = function() {

    return this.length === 0;
};

Array.prototype.joinFancy = function(options) {

    return Util.joinPtrList(this, options);
};

Array.prototype.last = function() {

    return this[this.length - 1];
};

Array.prototype.mid = function(begin, end) {

    end = (end === undefined ? this.length : end);
    return this.slice(begin, end - begin);
};

Array.prototype.minus = function(array) {

    var result = [];
    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        result[i] = this[i] - array[i];
    }
    return result;
};

Array.prototype.mul = function(scalar) {

    var result = [];
    for (var i = 0, length = this.length; i < length; i++) {
        result[i] = scalar * this[i];
    }
    return result;
};

Array.prototype.named = function(name, room) {

    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.name === name) {
            return element;
        }
    }
    return undefined;
};

Array.prototype.normalized = function() {

    var l = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
    var result = [];
    if (l > 0) {
        return [100 * this[0] / l, 100 * this[1] / l, 100 * this[2] / l];
    } else {
        return [0, 0, 0];
    }
};

Array.prototype.plus = function(array) {

    var result = [];
    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        result[i] = this[i] + array[i];
    }
    return result;
};

Array.prototype.prepend = function(value) {

    if (value instanceof Array) {
        var args = [0, 0].concat(value);
        this.splice.apply(this, args);
    } else {
        this.splice(0, 0, value);
        return value;
    }
};

Array.prototype.randomElement = function() {

    return this[randomInt(0, this.length)];
};

Array.prototype.removeAll = function(value) {

    var numRemovals = 0;
    while (this.removeOne(value)) {
        numRemovals++;
    }
    return numRemovals;
};

Array.prototype.removeAt = function(index) {

    this.splice(index, 1);
};

Array.prototype.removeFirst = function() {

    this.splice(0, 1);
};

Array.prototype.removeLast = function() {

    this.splice(this.length - 1, 1);
};

Array.prototype.removeOne = function(value) {

    var index = this.indexOf(value);
    if (index !== -1) {
        this.splice(index, 1);
        return true;
    }
    return false;
};

Array.prototype.send = function(message) {

    for (var i = 0, length = this.length; i < length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.send) {
            element.send(message);
        }
    }
};

Array.prototype.takeFirst = function() {

    return this.splice(0, 1)[0];
};

Array.prototype.takeLast = function() {

    return this.splice(this.length - 1, 1)[0];
};

Array.prototype.total = function() {

    var sum = 0;
    for (var i = 0, length = this.length; i < length; i++) {
        sum += this[i];
    }
    return sum;
};

Array.prototype.vectorLength = function() {

    return Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
}

Array.prototype.withId = function(id) {

    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.id === id) {
            return element;
        }
    }
    return undefined;
};

Array.prototype.withoutId = function(id) {

    var result = [];
    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.id !== id) {
            result.push(element);
        }
    }
    return result;
};

Object.defineProperty(Object.prototype, "clone", {
    "value": function() {
        var clone = {};
        for (var key in this) {
            if (this.hasOwnProperty(key)) {
                var value = this[key];
                if (value instanceof Object) {
                    value = value.clone();
                }
                clone[key] = value;
            }
        }
        return clone;
    },
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "contains", {
    "value": Object.prototype.hasOwnProperty,
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "isEmpty", {
    "value": function() { for (var key in this) { return false; } return true; },
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "keys", {
    "value": function() { return Object.keys(this) },
    "configurable": true,
    "writable": true
});

String.prototype.arg = function() {

    var result = this;

    var argNum;
    for (var i = 0; i < 10 && (argNum === undefined || argNum < arguments.length); i++) {
        var substr = "%" + i;
        var index = result.indexOf(substr);
        if (index > -1) {
            if (argNum === undefined) {
                argNum = 0;
            }

            while (index > -1) {
                result = result.replace(substr, arguments[argNum]);
                index = result.indexOf(substr, index);
            }
        }

        if (argNum !== undefined) {
            argNum++;
        }
    }

    return result;
};

String.prototype.capitalized = function() {

    return Util.capitalize(this);
};

String.prototype.colorized = function(color) {

    return Util.colorize(this, color);
};

String.prototype.contains = function(string) {

    return this.indexOf(string) > -1;
};

String.prototype.endsWith = function(string) {

    return this.substr(this.length - string.length) === string;
};

String.prototype.highlighted = function() {

    return Util.highlight(this);
};

String.prototype.isEmpty = function() {

    return this.length === 0;
};

String.prototype.left = function(n) {

    return this.substr(0, n);
};

String.prototype.leftJustified = function(n, fill) {

    fill = fill || " ";
    var padding = "";
    for (var i = n - this.length; i > 0; i--) {
        padding += fill;
    }
    return this + padding;
};

String.prototype.mid = function(begin, end) {

    return this.substr(begin, end);
};

String.prototype.replaceAll = function(before, after) {

    var result = this;
    while (result.contains(before)) {
        result = result.replace(before, after);
    }
    return result;
};

String.prototype.right = function(n) {

    return this.substr(n);
};

String.prototype.rightJustified = function(n, fill) {

    fill = fill || " ";
    var padding = "";
    for (var i = n - this.length; i > 0; i--) {
        padding += fill;
    }
    return padding + this;
};

String.prototype.section = function(separator, start, end) {

    var parts = this.split(separator).slice(start, end);
    return parts.join(separator);
};

String.prototype.startsWith = function(string) {

    return this.substr(0, string.length) === string;
};

String.prototype.toDouble = function() {

    var value = parseFloat(this);
    if (isNaN(value)) {
        value = 0.0;
    }
    return value;
};

String.prototype.toInt = function() {

    var value = parseInt(this, 10);
    if (isNaN(value)) {
        value = 0;
    }
    return value;
};

String.prototype.toLower = function() {

    return this.toLowerCase();
};

String.prototype.toUpper = function() {

    return this.toUpperCase();
};

String.prototype.trimmed = function() {

    return this.replace(/^\s+|\s+$/g, "");
};

Util.randomAlternative = function() {

    return arguments[Util.randomInt(0, arguments.length)];
}

function $(identifier) {

    var split = identifier.split(":");
    return Realm.getObject(Util.capitalize(split[0]), parseInt(split[1], 10));
}

function byChance(n, p) {

    return Util.randomInt(0, p) < n;
}

function min(a, b) {

    return a < b ? a : b;
}

function max(a, b) {

    return a > b ? a : b;
}

function randomInt(min, max) {

    return Util.randomInt(min, max);
}
<commit_msg>Implement console.log() and friends in JS.<commit_after>
var Color = {
    White: 0,
    Silver: 1,
    Gray: 2,
    Black: 3,
    Red: 4,
    Maroon: 5,
    Yellow: 6,
    Olive: 7,
    Lime: 8,
    Green: 9,
    Aqua: 10,
    Teal: 11,
    Blue: 12,
    Navy: 13,
    Fuchsia: 14,
    Purple: 15
};

var Options = {
    None: 0x0000,
    Capitalized: 0x0001,
    DefiniteArticles: 0x0002,
    IfNotLast: 0x0040,
    Highlighted: 0x0800
};

Array.prototype.add = function(array) {

    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        this[i] += array[i];
    }
    return this;
};

Array.prototype.angle = function(other) {

    var x1 = this[0], y1 = this[1], z1 = this[2],
        x2 = other[0], y2 = other[1], z2 = other[2];
    return Math.acos((x1 * x2 + y1 * y2 + z1 * z2) /
                     (Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1) *
                      Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2)));
};

Array.prototype.append = function(value) {

    if (value instanceof Array) {
        for (var i = 0, l = value.length; i < l; i++) {
            this.push(value[i]);
        }
    } else {
        return this.push(value);
    }
};

Array.prototype.clear = function() {

    return this.splice(0, this.length);
};

Array.prototype.clone = function() {

    return this.slice(0);
};

Array.prototype.contains = function(element) {

    return this.indexOf(element) > -1;
};

Array.prototype.containsAny = function(array) {

    return this.findFirstAmong(array) !== null;
};

Array.prototype.equals = function(array) {

    if (this.length !== array.length) {
        return false;
    }
    for (var i = 0; i < this.length; i++) {
        if (this[i] !== array[i]) {
            return false;
        }
    }
    return true;
};

Array.prototype.findFirstAmong = function(array) {

    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < array.length; j++) {
            if (this[i] === array[j]) {
                return this[i];
            }
        }
    }
    return null;
};

Array.prototype.first = function() {

    return this[0];
};

Array.prototype.firstItemIsPlural = function() {

    if (this.length > 0) {
        if (this[0].flags.split("|").indexOf("ImpliedPlural") > -1) {
            return true;
        } else {
            for (var i = 1; i < this.length; i++) {
                if (this[i].name === this[0].name) {
                    return true;
                }
            }
        }
    }
    return false;
};

Array.prototype.insert = function(element) {

    if (!this.contains(element)) {
        this.push(element);
    }
};

Array.prototype.isEmpty = function() {

    return this.length === 0;
};

Array.prototype.joinFancy = function(options) {

    return Util.joinPtrList(this, options);
};

Array.prototype.last = function() {

    return this[this.length - 1];
};

Array.prototype.mid = function(begin, end) {

    end = (end === undefined ? this.length : end);
    return this.slice(begin, end - begin);
};

Array.prototype.minus = function(array) {

    var result = [];
    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        result[i] = this[i] - array[i];
    }
    return result;
};

Array.prototype.mul = function(scalar) {

    var result = [];
    for (var i = 0, length = this.length; i < length; i++) {
        result[i] = scalar * this[i];
    }
    return result;
};

Array.prototype.named = function(name, room) {

    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.name === name) {
            return element;
        }
    }
    return undefined;
};

Array.prototype.normalized = function() {

    var l = Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
    var result = [];
    if (l > 0) {
        return [100 * this[0] / l, 100 * this[1] / l, 100 * this[2] / l];
    } else {
        return [0, 0, 0];
    }
};

Array.prototype.plus = function(array) {

    var result = [];
    for (var i = 0, length = min(this.length, array.length); i < length; i++) {
        result[i] = this[i] + array[i];
    }
    return result;
};

Array.prototype.prepend = function(value) {

    if (value instanceof Array) {
        var args = [0, 0].concat(value);
        this.splice.apply(this, args);
    } else {
        this.splice(0, 0, value);
        return value;
    }
};

Array.prototype.randomElement = function() {

    return this[randomInt(0, this.length)];
};

Array.prototype.removeAll = function(value) {

    var numRemovals = 0;
    while (this.removeOne(value)) {
        numRemovals++;
    }
    return numRemovals;
};

Array.prototype.removeAt = function(index) {

    this.splice(index, 1);
};

Array.prototype.removeFirst = function() {

    this.splice(0, 1);
};

Array.prototype.removeLast = function() {

    this.splice(this.length - 1, 1);
};

Array.prototype.removeOne = function(value) {

    var index = this.indexOf(value);
    if (index !== -1) {
        this.splice(index, 1);
        return true;
    }
    return false;
};

Array.prototype.send = function(message) {

    for (var i = 0, length = this.length; i < length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.send) {
            element.send(message);
        }
    }
};

Array.prototype.takeFirst = function() {

    return this.splice(0, 1)[0];
};

Array.prototype.takeLast = function() {

    return this.splice(this.length - 1, 1)[0];
};

Array.prototype.total = function() {

    var sum = 0;
    for (var i = 0, length = this.length; i < length; i++) {
        sum += this[i];
    }
    return sum;
};

Array.prototype.vectorLength = function() {

    return Math.sqrt(this[0] * this[0] + this[1] * this[1] + this[2] * this[2]);
}

Array.prototype.withId = function(id) {

    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.id === id) {
            return element;
        }
    }
    return undefined;
};

Array.prototype.withoutId = function(id) {

    var result = [];
    for (var i = 0; i < this.length; i++) {
        var element = this[i];
        if (element && typeof element === "object" && element.id !== id) {
            result.push(element);
        }
    }
    return result;
};

Object.defineProperty(Object.prototype, "clone", {
    "value": function() {
        var clone = {};
        for (var key in this) {
            if (this.hasOwnProperty(key)) {
                var value = this[key];
                if (value instanceof Object) {
                    value = value.clone();
                }
                clone[key] = value;
            }
        }
        return clone;
    },
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "contains", {
    "value": Object.prototype.hasOwnProperty,
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "isEmpty", {
    "value": function() { for (var key in this) { return false; } return true; },
    "configurable": true,
    "writable": true
});

Object.defineProperty(Object.prototype, "keys", {
    "value": function() { return Object.keys(this) },
    "configurable": true,
    "writable": true
});

String.prototype.arg = function() {

    var result = this;

    var argNum;
    for (var i = 0; i < 10 && (argNum === undefined || argNum < arguments.length); i++) {
        var substr = "%" + i;
        var index = result.indexOf(substr);
        if (index > -1) {
            if (argNum === undefined) {
                argNum = 0;
            }

            while (index > -1) {
                result = result.replace(substr, arguments[argNum]);
                index = result.indexOf(substr, index);
            }
        }

        if (argNum !== undefined) {
            argNum++;
        }
    }

    return result;
};

String.prototype.capitalized = function() {

    return Util.capitalize(this);
};

String.prototype.colorized = function(color) {

    return Util.colorize(this, color);
};

String.prototype.contains = function(string) {

    return this.indexOf(string) > -1;
};

String.prototype.endsWith = function(string) {

    return this.substr(this.length - string.length) === string;
};

String.prototype.highlighted = function() {

    return Util.highlight(this);
};

String.prototype.isEmpty = function() {

    return this.length === 0;
};

String.prototype.left = function(n) {

    return this.substr(0, n);
};

String.prototype.leftJustified = function(n, fill) {

    fill = fill || " ";
    var padding = "";
    for (var i = n - this.length; i > 0; i--) {
        padding += fill;
    }
    return this + padding;
};

String.prototype.mid = function(begin, end) {

    return this.substr(begin, end);
};

String.prototype.replaceAll = function(before, after) {

    var result = this;
    while (result.contains(before)) {
        result = result.replace(before, after);
    }
    return result;
};

String.prototype.right = function(n) {

    return this.substr(n);
};

String.prototype.rightJustified = function(n, fill) {

    fill = fill || " ";
    var padding = "";
    for (var i = n - this.length; i > 0; i--) {
        padding += fill;
    }
    return padding + this;
};

String.prototype.section = function(separator, start, end) {

    var parts = this.split(separator).slice(start, end);
    return parts.join(separator);
};

String.prototype.startsWith = function(string) {

    return this.substr(0, string.length) === string;
};

String.prototype.toDouble = function() {

    var value = parseFloat(this);
    if (isNaN(value)) {
        value = 0.0;
    }
    return value;
};

String.prototype.toInt = function() {

    var value = parseInt(this, 10);
    if (isNaN(value)) {
        value = 0;
    }
    return value;
};

String.prototype.toLower = function() {

    return this.toLowerCase();
};

String.prototype.toUpper = function() {

    return this.toUpperCase();
};

String.prototype.trimmed = function() {

    return this.replace(/^\s+|\s+$/g, "");
};

var console = (function() {

    var flagsRegExp = /%[sdifo]/;

    function parseArguments(args) {
        var strings = [];
        for (var i = 0; i < args.length; i++) {
            var string = args[i], result;
            while ((result = flagsRegExp.exec(string)) !== null) {
                i++;
                string = string.replace(result[0], args[i].toString());
            }
            strings.push(string);
        }
        return strings;
    }

    function debug() {
        LogUtil.logDebug(parseArguments(arguments).join(" "));
    }

    function error() {
        LogUtil.logError(parseArguments(arguments).join(" "));
    }

    function info() {
        LogUtil.logInfo(parseArguments(arguments).join(" "));
    }

    function log() {
        LogUtil.logDebug(parseArguments(arguments).join(" "));
    }

    function warn() {
        LogUtil.logError(parseArguments(arguments).join(" "));
    }

    return {
        "debug": debug,
        "error": error,
        "info": info,
        "log": log,
        "warn": warn
    };
})();

function $(identifier) {

    var split = identifier.split(":");
    return Realm.getObject(Util.capitalize(split[0]), parseInt(split[1], 10));
}

function byChance(n, p) {

    return Util.randomInt(0, p) < n;
}

function min(a, b) {

    return a < b ? a : b;
}

function max(a, b) {

    return a > b ? a : b;
}

function randomInt(min, max) {

    return Util.randomInt(min, max);
}
<|endoftext|>


<commit_before>const minimist = require('minimist');

// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
    boolean: ["dev", "debug", "d", "v", "lint", "help", "version"],
    string: ["init"],
});

const cwd = process.cwd();

module.exports = {
    runnerPath: `${cwd}/kabafile.js`,
    modulePath: `${cwd}/node_modules/kaba`,
    app: getAppEnvironment(argv),
    verbose: argv.v,
    arguments: argv._,
    init: argv.init || null,
    version: argv.version,
    help: argv.help,
};

/**
 *
 * @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, lint: boolean}} argv
 *
 * @return {KabaAppEnvironment}
 */
function getAppEnvironment (argv)
{
    const env = {
        debug: false,
        lint: false,
        watch: false,
        verbose: false,
        mode: "compile",
        cliVersion: null,
    };

    if (argv.d || argv.dev)
    {
        env.debug = true;
        env.lint = true;
        env.watch = true;
    }

    if (argv.debug)
    {
        env.debug = true;
    }

    if (argv.v)
    {
        env.verbose = true;
    }

    if (argv.lint)
    {
        env.lint = true;
        env.mode = "lint";
    }

    if (argv.debug)
    {
        env.debug = true;
    }

    return env;
}
<commit_msg>Rename „lint“ mode to „validate“<commit_after>const minimist = require('minimist');

// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
    boolean: ["dev", "debug", "d", "v", "validate", "help", "version"],
    string: ["init"],
});

const cwd = process.cwd();

module.exports = {
    runnerPath: `${cwd}/kabafile.js`,
    modulePath: `${cwd}/node_modules/kaba`,
    app: getAppEnvironment(argv),
    verbose: argv.v,
    arguments: argv._,
    init: argv.init || null,
    version: argv.version,
    help: argv.help,
};

/**
 *
 * @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, validate: boolean}} argv
 *
 * @return {KabaAppEnvironment}
 */
function getAppEnvironment (argv)
{
    const env = {
        debug: false,
        lint: false,
        watch: false,
        verbose: false,
        mode: "compile",
        cliVersion: null,
    };

    if (argv.d || argv.dev)
    {
        env.debug = true;
        env.lint = true;
        env.watch = true;
    }

    if (argv.debug)
    {
        env.debug = true;
    }

    if (argv.v)
    {
        env.verbose = true;
    }

    if (argv.validate)
    {
        env.lint = true;
        env.mode = "validate";
    }

    if (argv.debug)
    {
        env.debug = true;
    }

    return env;
}
<|endoftext|>