<commit_before>/**
 * helper functions for e2e tests
 */

module.exports = {

  logout: logout,

  login: login,

  deleteAssetFromList: deleteAssetFromList,

  loginAsAdmin: function() {
    login('superadmin', 'admin', 'admin');
  }

};

// ----------------------------------------------------------------------------

function login(tenant, username, password) {

  browser.get('/login');
  element(by.id('loginTenant')).clear().sendKeys(tenant);
  element(by.id('loginUsername')).clear().sendKeys(username);
  element(by.id('loginPassword')).clear().sendKeys(password);
  element(by.partialButtonText('Submit')).click();
  expect(element(by.css('header .dropdown-toggle .fa-user')).isPresent()).toBe(true);

}

function deleteAssetFromList(list, name) {
  var selectedItem;
  list
    .then(function(s) {
      s.forEach(function(item, index) {
        item.getText().then(function(text) {
          if (text === name) {
            selectedItem = item;
          }
        });
      });
    })
    .then(function() {
      selectedItem.element(by.xpath("ancestor::tr"))
        .element(by.cssContainingText('.btn', 'Delete')).click();
      element(by.css('.modal-dialog .modal-footer .btn-primary')).click();
    });
}

function logout() {

  element(by.css('header .navbar-right .dropdown-toggle')).click();
  element(by.css('.dropdown-menu a[ng-click^="logout"]')).click();
  expect(element(by.css('header .dropdown-toggle .fa-user')).isPresent()).toBe(false);

}
<commit_msg>Adds common edit-asset behavior as part of the helper function.<commit_after>/**
 * helper functions for e2e tests
 */

module.exports = {

  logout: logout,

  login: login,

  deleteAssetFromList: deleteAssetFromList,

  editAssetFromList: editAssetFromList,

  loginAsAdmin: function() {
    login('superadmin', 'admin', 'admin');
  }

};

// ----------------------------------------------------------------------------

function login(tenant, username, password) {

  browser.get('/login');
  element(by.id('loginTenant')).clear().sendKeys(tenant);
  element(by.id('loginUsername')).clear().sendKeys(username);
  element(by.id('loginPassword')).clear().sendKeys(password);
  element(by.partialButtonText('Submit')).click();
  expect(element(by.css('header .dropdown-toggle .fa-user')).isPresent()).toBe(true);

}

function deleteAssetFromList(list, name) {
  var selectedItem;
  list
    .then(function(s) {
      s.forEach(function(item, index) {
        item.getText().then(function(text) {
          if (text === name) {
            selectedItem = item;
          }
        });
      });
    })
    .then(function() {
      selectedItem.element(by.xpath("ancestor::tr"))
        .element(by.cssContainingText('.btn', 'Delete')).click();
      element(by.css('.modal-dialog .modal-footer .btn-primary')).click();
    });
}

function editAssetFromList(list, name) {
  var selectedItem;
  list
    .then(function(s) {
      s.forEach(function(item, index) {
        item.getText().then(function(text) {
          if (text === name) {
            selectedItem = item;
          }
        });
      });
    })
    .then(function() {
      selectedItem.element(by.xpath("ancestor::tr"))
        .element(by.cssContainingText('.btn', 'Edit')).click();
    });
}

function logout() {

  element(by.css('header .navbar-right .dropdown-toggle')).click();
  element(by.css('.dropdown-menu a[ng-click^="logout"]')).click();
  expect(element(by.css('header .dropdown-toggle .fa-user')).isPresent()).toBe(false);

}
<|endoftext|>


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

/**
 * @fileoverview The SafeStyle type and its builders.
 *
 * TODO(user): Link to document stating type contract.
 */

goog.provide('goog.html.SafeStyle');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('goog.string.TypedString');

/**
 * A string-like object which represents a sequence of CSS declarations
 * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})
 * and that carries the security type contract that its value, as a string,
 * will not cause untrusted script execution (XSS) when evaluated as CSS in a
 * browser.
 *
 * Instances of this type must be created via the factory methods
 * ({@code goog.html.SafeStyle.create} or
 * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its
 * constructor. The constructor intentionally takes no parameters and the type
 * is immutable; hence only a default instance corresponding to the empty string
 * can be obtained via constructor invocation.
 *
 * A SafeStyle's string representation ({@link #getSafeStyleString()}) can
 * safely:
 *

 *
Be interpolated as the entire content of a *quoted* HTML style
 *       attribute, or before already existing properties. The SafeStyle string
 *       *must be HTML-attribute-escaped* (where " and ' are escaped) before
 *       interpolation.
 *
Be interpolated as the entire content of a {}-wrapped block within a
 *       stylesheet, or before already existing properties. The SafeStyle string
 *       should not be escaped before interpolation. SafeStyle's contract also
 *       guarantees that the string will not be able to introduce new properties
 *       or elide existing ones.
 *
Be assigned to the style property of a DOM node. The SafeStyle string
 *       should not be escaped before being assigned to the property.
 *

 *
 * A SafeStyle may never contain literal angle brackets. Otherwise, it could
 * be unsafe to place a SafeStyle into a <style> tag (where it can't
 * be HTML escaped). For example, if the SafeStyle containing
 * "{@code font: 'foo <style/><script>evil</script>'}" were
 * interpolated within a <style> tag, this would then break out of the
 * style context into HTML.
 *
 * A SafeStyle may contain literal single or double quotes, and as such the
 * entire style string must be escaped when used in a style attribute (if
 * this were not the case, the string could contain a matching quote that
 * would escape from the style attribute).
 *
 * Values of this type must be composable, i.e. for any two values
 * {@code style1} and {@code style2} of this type,
 * {@code style1.getSafeStyleString() + style2.getSafeStyleString()} must
 * itself be a value that satisfies the SafeStyle type constraint. This
 * requirement implies that for any value {@code style} of this type,
 * {@code style.getSafeStyleString()} must not end in a "property value" or
 * "property name" context. For example, a value of {@code background:url("}
 * or {@code font-} would not satisfy the SafeStyle contract. This is because
 * concatenating such strings with a second value that itself does not contain
 * unsafe CSS can result in an overall string that does. For example, if
 * {@code javascript:evil())"} is appended to {@code background:url("}, the
 * resulting string may result in the execution of a malicious script.
 *
 * TODO(user): Consider whether we should implement UTF-8 interchange
 * validity checks and blacklisting of newlines (including Unicode ones) and
 * other whitespace characters (\t, \f). Document here if so and also update
 * SafeStyle.fromConstant().
 *
 * The following example values comply with this type's contract:
 *

 *

width: 1em;

 *

height:1em;

 *

width: 1em;height: 1em;

 *

background:url('http://url');

 *

 * In addition, the empty string is safe for use in a CSS attribute.
 *
 * The following example values do NOT comply with this type's contract:
 *

 *

background: red
 (missing a trailing semi-colon)
 *

background:
 (missing a value and a trailing semi-colon)
 *

1em
 (missing an attribute name, which provides context for
 *       the value)
 *

 *
 * @see goog.html.SafeStyle#create
 * @see goog.html.SafeStyle#fromConstant
 * @see http://www.w3.org/TR/css3-syntax/
 * @constructor
 * @final
 * @struct
 * @implements {goog.string.TypedString}
 */
goog.html.SafeStyle = function() {
  /**
   * The contained value of this SafeStyle.  The field has a purposely
   * ugly name to make (non-compiled) code that attempts to directly access this
   * field stand out.
   * @private {string}
   */
  this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';

  /**
   * A type marker used to implement additional run-time type checking.
   * @see goog.html.SafeStyle#unwrap
   * @const
   * @private
   */
  this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
      goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};

/**
 * @override
 * @const
 */
goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;

/**
 * Type marker for the SafeStyle type, used to implement additional
 * run-time type checking.
 * @const
 * @private
 */
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};

/**
 * Creates a SafeStyle object from a compile-time constant string.
 *
 * {@code style} should be in the format
 * {@code name: value; [name: value; ...]} and must not have any < or >
 * characters in it. This is so that SafeStyle's contract is preserved,
 * allowing the SafeStyle to correctly be interpreted as a sequence of CSS
 * declarations and without affecting the syntactic structure of any
 * surrounding CSS and HTML.
 *
 * This method performs basic sanity checks on the format of {@code style}
 * but does not constrain the format of {@code name} and {@code value}, except
 * for disallowing tag characters.
 *
 * @param {!goog.string.Const} style A compile-time-constant string from which
 *     to create a SafeStyle.
 * @return {!goog.html.SafeStyle} A SafeStyle object initialized to
 *     {@code style}.
 */
goog.html.SafeStyle.fromConstant = function(style) {
  var styleString = goog.string.Const.unwrap(style);
  if (styleString.length === 0) {
    return goog.html.SafeStyle.EMPTY;
  }
  goog.html.SafeStyle.checkStyle_(styleString);
  goog.asserts.assert(goog.string.endsWith(styleString, ';'),
      'Last character of style string is not \';\': ' + styleString);
  goog.asserts.assert(goog.string.contains(styleString, ':'),
      'Style string must contain at least one \':\', to ' +
      'specify a "name: value" pair: ' + styleString);
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      styleString);
};

/**
 * Checks if the style definition is valid.
 * @param {string} style
 * @private
 */
goog.html.SafeStyle.checkStyle_ = function(style) {
  goog.asserts.assert(!/[<>]/.test(style),
      'Forbidden characters in style string: ' + style);
};

/**
 * Returns this SafeStyle's value as a string.
 *
 * IMPORTANT: In code where it is security relevant that an object's type is
 * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of
 * this method. If in doubt, assume that it's security relevant. In particular,
 * note that goog.html functions which return a goog.html type do not guarantee
 * the returned instance is of the right type. For example:
 *
 *

 * var fakeSafeHtml = new String('fake');
 * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
 * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
 * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
 * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
 * // instanceof goog.html.SafeHtml.
 *

 *
 * @see goog.html.SafeStyle#unwrap
 * @override
 */
goog.html.SafeStyle.prototype.getTypedStringValue = function() {
  return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
};

if (goog.DEBUG) {
  /**
   * Returns a debug string-representation of this value.
   *
   * To obtain the actual string value wrapped in a SafeStyle, use
   * {@code goog.html.SafeStyle.unwrap}.
   *
   * @see goog.html.SafeStyle#unwrap
   * @override
   */
  goog.html.SafeStyle.prototype.toString = function() {
    return 'SafeStyle{' +
        this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}';
  };
}

/**
 * Performs a runtime check that the provided object is indeed a
 * SafeStyle object, and returns its value.
 *
 * @param {!goog.html.SafeStyle} safeStyle The object to extract from.
 * @return {string} The safeStyle object's contained string, unless
 *     the run-time type check fails. In that case, {@code unwrap} returns an
 *     innocuous string, or, if assertions are enabled, throws
 *     {@code goog.asserts.AssertionError}.
 */
goog.html.SafeStyle.unwrap = function(safeStyle) {
  // Perform additional Run-time type-checking to ensure that
  // safeStyle is indeed an instance of the expected type.  This
  // provides some additional protection against security bugs due to
  // application code that disables type checks.
  // Specifically, the following checks are performed:
  // 1. The object is an instance of the expected type.
  // 2. The object is not an instance of a subclass.
  // 3. The object carries a type marker for the expected type. "Faking" an
  // object requires a reference to the type marker, which has names intended
  // to stand out in code reviews.
  if (safeStyle instanceof goog.html.SafeStyle &&
      safeStyle.constructor === goog.html.SafeStyle &&
      safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
          goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
    return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  } else {
    goog.asserts.fail(
        'expected object of type SafeStyle, got \'' + safeStyle + '\'');
    return 'type_error:SafeStyle';
  }
};

/**
 * Package-internal utility method to create SafeStyle instances.
 *
 * @param {string} style The string to initialize the SafeStyle object with.
 * @return {!goog.html.SafeStyle} The initialized SafeStyle object.
 * @package
 */
goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse =
    function(style) {
  var safeStyle = new goog.html.SafeStyle();
  safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
  return safeStyle;
};

/**
 * A SafeStyle instance corresponding to the empty string.
 * @const {!goog.html.SafeStyle}
 */
goog.html.SafeStyle.EMPTY =
    goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');

/**
 * The innocuous string generated by goog.html.SafeUrl.create when passed
 * an unsafe value.
 * @const {string}
 */
goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';

/**
 * Mapping of property names to their values.
 * @typedef {!Object<string, goog.string.Const|string>}
 */
goog.html.SafeStyle.PropertyMap;

/**
 * Creates a new SafeStyle object from the properties specified in the map.
 * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to
 *     their values, for example {'margin': '1px'}. Names must consist of
 *     [-_a-zA-Z0-9]. Values might be strings consisting of [-.%_!# a-zA-Z0-9].
 *     Other values must be wrapped in goog.string.Const. Null value causes
 *     skipping the property.
 * @return {!goog.html.SafeStyle}
 * @throws {Error} If invalid name is provided.
 * @throws {goog.asserts.AssertionError} If invalid value is provided. With
 *     disabled assertions, invalid value is replaced by
 *     goog.html.SafeStyle.INNOCUOUS_STRING.
 */
goog.html.SafeStyle.create = function(map) {
  var style = '';
  for (var name in map) {
    if (!/^[-_a-zA-Z0-9]+$/.test(name)) {
      throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name);
    }
    var value = map[name];
    if (value == null) {
      continue;
    }
    if (value instanceof goog.string.Const) {
      value = goog.string.Const.unwrap(value);
      // These characters can be used to change context and we don't want that
      // even with const values.
      goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].');
    } else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) {
      goog.asserts.fail(
          'String value allows only [-.%_!# a-zA-Z0-9], got: ' + value);
      value = goog.html.SafeStyle.INNOCUOUS_STRING;
    }
    style += name + ':' + value + ';';
  }
  if (!style) {
    return goog.html.SafeStyle.EMPTY;
  }
  goog.html.SafeStyle.checkStyle_(style);
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};

// Keep in sync with the error string in create().
/**
 * Regular expression for safe values.
 * @const {!RegExp}
 * @private
 */
goog.html.SafeStyle.VALUE_RE_ = /^[-.%_!# a-zA-Z0-9]+$/;

/**
 * Creates a new SafeStyle object by concatenating the values.
 * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args
 *     SafeStyles to concatenate.
 * @return {!goog.html.SafeStyle}
 */
goog.html.SafeStyle.concat = function(var_args) {
  var style = '';

  /**
   * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument
   */
  var addArgument = function(argument) {
    if (goog.isArray(argument)) {
      goog.array.forEach(argument, addArgument);
    } else {
      style += goog.html.SafeStyle.unwrap(argument);
    }
  };

  goog.array.forEach(arguments, addArgument);
  if (!style) {
    return goog.html.SafeStyle.EMPTY;
  }
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};
<commit_msg>Fix incorrect methods name in class documentation. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=81987413<commit_after>// Copyright 2014 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The SafeStyle type and its builders.
 *
 * TODO(user): Link to document stating type contract.
 */

goog.provide('goog.html.SafeStyle');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.Const');
goog.require('goog.string.TypedString');

/**
 * A string-like object which represents a sequence of CSS declarations
 * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})
 * and that carries the security type contract that its value, as a string,
 * will not cause untrusted script execution (XSS) when evaluated as CSS in a
 * browser.
 *
 * Instances of this type must be created via the factory methods
 * ({@code goog.html.SafeStyle.create} or
 * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its
 * constructor. The constructor intentionally takes no parameters and the type
 * is immutable; hence only a default instance corresponding to the empty string
 * can be obtained via constructor invocation.
 *
 * A SafeStyle's string representation ({@link #getSafeStyleString()}) can
 * safely:
 *

 *
Be interpolated as the entire content of a *quoted* HTML style
 *       attribute, or before already existing properties. The SafeStyle string
 *       *must be HTML-attribute-escaped* (where " and ' are escaped) before
 *       interpolation.
 *
Be interpolated as the entire content of a {}-wrapped block within a
 *       stylesheet, or before already existing properties. The SafeStyle string
 *       should not be escaped before interpolation. SafeStyle's contract also
 *       guarantees that the string will not be able to introduce new properties
 *       or elide existing ones.
 *
Be assigned to the style property of a DOM node. The SafeStyle string
 *       should not be escaped before being assigned to the property.
 *

 *
 * A SafeStyle may never contain literal angle brackets. Otherwise, it could
 * be unsafe to place a SafeStyle into a <style> tag (where it can't
 * be HTML escaped). For example, if the SafeStyle containing
 * "{@code font: 'foo <style/><script>evil</script>'}" were
 * interpolated within a <style> tag, this would then break out of the
 * style context into HTML.
 *
 * A SafeStyle may contain literal single or double quotes, and as such the
 * entire style string must be escaped when used in a style attribute (if
 * this were not the case, the string could contain a matching quote that
 * would escape from the style attribute).
 *
 * Values of this type must be composable, i.e. for any two values
 * {@code style1} and {@code style2} of this type,
 * {@code goog.html.SafeStyle.unwrap(style1) +
 * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies
 * the SafeStyle type constraint. This requirement implies that for any value
 * {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must
 * not end in a "property value" or "property name" context. For example,
 * a value of {@code background:url("} or {@code font-} would not satisfy the
 * SafeStyle contract. This is because concatenating such strings with a
 * second value that itself does not contain unsafe CSS can result in an
 * overall string that does. For example, if {@code javascript:evil())"} is
 * appended to {@code background:url("}, the resulting string may result in
 * the execution of a malicious script.
 *
 * TODO(user): Consider whether we should implement UTF-8 interchange
 * validity checks and blacklisting of newlines (including Unicode ones) and
 * other whitespace characters (\t, \f). Document here if so and also update
 * SafeStyle.fromConstant().
 *
 * The following example values comply with this type's contract:
 *

 *

width: 1em;

 *

height:1em;

 *

width: 1em;height: 1em;

 *

background:url('http://url');

 *

 * In addition, the empty string is safe for use in a CSS attribute.
 *
 * The following example values do NOT comply with this type's contract:
 *

 *

background: red
 (missing a trailing semi-colon)
 *

background:
 (missing a value and a trailing semi-colon)
 *

1em
 (missing an attribute name, which provides context for
 *       the value)
 *

 *
 * @see goog.html.SafeStyle#create
 * @see goog.html.SafeStyle#fromConstant
 * @see http://www.w3.org/TR/css3-syntax/
 * @constructor
 * @final
 * @struct
 * @implements {goog.string.TypedString}
 */
goog.html.SafeStyle = function() {
  /**
   * The contained value of this SafeStyle.  The field has a purposely
   * ugly name to make (non-compiled) code that attempts to directly access this
   * field stand out.
   * @private {string}
   */
  this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';

  /**
   * A type marker used to implement additional run-time type checking.
   * @see goog.html.SafeStyle#unwrap
   * @const
   * @private
   */
  this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
      goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
};

/**
 * @override
 * @const
 */
goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;

/**
 * Type marker for the SafeStyle type, used to implement additional
 * run-time type checking.
 * @const
 * @private
 */
goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};

/**
 * Creates a SafeStyle object from a compile-time constant string.
 *
 * {@code style} should be in the format
 * {@code name: value; [name: value; ...]} and must not have any < or >
 * characters in it. This is so that SafeStyle's contract is preserved,
 * allowing the SafeStyle to correctly be interpreted as a sequence of CSS
 * declarations and without affecting the syntactic structure of any
 * surrounding CSS and HTML.
 *
 * This method performs basic sanity checks on the format of {@code style}
 * but does not constrain the format of {@code name} and {@code value}, except
 * for disallowing tag characters.
 *
 * @param {!goog.string.Const} style A compile-time-constant string from which
 *     to create a SafeStyle.
 * @return {!goog.html.SafeStyle} A SafeStyle object initialized to
 *     {@code style}.
 */
goog.html.SafeStyle.fromConstant = function(style) {
  var styleString = goog.string.Const.unwrap(style);
  if (styleString.length === 0) {
    return goog.html.SafeStyle.EMPTY;
  }
  goog.html.SafeStyle.checkStyle_(styleString);
  goog.asserts.assert(goog.string.endsWith(styleString, ';'),
      'Last character of style string is not \';\': ' + styleString);
  goog.asserts.assert(goog.string.contains(styleString, ':'),
      'Style string must contain at least one \':\', to ' +
      'specify a "name: value" pair: ' + styleString);
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      styleString);
};

/**
 * Checks if the style definition is valid.
 * @param {string} style
 * @private
 */
goog.html.SafeStyle.checkStyle_ = function(style) {
  goog.asserts.assert(!/[<>]/.test(style),
      'Forbidden characters in style string: ' + style);
};

/**
 * Returns this SafeStyle's value as a string.
 *
 * IMPORTANT: In code where it is security relevant that an object's type is
 * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of
 * this method. If in doubt, assume that it's security relevant. In particular,
 * note that goog.html functions which return a goog.html type do not guarantee
 * the returned instance is of the right type. For example:
 *
 *

 * var fakeSafeHtml = new String('fake');
 * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
 * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
 * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
 * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
 * // instanceof goog.html.SafeHtml.
 *

 *
 * @see goog.html.SafeStyle#unwrap
 * @override
 */
goog.html.SafeStyle.prototype.getTypedStringValue = function() {
  return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
};

if (goog.DEBUG) {
  /**
   * Returns a debug string-representation of this value.
   *
   * To obtain the actual string value wrapped in a SafeStyle, use
   * {@code goog.html.SafeStyle.unwrap}.
   *
   * @see goog.html.SafeStyle#unwrap
   * @override
   */
  goog.html.SafeStyle.prototype.toString = function() {
    return 'SafeStyle{' +
        this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}';
  };
}

/**
 * Performs a runtime check that the provided object is indeed a
 * SafeStyle object, and returns its value.
 *
 * @param {!goog.html.SafeStyle} safeStyle The object to extract from.
 * @return {string} The safeStyle object's contained string, unless
 *     the run-time type check fails. In that case, {@code unwrap} returns an
 *     innocuous string, or, if assertions are enabled, throws
 *     {@code goog.asserts.AssertionError}.
 */
goog.html.SafeStyle.unwrap = function(safeStyle) {
  // Perform additional Run-time type-checking to ensure that
  // safeStyle is indeed an instance of the expected type.  This
  // provides some additional protection against security bugs due to
  // application code that disables type checks.
  // Specifically, the following checks are performed:
  // 1. The object is an instance of the expected type.
  // 2. The object is not an instance of a subclass.
  // 3. The object carries a type marker for the expected type. "Faking" an
  // object requires a reference to the type marker, which has names intended
  // to stand out in code reviews.
  if (safeStyle instanceof goog.html.SafeStyle &&
      safeStyle.constructor === goog.html.SafeStyle &&
      safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
          goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
    return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
  } else {
    goog.asserts.fail(
        'expected object of type SafeStyle, got \'' + safeStyle + '\'');
    return 'type_error:SafeStyle';
  }
};

/**
 * Package-internal utility method to create SafeStyle instances.
 *
 * @param {string} style The string to initialize the SafeStyle object with.
 * @return {!goog.html.SafeStyle} The initialized SafeStyle object.
 * @package
 */
goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse =
    function(style) {
  var safeStyle = new goog.html.SafeStyle();
  safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
  return safeStyle;
};

/**
 * A SafeStyle instance corresponding to the empty string.
 * @const {!goog.html.SafeStyle}
 */
goog.html.SafeStyle.EMPTY =
    goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');

/**
 * The innocuous string generated by goog.html.SafeUrl.create when passed
 * an unsafe value.
 * @const {string}
 */
goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';

/**
 * Mapping of property names to their values.
 * @typedef {!Object<string, goog.string.Const|string>}
 */
goog.html.SafeStyle.PropertyMap;

/**
 * Creates a new SafeStyle object from the properties specified in the map.
 * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to
 *     their values, for example {'margin': '1px'}. Names must consist of
 *     [-_a-zA-Z0-9]. Values might be strings consisting of [-.%_!# a-zA-Z0-9].
 *     Other values must be wrapped in goog.string.Const. Null value causes
 *     skipping the property.
 * @return {!goog.html.SafeStyle}
 * @throws {Error} If invalid name is provided.
 * @throws {goog.asserts.AssertionError} If invalid value is provided. With
 *     disabled assertions, invalid value is replaced by
 *     goog.html.SafeStyle.INNOCUOUS_STRING.
 */
goog.html.SafeStyle.create = function(map) {
  var style = '';
  for (var name in map) {
    if (!/^[-_a-zA-Z0-9]+$/.test(name)) {
      throw Error('Name allows only [-_a-zA-Z0-9], got: ' + name);
    }
    var value = map[name];
    if (value == null) {
      continue;
    }
    if (value instanceof goog.string.Const) {
      value = goog.string.Const.unwrap(value);
      // These characters can be used to change context and we don't want that
      // even with const values.
      goog.asserts.assert(!/[{;}]/.test(value), 'Value does not allow [{;}].');
    } else if (!goog.html.SafeStyle.VALUE_RE_.test(value)) {
      goog.asserts.fail(
          'String value allows only [-.%_!# a-zA-Z0-9], got: ' + value);
      value = goog.html.SafeStyle.INNOCUOUS_STRING;
    }
    style += name + ':' + value + ';';
  }
  if (!style) {
    return goog.html.SafeStyle.EMPTY;
  }
  goog.html.SafeStyle.checkStyle_(style);
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};

// Keep in sync with the error string in create().
/**
 * Regular expression for safe values.
 * @const {!RegExp}
 * @private
 */
goog.html.SafeStyle.VALUE_RE_ = /^[-.%_!# a-zA-Z0-9]+$/;

/**
 * Creates a new SafeStyle object by concatenating the values.
 * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args
 *     SafeStyles to concatenate.
 * @return {!goog.html.SafeStyle}
 */
goog.html.SafeStyle.concat = function(var_args) {
  var style = '';

  /**
   * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument
   */
  var addArgument = function(argument) {
    if (goog.isArray(argument)) {
      goog.array.forEach(argument, addArgument);
    } else {
      style += goog.html.SafeStyle.unwrap(argument);
    }
  };

  goog.array.forEach(arguments, addArgument);
  if (!style) {
    return goog.html.SafeStyle.EMPTY;
  }
  return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
      style);
};
<|endoftext|>


<commit_before>export default generateHtmlString;

function generateHtmlString(sheets, className) {
  let html = '';
  for (let i = 0; i < sheets.length; i++) {
    const sheet = sheets[i];
    const mediaAttr = sheet.media ? ` media="${sheet.media}"` : '';
    html += `<style class="${className}"${mediaAttr}>${sheet.css}</style>`;
  }
  return html;
}
<commit_msg>Avoid rendering empty class attribute<commit_after>export default generateHtmlString;

function generateHtmlString(sheets, className) {
  let html = '';
  for (let i = 0; i < sheets.length; i++) {
    const sheet = sheets[i];
    const classAttr = className ? ` class="${className}"` : '';
    const mediaAttr = sheet.media ? ` media="${sheet.media}"` : '';
    html += `<style${classAttr}${mediaAttr}>${sheet.css}</style>`;
  }
  return html;
}
<|endoftext|>


<commit_before>var container;
var camera, scene, renderer, particles, geometry, material, i, h, color;
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init() {
  container = document.createElement('div');
  document.body.appendChild(container);

  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 5000);
  scene = new THREE.Scene();

  geometry = new THREE.Geometry();

  var variance = 2.5 * (Math.random() + Math.random() + Math.random()) / 3.0;
  var arms = Math.floor(Math.random() * 4) + 3;

  var clouds = 500 * arms;
  var stars = 4000;

  var vertices = new Float32Array((clouds + stars) * 3);
  var colors = new Float32Array((clouds + stars) * 3);
  var alphas = new Float32Array((clouds + stars) * 1);
  var sizes = new Float32Array((clouds + stars) * 1);

  var r1 = 1.0;
  var g1 = 1.0;
  var b1 = 0.8;

  var r2 = 0.65;
  var g2 = 0.85;
  var b2 = 1.0;

  for (i = 0; i < clouds; ++i) {
    var f = (clouds - i) / clouds;
    var g = i / clouds;
    var a = (i % arms) / arms * 2.0 * 3.19149 + g * 3.0 + variance * ((Math.random() + Math.random() + Math.random()) * 0.4 / 3.0 - 0.2);
    var r = g * 700;
    var x = Math.cos(a) * r;
    var y = Math.sin(a) * r;
    var z = 0.0;

    vertices[i * 3 + 0] = x;
    vertices[i * 3 + 1] = y;
    vertices[i * 3 + 2] = z;

    var c = Math.pow(f, 0.8);
    colors[i * 3 + 0] = c * r1 + (1.0 - c) * r2;
    colors[i * 3 + 1] = c * g1 + (1.0 - c) * g2;
    colors[i * 3 + 2] = c * b1 + (1.0 - c) * b2;

    var s = Math.pow(512.0, Math.pow(f * Math.random(), 0.3));
    alphas[i] = Math.random() * (400.0 - s) / 5000.0 * Math.pow(g, 0.49);
    sizes[i] = s;
  }

  for (i = clouds; i < clouds + stars; ++i) {
    var f = (clouds + stars - i) / (clouds + stars);
    var g = i / (clouds + stars);
    //var a = Math.random() * 3.14159 * 2.0;
    // var r = f * 700;
    var x = Math.random() * 5000.0 - 2500.0;
    var y = Math.random() * 5000.0 - 2500.0;
    var z = Math.random() * 5000.0 - 2500.0;
    if (f < 0.2) {
      var a = Math.random() * 3.14159 * 2.0;
      var r = 5.0 + Math.pow(f, 1.5) / Math.pow(0.2, 1.5) * 700;
      var x = Math.cos(a) * r;
      var y = Math.sin(a) * r;
      var z = Math.random() * g * g * Math.sqrt(r) - 0.5 * Math.sqrt(r);
    }

    vertices[i * 3 + 0] = x;
    vertices[i * 3 + 1] = y;
    vertices[i * 3 + 2] = z;

    var c = Math.pow(f, 0.8);
    colors[i * 3 + 0] = 1.0;
    colors[i * 3 + 1] = 1.0;
    colors[i * 3 + 2] = 1.0;

    var s = Math.pow(512.0, Math.pow(f * Math.random(), 0.3));
    alphas[i] = 0.2 + Math.random() * 0.8;
    sizes[i] = Math.random() * Math.random() * 8.0;
  }

  var bufferGeometry = new THREE.BufferGeometry();
  bufferGeometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
  bufferGeometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
  bufferGeometry.addAttribute('alpha', new THREE.BufferAttribute(alphas, 1));
  bufferGeometry.addAttribute('size', new THREE.BufferAttribute(sizes, 1));

  uniforms = {
    texture: { type: "t", value: THREE.ImageUtils.loadTexture("sphere.png") }
  };

  var shaderMaterial = new THREE.ShaderMaterial({
    uniforms:       uniforms,
    vertexShader:   document.getElementById('vertexshader').textContent,
    fragmentShader: document.getElementById('fragmentshader').textContent,
    transparent:    true,
    depthTest:      false,
    blending:       THREE.AdditiveBlending
  });

  particles = new THREE.Points(bufferGeometry, shaderMaterial);
  scene.add(particles);

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  document.addEventListener('mousemove', onDocumentMouseMove, false);
  document.addEventListener('touchstart', onDocumentTouchStart, false);
  document.addEventListener('touchmove', onDocumentTouchMove, false);

  window.addEventListener('resize', onWindowResize, false);
}

function onDocumentMouseMove(event) {
  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;
}

function onDocumentTouchStart(event) {
  if (event.touches.length === 1) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onDocumentTouchMove(event) {
  if (event.touches.length === 1) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onWindowResize(event) {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
  requestAnimationFrame(animate);

  var a = 2 * mouseX / windowHalfX;
  var b = 2 * mouseY / windowHalfY;
  var x = 0.0;
  var y = 1000;
  var z = 1000 + 1000 * b;
  camera.position.x = x * Math.cos(a) - y * Math.sin(a);
  camera.position.y = - x * Math.sin(a) + y * Math.cos(a);
  camera.position.z = z;

  camera.lookAt(scene.position);
  camera.rotation.order = 'XYZ';
  camera.rotateOnAxis(new THREE.Vector3(0, 0, 1), a / 10.0);
  camera.up = new THREE.Vector3(0, 0, 1);

  render();
}

function render() {
  renderer.render(scene, camera);
}
<commit_msg>Add twist randomization<commit_after>var container;
var camera, scene, renderer, particles, geometry, material, i, h, color;
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init() {
  container = document.createElement('div');
  document.body.appendChild(container);

  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 5000);
  scene = new THREE.Scene();

  geometry = new THREE.Geometry();

  var variance = 2.5 * (Math.random() + Math.random() + Math.random()) / 3.0;
  var arms = Math.floor(Math.random() * 4) + 3;
  var twist = 0.6 + (Math.random() + Math.random() + Math.random() + Math.random() + Math.random());

  var clouds = 500 * arms;
  var stars = 4000;

  var vertices = new Float32Array((clouds + stars) * 3);
  var colors = new Float32Array((clouds + stars) * 3);
  var alphas = new Float32Array((clouds + stars) * 1);
  var sizes = new Float32Array((clouds + stars) * 1);

  var r1 = 1.0;
  var g1 = 1.0;
  var b1 = 0.8;

  var r2 = 0.65;
  var g2 = 0.85;
  var b2 = 1.0;

  for (i = 0; i < clouds; ++i) {
    var f = (clouds - i) / clouds;
    var g = i / clouds;
    var r = g * 700;
    var a = (i % arms) / arms * 2.0 * 3.19149 + g * twist + variance * ((Math.random() + Math.random() + Math.random()) * 0.4 / 3.0 - 0.2);
    var x = Math.cos(a) * r;
    var y = Math.sin(a) * r;
    var z = 0.0;

    vertices[i * 3 + 0] = x;
    vertices[i * 3 + 1] = y;
    vertices[i * 3 + 2] = z;

    var c = Math.pow(f, 0.8);
    colors[i * 3 + 0] = c * r1 + (1.0 - c) * r2;
    colors[i * 3 + 1] = c * g1 + (1.0 - c) * g2;
    colors[i * 3 + 2] = c * b1 + (1.0 - c) * b2;

    var s = Math.pow(512.0, Math.pow(f * Math.random(), 0.3));
    alphas[i] = Math.random() * (400.0 - s) / 5000.0 * Math.pow(g, 0.49);
    sizes[i] = s;
  }

  for (i = clouds; i < clouds + stars; ++i) {
    var f = (clouds + stars - i) / (clouds + stars);
    var g = i / (clouds + stars);
    //var a = Math.random() * 3.14159 * 2.0;
    // var r = f * 700;
    var x = Math.random() * 5000.0 - 2500.0;
    var y = Math.random() * 5000.0 - 2500.0;
    var z = Math.random() * 5000.0 - 2500.0;
    if (f < 0.2) {
      var a = Math.random() * 3.14159 * 2.0;
      var r = 5.0 + Math.pow(f, 1.5) / Math.pow(0.2, 1.5) * 700;
      var x = Math.cos(a) * r;
      var y = Math.sin(a) * r;
      var z = Math.random() * g * g * Math.sqrt(r) - 0.5 * Math.sqrt(r);
    }

    vertices[i * 3 + 0] = x;
    vertices[i * 3 + 1] = y;
    vertices[i * 3 + 2] = z;

    var c = Math.pow(f, 0.8);
    colors[i * 3 + 0] = 1.0;
    colors[i * 3 + 1] = 1.0;
    colors[i * 3 + 2] = 1.0;

    var s = Math.pow(512.0, Math.pow(f * Math.random(), 0.3));
    alphas[i] = 0.2 + Math.random() * 0.8;
    sizes[i] = Math.random() * Math.random() * 8.0;
  }

  var bufferGeometry = new THREE.BufferGeometry();
  bufferGeometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
  bufferGeometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
  bufferGeometry.addAttribute('alpha', new THREE.BufferAttribute(alphas, 1));
  bufferGeometry.addAttribute('size', new THREE.BufferAttribute(sizes, 1));

  uniforms = {
    texture: { type: "t", value: THREE.ImageUtils.loadTexture("sphere.png") }
  };

  var shaderMaterial = new THREE.ShaderMaterial({
    uniforms:       uniforms,
    vertexShader:   document.getElementById('vertexshader').textContent,
    fragmentShader: document.getElementById('fragmentshader').textContent,
    transparent:    true,
    depthTest:      false,
    blending:       THREE.AdditiveBlending
  });

  particles = new THREE.Points(bufferGeometry, shaderMaterial);
  scene.add(particles);

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  document.addEventListener('mousemove', onDocumentMouseMove, false);
  document.addEventListener('touchstart', onDocumentTouchStart, false);
  document.addEventListener('touchmove', onDocumentTouchMove, false);

  window.addEventListener('resize', onWindowResize, false);
}

function onDocumentMouseMove(event) {
  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;
}

function onDocumentTouchStart(event) {
  if (event.touches.length === 1) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onDocumentTouchMove(event) {
  if (event.touches.length === 1) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onWindowResize(event) {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate() {
  requestAnimationFrame(animate);

  var a = 2 * mouseX / windowHalfX;
  var b = 2 * mouseY / windowHalfY;
  var x = 0.0;
  var y = 1000;
  var z = 1000 + 1000 * b;
  camera.position.x = x * Math.cos(a) - y * Math.sin(a);
  camera.position.y = - x * Math.sin(a) + y * Math.cos(a);
  camera.position.z = z;

  camera.lookAt(scene.position);
  camera.rotation.order = 'XYZ';
  camera.rotateOnAxis(new THREE.Vector3(0, 0, 1), a / 10.0);
  camera.up = new THREE.Vector3(0, 0, 1);

  render();
}

function render() {
  renderer.render(scene, camera);
}
<|endoftext|>


<commit_before>var UntilStream = require('../');
var streamBuffers = require("stream-buffers");

var us = new UntilStream({ pattern: ' World'});

var sourceStream = new streamBuffers.ReadableStreamBuffer({ chunkSize: 1000 });
sourceStream.put("Hello World!");
us.on('finish', function () {
  sourceStream.destroy();
});

var writableStream = new streamBuffers.WritableStreamBuffer();

sourceStream.pipe(us).pipe(writableStream);

writableStream.once('close', function () {
  var str = writableStream.getContentsAsString('utf8'); //Hello
  console.log('Piped data before pattern occurs:', "'" + str + "'");
  var data = us.read(); // World
  console.log('Next call to read() returns the pattern:', "'" + data.toString() + "'");
});

//Output
//Piped data before pattern occurs: 'Hello'
//Next call to read() returns the pattern: ' World'<commit_msg>Clean up examples<commit_after>var UntilStream = require('../');
var streamBuffers = require("stream-buffers");

var us = new UntilStream({ pattern: 'World'});

var sourceStream = new streamBuffers.ReadableStreamBuffer();
sourceStream.put("Hello World");
us.on('finish', function () {
  sourceStream.destroy();
});

var writableStream = new streamBuffers.WritableStreamBuffer();

sourceStream.pipe(us).pipe(writableStream);

writableStream.once('close', function () {
  var str = writableStream.getContentsAsString('utf8');
  console.log('Piped data before pattern occurs:', "'" + str + "'");
  var data = us.read();
  console.log('Next call to read() returns the pattern:', "'" + data.toString() + "'");
});

//Output
//Piped data before pattern occurs: 'Hello '
//Next call to read() returns the pattern: 'World'<|endoftext|>


<commit_before>/**
 * Cangraph
 *
 * Graphing and function plotting for the HTML5 canvas. Main function plotting
 * engine was taken from the link below and modified.
 *
 * @link http://www.javascripter.net/faq/plotafunctiongraph.htm
 */
(function ($) {

    /**
     * Constructor and initialization
     *
     * @class Cangraph
     *
     * @param {String} canvasId The canvas element to draw on
     * @param {Object} options Allows us to change defaults upon instantiation
     */
    function Cangraph(canvasId, options) {
        var defaults = {
            axes: {
                xOffset: 0,
                yOffset: 0,
                scale: 40,
                showNegativeX: true,
                strokeColor: '#000000'
            },
            graph: {
                strokeColor: '#1fcd38',
                lineWidth: '1',
                scale: 4
            }
        };
        var canvas;

        // Set canvas and context
        this.set('canvasId', canvasId);
        canvas = document.getElementById(this.canvasId);
        this.set('canvas', canvas);
        this.setContext();

        // Merge defaults with passed in options
        this.options = options || {};
        this.options = $.extend(true, {}, defaults, this.options);

        this.setDerivedAxesProperties();
        this.setDerivedGraphProperties();
    }

    Cangraph.prototype.set = function (name, value) {
        if (value === null || typeof value === 'undefined') {
            console.log(name, 'is undefined or null!');

            return false;
        }

        this[name] = value;
    };

    Cangraph.prototype.setContext = function () {
        var context = this.canvas.getContext('2d');

        this.set('context', context);
    };

    Cangraph.prototype.setDerivedAxesProperties = function () {
        this.set('x0', this.options.axes.xOffset + .5 * this.canvas.width);
        this.set('y0', this.options.axes.yOffset + .5 * this.canvas.height);

        if (this.options.axes.showNegativeX) {
            this.set('xMin', 0);
        } else {
            this.set('xMin', this.x0);
        }
    };

    Cangraph.prototype.setDerivedGraphProperties = function () {
        this.set('graphPlottingMax', Math.round((this.canvas.width - this.x0) / this.options.graph.scale));

        if (this.options.axes.showNegativeX) {
            this.set('graphPlottingMin', Math.round(-this.x0 / this.options.graph.scale));
        } else {
            this.set('graphPlottingMin', 0);
        }
    };

    Cangraph.prototype.drawAxes = function (fx) {
        this.context.beginPath();
        this.context.strokeStyle = this.options.axes.strokeColor;
        this.context.moveTo(this.xMin, this.y0);
        this.context.lineTo(this.canvas.width, this.y0);
        this.context.moveTo(this.x0, 0);
        this.context.lineTo(this.x0, this.canvas.height);
        this.context.stroke();
    };

    Cangraph.prototype.drawGraph = function (fx) {
        var x;
        var y;
        var i;

        this.context.beginPath();
        this.context.lineWidth = this.options.graph.lineWidth;
        this.context.strokeStyle = this.options.graph.strokeColor;

        for (i = this.graphPlottingMin; i <= this.graphPlottingMax; i += 1) {
            x = this.options.graph.scale * i;
            y = this.options.axes.scale * fx(x / this.options.axes.scale);

            if (i === this.graphPlottingMin) {
                this.context.moveTo(this.x0 + x, this.y0 - y);
            } else {
                this.context.lineTo(this.x0 + x, this.y0 - y);
            }
        }

        this.context.stroke();
    };

    // Attach object to global namespace
    this.Cangraph = Cangraph;
}).call(this, $);<commit_msg>Allow drawing of each axis conditionally<commit_after>/**
 * Cangraph
 *
 * Graphing and function plotting for the HTML5 canvas. Main function plotting
 * engine was taken from the link below and modified.
 *
 * @link http://www.javascripter.net/faq/plotafunctiongraph.htm
 */
(function ($) {

    /**
     * Constructor and initialization
     *
     * @class Cangraph
     *
     * @param {String} canvasId The canvas element to draw on
     * @param {Object} options Allows us to change defaults upon instantiation
     */
    function Cangraph(canvasId, options) {
        var defaults = {
            axes: {
                xOffset: 0,
                yOffset: 0,
                scale: 40,
                showNegativeX: true,
                strokeColor: '#000000',
                showXAxis: true,
                showYAxis: true
            },
            graph: {
                strokeColor: '#1fcd38',
                lineWidth: '1',
                scale: 4
            }
        };
        var canvas;

        // Set canvas and context
        this.set('canvasId', canvasId);
        canvas = document.getElementById(this.canvasId);
        this.set('canvas', canvas);
        this.setContext();

        // Merge defaults with passed in options
        this.options = options || {};
        this.options = $.extend(true, {}, defaults, this.options);

        this.setDerivedAxesProperties();
        this.setDerivedGraphProperties();
    }

    Cangraph.prototype.set = function (name, value) {
        if (value === null || typeof value === 'undefined') {
            console.log(name, 'is undefined or null!');

            return false;
        }

        this[name] = value;
    };

    Cangraph.prototype.setContext = function () {
        var context = this.canvas.getContext('2d');

        this.set('context', context);
    };

    Cangraph.prototype.setDerivedAxesProperties = function () {
        this.set('x0', this.options.axes.xOffset + .5 * this.canvas.width);
        this.set('y0', this.options.axes.yOffset + .5 * this.canvas.height);

        if (this.options.axes.showNegativeX) {
            this.set('xMin', 0);
        } else {
            this.set('xMin', this.x0);
        }
    };

    Cangraph.prototype.setDerivedGraphProperties = function () {
        this.set('graphPlottingMax', Math.round((this.canvas.width - this.x0) / this.options.graph.scale));

        if (this.options.axes.showNegativeX) {
            this.set('graphPlottingMin', Math.round(-this.x0 / this.options.graph.scale));
        } else {
            this.set('graphPlottingMin', 0);
        }
    };

    Cangraph.prototype.drawAxes = function (fx) {
        this.context.beginPath();
        this.context.strokeStyle = this.options.axes.strokeColor;

        if (this.options.axes.showXAxis) {
            this.context.moveTo(this.xMin, this.y0);
            this.context.lineTo(this.canvas.width, this.y0);
        }

        if (this.options.axes.showYAxis) {
            this.context.moveTo(this.x0, 0);
            this.context.lineTo(this.x0, this.canvas.height);
        }

        this.context.stroke();
    };

    Cangraph.prototype.drawGraph = function (fx) {
        var x;
        var y;
        var i;

        this.context.beginPath();
        this.context.lineWidth = this.options.graph.lineWidth;
        this.context.strokeStyle = this.options.graph.strokeColor;

        for (i = this.graphPlottingMin; i <= this.graphPlottingMax; i += 1) {
            x = this.options.graph.scale * i;
            y = this.options.axes.scale * fx(x / this.options.axes.scale);

            if (i === this.graphPlottingMin) {
                this.context.moveTo(this.x0 + x, this.y0 - y);
            } else {
                this.context.lineTo(this.x0 + x, this.y0 - y);
            }
        }

        this.context.stroke();
    };

    // Attach object to global namespace
    this.Cangraph = Cangraph;
}).call(this, $);<|endoftext|>


<commit_before>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var XHRTestScene = TestScene.extend({
    ctor:function () {
        this._super(true);
        var xhrLayer = new XHRTestLayer();
        this.addChild(xhrLayer);
    },
    runThisTest:function () {
        cc.director.runScene(this);
    },
    MainMenuCallback:function (sender) {
        this._super(sender);
    }
});

var XHRTestLayer = cc.Layer.extend({
    ctor:function () {
        this._super();
    },

    onEnter: function() {
        this._super();
        var l = new cc.LabelTTF("Get infos via XHR", "Thonburi", 16);
        this.addChild(l, 1);
        l.x = winSize.width / 2;
        l.y = winSize.height - 60;

        this.sendGetRequest();
        this.sendPostPlainText();
        this.sendPostForms();
    },

    sendGetRequest: function() {
        var that = this;
        var xhr = cc.loader.getXMLHttpRequest();
        var statusGetLabel = new cc.LabelTTF("Status:", "Thonburi", 18);
        this.addChild(statusGetLabel, 1);
        statusGetLabel.x = winSize.width / 2;
        statusGetLabel.y = winSize.height - 100;
        statusGetLabel.setString("Status: Send Get Request to httpbin.org");
        //set arguments with <URL>?xxx=xxx&yyy=yyy
        xhr.open("GET", "http://httpbin.org/get?show_env=1", true);

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                var httpStatus = xhr.statusText;
                var response = xhr.responseText.substring(0, 100) + "...";
                var responseLabel = new cc.LabelTTF("GET Response (100 chars): \n" + response, "Thonburi", 16);
                that.addChild(responseLabel, 1);
                responseLabel.anchorX = 0;
                responseLabel.anchorY = 1;
                responseLabel.textAlign = cc.TEXT_ALIGNMENT_LEFT;

                responseLabel.x = 10;
                responseLabel.y = winSize.height / 2;
                statusGetLabel.setString("Status: Got GET response! " + httpStatus);
            }
        };
        xhr.send();
    },

    sendPostPlainText: function() {
        var that = this;
        var xhr = cc.loader.getXMLHttpRequest();
        var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 18);
        this.addChild(statusPostLabel, 1);

        statusPostLabel.x = winSize.width / 2;

        statusPostLabel.y = winSize.height - 140;
        statusPostLabel.setString("Status: Send Post Request to httpbin.org with plain text");

        xhr.open("POST", "http://httpbin.org/post");
        //set Content-type "text/plain;charset=UTF-8" to post plain text
        xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                var httpStatus = xhr.statusText;
                var response = xhr.responseText.substring(0, 100) + "...";
                var responseLabel = new cc.LabelTTF("POST Response (100 chars):  \n" + response, "Thonburi", 16);
                that.addChild(responseLabel, 1);
                responseLabel.anchorX = 0;
                responseLabel.anchorY = 1;
                responseLabel.textAlign = cc.TEXT_ALIGNMENT_LEFT;

                responseLabel.x = winSize.width / 10 * 3;
                responseLabel.y = winSize.height / 2;
                statusPostLabel.setString("Status: Got POST response! " + httpStatus);
            }
        };
        xhr.send("plain text message");
    },

    sendPostForms: function() {
        var that = this;
        var xhr = cc.loader.getXMLHttpRequest();
        var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 18);
        this.addChild(statusPostLabel, 1);

        statusPostLabel.x = winSize.width / 2;

        statusPostLabel.y = winSize.height - 180;
        statusPostLabel.setString("Status: Send Post Request to httpbin.org width form data");

        xhr.open("POST", "http://httpbin.org/post");
        //set Content-Type "application/x-www-form-urlencoded" to post form data
        //mulipart/form-data for upload
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
                var httpStatus = xhr.statusText;
                var response = xhr.responseText.substring(0, 100) + "...";
                var responseLabel = new cc.LabelTTF("POST Response (100 chars):  \n" + response, "Thonburi", 16);
                that.addChild(responseLabel, 1);
                responseLabel.anchorX = 0;
                responseLabel.anchorY = 1;
                responseLabel.textAlign = cc.TEXT_ALIGNMENT_LEFT;

                responseLabel.x = winSize.width / 10 * 7;
                responseLabel.y = winSize.height / 2;
                statusPostLabel.setString("Status: Got POST response! " + httpStatus);
            }
        };
        /**
        form : {
            "a" : "hello",
            "b" : "world"
        }
        **/
        var args = "a=hello&b=world";
        xhr.send(args);

    },

    scrollViewDidScroll:function (view) {
    },
    scrollViewDidZoom:function (view) {
    }
});

var runXHRTest = function () {
    var pScene = new cc.Scene();
    var pLayer = new XHRTestLayer();
    pScene.addChild(pLayer);
    cc.director.runScene(pScene);
};
<commit_msg>added some events to XHRTest<commit_after>/****************************************************************************
 Copyright (c) 2008-2010 Ricardo Quesada
 Copyright (c) 2011-2012 cocos2d-x.org
 Copyright (c) 2013-2014 Chukong Technologies Inc.

 http://www.cocos2d-x.org

 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.
 ****************************************************************************/

//some utils functions
function ensureLeftAligned (label) {
    label.anchorX = 0;
    label.anchorY = 1;
    label.textAlign = cc.TEXT_ALIGNMENT_LEFT;
}

function streamXHREventsToLabel ( xhr, label, textbox, method ) {
    // Simple events
    ['loadstart', 'abort', 'error', 'load', 'loadend'].forEach(function (eventname) {
        xhr["on" + eventname] = function () {
            label.string += "\nEvent : " + eventname
        }
    });

    // Special event
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
            var httpStatus = xhr.statusText;
            var response = xhr.responseText.substring(0, 100) + "...";
            textbox.string = method + " Response (100 chars):\n"
            textbox.string += response
            label.string += "\nStatus: Got " + method + " response! " + httpStatus
        }
    }
}

var XHRTestScene = TestScene.extend({
    ctor:function () {
        this._super(true);
        var xhrLayer = new XHRTestLayer();
        this.addChild(xhrLayer);
    },
    runThisTest:function () {
        cc.director.runScene(this);
    },
    MainMenuCallback:function (sender) {
        this._super(sender);
    }
});

var XHRTestLayer = cc.Layer.extend({
    ctor:function () {
        this._super();
    },

    onEnter: function() {
        this._super();
        var l = new cc.LabelTTF("Get infos via XHR", "Thonburi", 16);
        this.addChild(l, 1);
        l.x = winSize.width / 2;
        l.y = winSize.height - 60;

        this.sendGetRequest();
        this.sendPostPlainText();
        this.sendPostForms();
    },

    sendGetRequest: function() {
        var statusGetLabel = new cc.LabelTTF("Status:", "Thonburi", 12);
        this.addChild(statusGetLabel, 1);

        statusGetLabel.x = 10
        statusGetLabel.y = winSize.height - 100;
        ensureLeftAligned(statusGetLabel);
        statusGetLabel.setString("Status: Send Get Request to httpbin.org");

        var responseLabel = new cc.LabelTTF("", "Thonburi", 16);
        this.addChild(responseLabel, 1);

        ensureLeftAligned(responseLabel);
        responseLabel.x = 10;
        responseLabel.y = winSize.height / 2;

        var xhr = cc.loader.getXMLHttpRequest();
        //set arguments with <URL>?xxx=xxx&yyy=yyy
        xhr.open("GET", "http://httpbin.org/get?show_env=1", true);
        xhr.send();

        streamXHREventsToLabel(xhr, statusGetLabel, responseLabel, "GET");
    },

    sendPostPlainText: function() {
        var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12);
        this.addChild(statusPostLabel, 1);

        statusPostLabel.x = winSize.width / 10 * 3;
        statusPostLabel.y = winSize.height - 100;
        ensureLeftAligned(statusPostLabel);
        statusPostLabel.setString("Status: Send Post Request to httpbin.org with plain text");

        var responseLabel = new cc.LabelTTF("", "Thonburi", 16);
        this.addChild(responseLabel, 1);
        ensureLeftAligned(responseLabel);
        responseLabel.x = winSize.width / 10 * 3;
        responseLabel.y = winSize.height / 2;

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", "http://httpbin.org/post");
        //set Content-type "text/plain;charset=UTF-8" to post plain text
        xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
        xhr.send("plain text message");

        streamXHREventsToLabel(xhr, statusPostLabel, responseLabel, "POST");
    },

    sendPostForms: function() {
        var statusPostLabel = new cc.LabelTTF("Status:", "Thonburi", 12);
        this.addChild(statusPostLabel, 1);

        statusPostLabel.x = winSize.width / 10 * 7;
        statusPostLabel.y = winSize.height - 100;
        ensureLeftAligned(statusPostLabel);
        statusPostLabel.setString("Status: Send Post Request to httpbin.org width form data");

        var responseLabel = new cc.LabelTTF("", "Thonburi", 16);
        this.addChild(responseLabel, 1);

        ensureLeftAligned(responseLabel);
        responseLabel.x = winSize.width / 10 * 7;
        responseLabel.y = winSize.height / 2;

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", "http://httpbin.org/post");
        //set Content-Type "application/x-www-form-urlencoded" to post form data
        //mulipart/form-data for upload
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        /**
        form : {
            "a" : "hello",
            "b" : "world"
        }
        **/
        var args = "a=hello&b=world";
        xhr.send(args);

        streamXHREventsToLabel(xhr, statusPostLabel, responseLabel, "POST");
    },

    scrollViewDidScroll:function (view) {
    },
    scrollViewDidZoom:function (view) {
    }
});

var runXHRTest = function () {
    var pScene = new cc.Scene();
    var pLayer = new XHRTestLayer();
    pScene.addChild(pLayer);
    cc.director.runScene(pScene);
};
<|endoftext|>


<commit_before>import Axios from 'axios';
const axios = Axios.create({ timeout: 30000 });
import buildURL from 'axios/lib/helpers/buildURL.js';
import combineURLs from 'axios/lib/helpers/combineURLs.js';
import axiosRetry from 'axios-retry';
import LS from 'lib/wallet/localStorage';
import { showError } from 'widgets/modals/flash';
import { translate } from 'lib/i18n';
import { eddsa } from 'elliptic';
const ec = new eddsa('ed25519');
import crypto from 'crypto';
import seeds from 'lib/wallet/seeds';

axiosRetry(axios, { retries: 3, retryDelay: axiosRetry.exponentialDelay, shouldResetTimeout: true });

const URLS = [
  process.env.SITE_URL,
  process.env.API_BTC_URL,
  process.env.API_BCH_URL,
  process.env.API_BSV_URL,
  process.env.API_LTC_URL,
  process.env.API_ETH_URL,
  process.env.API_XRP_URL,
  process.env.API_XLM_URL,
  process.env.API_EOS_URL,
  process.env.API_DOGE_URL,
  process.env.API_DASH_URL,
  process.env.API_XMR_URL,
];

axios.interceptors.request.use((config) => {
  if (config.intercepted === true) {
    return config;
  }
  if (config.baseURL) {
    config.url = combineURLs(config.baseURL, config.url);
    delete config.baseURL;
  }
  if (!URLS.some((item) => config.url.startsWith(item))) {
    config.intercepted = true;
    return config;
  }
  if (!config.method) {
    config.method = 'get';
  }

  if ((config.seed && config.id !== false) || config.id === true) {
    // object spread not supported
    config.params = Object.assign({
      id: LS.getId(),
    }, config.params);
  }

  if (config.params) {
    config.url = buildURL(config.url, config.params);
    delete config.params;
  }

  const date = (new Date()).toUTCString();
  config.headers = config.headers || {};
  config.headers['X-Release'] = process.env.RELEASE;
  config.headers['X-Date'] = date;

  if (config.seed) {
    const secret = seeds.get(config.seed);
    const privateKey = ec.keyFromSecret(secret);

    const body = config.data && JSON.stringify(config.data);
    const base = [
      config.method,
      config.url,
      date,
      process.env.RELEASE,
    ];
    if (config.method !== 'get' && body) {
      base.push(crypto.createHash('sha256').update(body).digest().toString('hex'));
    }
    const signature = privateKey.sign(Buffer.from(base.join(' '))).toHex();
    config.headers['Signature'] = signature;
  }

  config.intercepted = true;
  return config;
});

function request(config = {}) {
  return axios.request(config)
    .then((response) => {
      return response.data;
    })
    .catch((err) => {
      // TODO handle 401
      if (config.disableDefaultCatch) {
        throw err;
      }
      if (err.response) {
        const error = new Error(err.response.data.error || err.response.data.message || err.response.data);
        error.status = err.response.status;
        error.url = err.config.url;
        error.method = err.config.method;
        throw error;
      } else if (err.request) {
        if (!config.hideFlashError) {
          showError({ message: translate('Request timeout. Please check your internet connection.') });
        }
        throw err;
      } else {
        throw err;
      }
    });
}

export default request;
<commit_msg>fix: request for bsc<commit_after>import Axios from 'axios';
const axios = Axios.create({ timeout: 30000 });
import buildURL from 'axios/lib/helpers/buildURL.js';
import combineURLs from 'axios/lib/helpers/combineURLs.js';
import axiosRetry from 'axios-retry';
import LS from 'lib/wallet/localStorage';
import { showError } from 'widgets/modals/flash';
import { translate } from 'lib/i18n';
import { eddsa } from 'elliptic';
const ec = new eddsa('ed25519');
import crypto from 'crypto';
import seeds from 'lib/wallet/seeds';

axiosRetry(axios, { retries: 3, retryDelay: axiosRetry.exponentialDelay, shouldResetTimeout: true });

const URLS = [
  process.env.SITE_URL,
  process.env.API_BTC_URL,
  process.env.API_BCH_URL,
  process.env.API_BSV_URL,
  process.env.API_LTC_URL,
  process.env.API_ETH_URL,
  process.env.API_XRP_URL,
  process.env.API_XLM_URL,
  process.env.API_EOS_URL,
  process.env.API_DOGE_URL,
  process.env.API_DASH_URL,
  process.env.API_XMR_URL,
  process.env.API_BSC_URL,
];

axios.interceptors.request.use((config) => {
  if (config.intercepted === true) {
    return config;
  }
  if (config.baseURL) {
    config.url = combineURLs(config.baseURL, config.url);
    delete config.baseURL;
  }
  if (!URLS.some((item) => config.url.startsWith(item))) {
    config.intercepted = true;
    return config;
  }
  if (!config.method) {
    config.method = 'get';
  }

  if ((config.seed && config.id !== false) || config.id === true) {
    // object spread not supported
    config.params = Object.assign({
      id: LS.getId(),
    }, config.params);
  }

  if (config.params) {
    config.url = buildURL(config.url, config.params);
    delete config.params;
  }

  const date = (new Date()).toUTCString();
  config.headers = config.headers || {};
  config.headers['X-Release'] = process.env.RELEASE;
  config.headers['X-Date'] = date;

  if (config.seed) {
    const secret = seeds.get(config.seed);
    const privateKey = ec.keyFromSecret(secret);

    const body = config.data && JSON.stringify(config.data);
    const base = [
      config.method,
      config.url,
      date,
      process.env.RELEASE,
    ];
    if (config.method !== 'get' && body) {
      base.push(crypto.createHash('sha256').update(body).digest().toString('hex'));
    }
    const signature = privateKey.sign(Buffer.from(base.join(' '))).toHex();
    config.headers['Signature'] = signature;
  }

  config.intercepted = true;
  return config;
});

function request(config = {}) {
  return axios.request(config)
    .then((response) => {
      return response.data;
    })
    .catch((err) => {
      // TODO handle 401
      if (config.disableDefaultCatch) {
        throw err;
      }
      if (err.response) {
        const error = new Error(err.response.data.error || err.response.data.message || err.response.data);
        error.status = err.response.status;
        error.url = err.config.url;
        error.method = err.config.method;
        throw error;
      } else if (err.request) {
        if (!config.hideFlashError) {
          showError({ message: translate('Request timeout. Please check your internet connection.') });
        }
        throw err;
      } else {
        throw err;
      }
    });
}

export default request;
<|endoftext|>


<commit_before>import Immutable from "immutable";
import R from "ramda";
import {allSensorsDecorator} from "lib/sensors-decorators";
import * as f from "iwwa-formula-resolver";

const operatorMapping = {
    "+" : "add",
    "-" : "minus",
    "*" : "multiply",
    "/" : "divide",
    "(" : "open-braket",
    ")" : "close-braket",
    "^" : "circumflex",
    "sqrt" : "square-root",
    [f.TOTALIZATOR]: "delta",
    [f.A_1Y_FORWARD_SHIFT]: "add-1y",
    [f.A_1M_FORWARD_SHIFT]: "add-1m",
    [f.A_1W_FORWARD_SHIFT]: "add-1w",
    [f.A_1D_FORWARD_SHIFT]: "add-1d",
    [f.A_15MIN_FORWARD_SHIFT]: "add-15m",
    [f.A_1Y_BACKWARD_SHIFT]: "remove-1y",
    [f.A_1M_BACKWARD_SHIFT]: "remove-1m",
    [f.A_1W_BACKWARD_SHIFT]: "remove-1w",
    [f.A_1D_BACKWARD_SHIFT]: "remove-1d",
    [f.A_15MIN_BACKWARD_SHIFT]: "remove-15m"
};

export const potentialUnitsOfMeasurement = [
    {value: "#", label: "#"},
    {value: "%", label: "%"},
    {value: "€", label: "€"},
    {value: "€/kSm³", label: "€/kSm³"},
    {value: "€/kWh", label: "€/kWh"},
    {value: "€/MWh", label: "€/MWh"},
    {value: "€/Sm³", label: "€/Sm³"},
    {value: "°C", label: "°C"},
    {value: "°F", label: "°F"},
    {value: "µg", label: "µg"},
    {value: "A", label: "A"},
    {value: "atm", label: "atm"},
    {value: "bar", label: "bar"},
    {value: "barg", label: "barg"},
    {value: "BTU", label: "BTU"},
    {value: "cal", label: "cal"},
    {value: "cm²", label: "cm²"},
    {value: "g", label: "g"},
    {value: "GW", label: "GW"},
    {value: "GWh", label: "GWh"},
    {value: "hPa", label: "hPa"},
    {value: "Hz", label: "Hz"},
    {value: "J", label: "J"},
    {value: "K", label: "K"},
    {value: "kcal", label: "kcal"},
    {value: "kg", label: "kg"},
    {value: "kg/m³", label: "kg/m³"},
    {value: "kg/s", label: "kg/s"},
    {value: "KHz", label: "KHz"},
    {value: "KJ", label: "KJ"},
    {value: "km/h", label: "km/h"},
    {value: "km²", label: "km²"},
    {value: "kSm³", label: "kSm³"},
    {value: "kV", label: "kV"},
    {value: "kW", label: "kW"},
    {value: "kWh", label: "kWh"},
    {value: "l", label: "l"},
    {value: "l/h", label: "l/h"},
    {value: "l/s", label: "l/s"},
    {value: "lm", label: "lm"},
    {value: "lx", label: "lx"},
    {value: "m/s", label: "m/s"},
    {value: "m/s2", label: "m/s2"},
    {value: "m²", label: "m²"},
    {value: "m³", label: "m³"},
    {value: "m³/h", label: "m³/h"},
    {value: "mbar", label: "mbar"},
    {value: "mg", label: "mg"},
    {value: "mg/Nm³", label: "mg/Nm³"},
    {value: "MHz", label: "MHz"},
    {value: "min", label: "min"},
    {value: "mm²", label: "mm²"},
    {value: "MW", label: "MW"},
    {value: "MWh", label: "MWh"},
    {value: "Nm³", label: "Nm³"},
    {value: "ora", label: "ora"},
    {value: "Pa", label: "Pa"},
    {value: "ppm", label: "ppm"},
    {value: "Psi", label: "Psi"},
    {value: "s", label: "s"},
    {value: "Sm³", label: "Sm³"},
    {value: "Sm³/h", label: "Sm³/h"},
    {value: "ton", label: "ton"},
    {value: "Torr", label: "Torr"},
    {value: "V", label: "V"},
    {value: "W", label: "W"},
    {value: "Wh", label: "Wh"}
];

export function getUnitOfMeasurementLabel (val) {
    return R.find(R.propEq("value", val))(potentialUnitsOfMeasurement).label;
}

function swap (json) {
    var ret = {};
    for (var key in json) {
        ret[json[key]] = key;
    }
    return ret;
}

export const formulaToOperator = operatorMapping;
export const operatorToFormula = swap(operatorMapping);

export function findSensor (sensors, sensorId) {
    return sensors.get(sensorId);
}

export function getSensorLabel (sensor) {
    return sensor.get("name") ? sensor.get("name") : getSensorId(sensor);
}

export function getSensorId (sensor) {
    return sensor.get("_id") + (sensor.get("measurementType") ? "-" + sensor.get("measurementType") : "");
}

export function extractSensorsFromFormula (sensor, allSensors, extractedSensors = []) {
    if (sensor.get("formulas") && sensor.get("formulas").size > 0) {
        sensor.get("formulas").forEach(formula => {
            formula.get("variables").forEach(item => {
                extractSensorsFromFormula(allSensors.get(item), allSensors, extractedSensors);
            });
        })
    } else {
        extractedSensors.push(sensor);
    }
    return extractedSensors;
}

export function reduceFormula (sensor, allSensors) {
    if (!sensor.get("formulas")) {
        return null;
    }
    const result = reduceFormulaData(sensor, allSensors);
    const formula = sensor.get("formulas").first();
    return Immutable.Map({
        formula: result.formula,
        variables: result.variables,
        start: formula.get("start"),
        end: formula.get("end"),
        measurementType: formula.get("measurementType")
    });
}

function reduceFormulaData (sensor, allSensors, variables = [], formula) {
    const sensorFormula = sensor.get("formulas") ? sensor.get("formulas").first() : null;
    if (sensorFormula) {
        formula = sensorFormula.get("formula");
        sensorFormula.get("variables").forEach(item => {
            const reduced = reduceFormulaData(allSensors.get(item), allSensors, variables, formula);
            if (reduced.formula) {
                formula = sensorFormula.get("formula").replace(new RegExp(item, 'g'), reduced.formula)
            }
        });
    } else {
        formula = null;
        variables.push(getSensorId(sensor));
    }
    return {
        variables,
        formula
    };
}

export function getAllSensors (sensorsCollection) {
    if (!sensorsCollection) {
        return Immutable.Map();
    }
    return decorateWithMeasurementType(sensorsCollection, []);
}

export function getMonitoringSensors (sensorsCollection) {
    if (!sensorsCollection) {
        return Immutable.Map();
    }
    let originalToHide = [];
    sensorsCollection.forEach(sensor => {
        let parentId = sensor.get("parentSensorId");
        if (!sensor.get("isDeleted") && parentId) {
            originalToHide.push(parentId);
        }
    });
    return decorateWithMeasurementType(sensorsCollection.filter(
        sensor => !sensor.get("isDeleted") &&
        sensor.get("type") !== "pod"
    ), originalToHide);
}

function decorateWithMeasurementType (sensors, originalToHide) {
    let items = {};
    let fakeTheme = {
        colors: {}
    };
    sensors.forEach(sensor => {
        let types = R.filter(R.propEq("type", sensor.get("type")))(allSensorsDecorator(fakeTheme));
        if (types.length > 0) {
            types.forEach(type => {
                let measurementType = type.key;
                let itemKey = sensor.get("_id") + "-" + measurementType;
                if (originalToHide.indexOf(itemKey) < 0) {
                    items[itemKey] = sensor.set("measurementType", measurementType);
                }
            });
        } else {
            items[sensor.get("_id")] = sensor;
        }
    });
    return Immutable.fromJS(items);
}<commit_msg>fix lint<commit_after>import Immutable from "immutable";
import R from "ramda";
import {allSensorsDecorator} from "lib/sensors-decorators";
import * as f from "iwwa-formula-resolver";

const operatorMapping = {
    "+" : "add",
    "-" : "minus",
    "*" : "multiply",
    "/" : "divide",
    "(" : "open-braket",
    ")" : "close-braket",
    "^" : "circumflex",
    "sqrt" : "square-root",
    [f.TOTALIZATOR]: "delta",
    [f.A_1Y_FORWARD_SHIFT]: "add-1y",
    [f.A_1M_FORWARD_SHIFT]: "add-1m",
    [f.A_1W_FORWARD_SHIFT]: "add-1w",
    [f.A_1D_FORWARD_SHIFT]: "add-1d",
    [f.A_15MIN_FORWARD_SHIFT]: "add-15m",
    [f.A_1Y_BACKWARD_SHIFT]: "remove-1y",
    [f.A_1M_BACKWARD_SHIFT]: "remove-1m",
    [f.A_1W_BACKWARD_SHIFT]: "remove-1w",
    [f.A_1D_BACKWARD_SHIFT]: "remove-1d",
    [f.A_15MIN_BACKWARD_SHIFT]: "remove-15m"
};

export const potentialUnitsOfMeasurement = [
    {value: "#", label: "#"},
    {value: "%", label: "%"},
    {value: "€", label: "€"},
    {value: "€/kSm³", label: "€/kSm³"},
    {value: "€/kWh", label: "€/kWh"},
    {value: "€/MWh", label: "€/MWh"},
    {value: "€/Sm³", label: "€/Sm³"},
    {value: "°C", label: "°C"},
    {value: "°F", label: "°F"},
    {value: "µg", label: "µg"},
    {value: "A", label: "A"},
    {value: "atm", label: "atm"},
    {value: "bar", label: "bar"},
    {value: "barg", label: "barg"},
    {value: "BTU", label: "BTU"},
    {value: "cal", label: "cal"},
    {value: "cm²", label: "cm²"},
    {value: "g", label: "g"},
    {value: "GW", label: "GW"},
    {value: "GWh", label: "GWh"},
    {value: "hPa", label: "hPa"},
    {value: "Hz", label: "Hz"},
    {value: "J", label: "J"},
    {value: "K", label: "K"},
    {value: "kcal", label: "kcal"},
    {value: "kg", label: "kg"},
    {value: "kg/m³", label: "kg/m³"},
    {value: "kg/s", label: "kg/s"},
    {value: "KHz", label: "KHz"},
    {value: "KJ", label: "KJ"},
    {value: "km/h", label: "km/h"},
    {value: "km²", label: "km²"},
    {value: "kSm³", label: "kSm³"},
    {value: "kV", label: "kV"},
    {value: "kW", label: "kW"},
    {value: "kWh", label: "kWh"},
    {value: "l", label: "l"},
    {value: "l/h", label: "l/h"},
    {value: "l/s", label: "l/s"},
    {value: "lm", label: "lm"},
    {value: "lx", label: "lx"},
    {value: "m/s", label: "m/s"},
    {value: "m/s2", label: "m/s2"},
    {value: "m²", label: "m²"},
    {value: "m³", label: "m³"},
    {value: "m³/h", label: "m³/h"},
    {value: "mbar", label: "mbar"},
    {value: "mg", label: "mg"},
    {value: "mg/Nm³", label: "mg/Nm³"},
    {value: "MHz", label: "MHz"},
    {value: "min", label: "min"},
    {value: "mm²", label: "mm²"},
    {value: "MW", label: "MW"},
    {value: "MWh", label: "MWh"},
    {value: "Nm³", label: "Nm³"},
    {value: "ora", label: "ora"},
    {value: "Pa", label: "Pa"},
    {value: "ppm", label: "ppm"},
    {value: "Psi", label: "Psi"},
    {value: "s", label: "s"},
    {value: "Sm³", label: "Sm³"},
    {value: "Sm³/h", label: "Sm³/h"},
    {value: "ton", label: "ton"},
    {value: "Torr", label: "Torr"},
    {value: "V", label: "V"},
    {value: "W", label: "W"},
    {value: "Wh", label: "Wh"}
];

export function getUnitOfMeasurementLabel (val) {
    return R.find(R.propEq("value", val))(potentialUnitsOfMeasurement).label;
}

function swap (json) {
    var ret = {};
    for (var key in json) {
        ret[json[key]] = key;
    }
    return ret;
}

export const formulaToOperator = operatorMapping;
export const operatorToFormula = swap(operatorMapping);

export function findSensor (sensors, sensorId) {
    return sensors.get(sensorId);
}

export function getSensorLabel (sensor) {
    return sensor.get("name") ? sensor.get("name") : getSensorId(sensor);
}

export function getSensorId (sensor) {
    return sensor.get("_id") + (sensor.get("measurementType") ? "-" + sensor.get("measurementType") : "");
}

export function extractSensorsFromFormula (sensor, allSensors, extractedSensors = []) {
    if (sensor.get("formulas") && sensor.get("formulas").size > 0) {
        sensor.get("formulas").forEach(formula => {
            formula.get("variables").forEach(item => {
                extractSensorsFromFormula(allSensors.get(item), allSensors, extractedSensors);
            });
        });
    } else {
        extractedSensors.push(sensor);
    }
    return extractedSensors;
}

export function reduceFormula (sensor, allSensors) {
    if (!sensor.get("formulas")) {
        return null;
    }
    const result = reduceFormulaData(sensor, allSensors);
    const formula = sensor.get("formulas").first();
    return Immutable.Map({
        formula: result.formula,
        variables: result.variables,
        start: formula.get("start"),
        end: formula.get("end"),
        measurementType: formula.get("measurementType")
    });
}

function reduceFormulaData (sensor, allSensors, variables = [], formula) {
    const sensorFormula = sensor.get("formulas") ? sensor.get("formulas").first() : null;
    if (sensorFormula) {
        formula = sensorFormula.get("formula");
        sensorFormula.get("variables").forEach(item => {
            const reduced = reduceFormulaData(allSensors.get(item), allSensors, variables, formula);
            if (reduced.formula) {
                formula = sensorFormula.get("formula").replace(new RegExp(item, "g"), reduced.formula);
            }
        });
    } else {
        formula = null;
        variables.push(getSensorId(sensor));
    }
    return {
        variables,
        formula
    };
}

export function getAllSensors (sensorsCollection) {
    if (!sensorsCollection) {
        return Immutable.Map();
    }
    return decorateWithMeasurementType(sensorsCollection, []);
}

export function getMonitoringSensors (sensorsCollection) {
    if (!sensorsCollection) {
        return Immutable.Map();
    }
    let originalToHide = [];
    sensorsCollection.forEach(sensor => {
        let parentId = sensor.get("parentSensorId");
        if (!sensor.get("isDeleted") && parentId) {
            originalToHide.push(parentId);
        }
    });
    return decorateWithMeasurementType(sensorsCollection.filter(
        sensor => !sensor.get("isDeleted") &&
        sensor.get("type") !== "pod"
    ), originalToHide);
}

function decorateWithMeasurementType (sensors, originalToHide) {
    let items = {};
    let fakeTheme = {
        colors: {}
    };
    sensors.forEach(sensor => {
        let types = R.filter(R.propEq("type", sensor.get("type")))(allSensorsDecorator(fakeTheme));
        if (types.length > 0) {
            types.forEach(type => {
                let measurementType = type.key;
                let itemKey = sensor.get("_id") + "-" + measurementType;
                if (originalToHide.indexOf(itemKey) < 0) {
                    items[itemKey] = sensor.set("measurementType", measurementType);
                }
            });
        } else {
            items[sensor.get("_id")] = sensor;
        }
    });
    return Immutable.fromJS(items);
}<|endoftext|>