text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _utils = require('./utils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint prefer-template: 0 */

var Dropzone = function (_React$Component) {
  _inherits(Dropzone, _React$Component);

  function Dropzone(props, context) {
    _classCallCheck(this, Dropzone);

    var _this = _possibleConstructorReturn(this, (Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this, props, context));

    _this.renderChildren = function (children, isDragActive, isDragAccept, isDragReject) {
      if (typeof children === 'function') {
        return children(_extends({}, _this.state, {
          isDragActive: isDragActive,
          isDragAccept: isDragAccept,
          isDragReject: isDragReject
        }));
      }
      return children;
    };

    _this.composeHandlers = _this.composeHandlers.bind(_this);
    _this.onClick = _this.onClick.bind(_this);
    _this.onDocumentDrop = _this.onDocumentDrop.bind(_this);
    _this.onDragEnter = _this.onDragEnter.bind(_this);
    _this.onDragLeave = _this.onDragLeave.bind(_this);
    _this.onDragOver = _this.onDragOver.bind(_this);
    _this.onDragStart = _this.onDragStart.bind(_this);
    _this.onDrop = _this.onDrop.bind(_this);
    _this.onFileDialogCancel = _this.onFileDialogCancel.bind(_this);
    _this.onInputElementClick = _this.onInputElementClick.bind(_this);

    _this.setRef = _this.setRef.bind(_this);
    _this.setRefs = _this.setRefs.bind(_this);

    _this.isFileDialogActive = false;

    _this.state = {
      draggedFiles: [],
      acceptedFiles: [],
      rejectedFiles: []
    };
    return _this;
  }

  _createClass(Dropzone, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;

      this.dragTargets = [];

      if (preventDropOnDocument) {
        document.addEventListener('dragover', _utils.onDocumentDragOver, false);
        document.addEventListener('drop', this.onDocumentDrop, false);
      }
      this.fileInputEl.addEventListener('click', this.onInputElementClick, false);
      // Tried implementing addEventListener, but didn't work out
      document.body.onfocus = this.onFileDialogCancel;
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var preventDropOnDocument = this.props.preventDropOnDocument;

      if (preventDropOnDocument) {
        document.removeEventListener('dragover', _utils.onDocumentDragOver);
        document.removeEventListener('drop', this.onDocumentDrop);
      }
      this.fileInputEl.removeEventListener('click', this.onInputElementClick, false);
      // Can be replaced with removeEventListener, if addEventListener works
      document.body.onfocus = null;
    }
  }, {
    key: 'composeHandlers',
    value: function composeHandlers(handler) {
      if (this.props.disabled) {
        return null;
      }

      return handler;
    }
  }, {
    key: 'onDocumentDrop',
    value: function onDocumentDrop(evt) {
      if (this.node && this.node.contains(evt.target)) {
        // if we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
        return;
      }
      evt.preventDefault();
      this.dragTargets = [];
    }
  }, {
    key: 'onDragStart',
    value: function onDragStart(evt) {
      if (this.props.onDragStart) {
        this.props.onDragStart.call(this, evt);
      }
    }
  }, {
    key: 'onDragEnter',
    value: function onDragEnter(evt) {
      evt.preventDefault();

      // Count the dropzone and any children that are entered.
      if (this.dragTargets.indexOf(evt.target) === -1) {
        this.dragTargets.push(evt.target);
      }

      this.setState({
        isDragActive: true, // Do not rely on files for the drag state. It doesn't work in Safari.
        draggedFiles: (0, _utils.getDataTransferItems)(evt)
      });

      if (this.props.onDragEnter) {
        this.props.onDragEnter.call(this, evt);
      }
    }
  }, {
    key: 'onDragOver',
    value: function onDragOver(evt) {
      // eslint-disable-line class-methods-use-this
      evt.preventDefault();
      evt.stopPropagation();
      try {
        evt.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign
      } catch (err) {
        // continue regardless of error
      }

      if (this.props.onDragOver) {
        this.props.onDragOver.call(this, evt);
      }
      return false;
    }
  }, {
    key: 'onDragLeave',
    value: function onDragLeave(evt) {
      var _this2 = this;

      evt.preventDefault();

      // Only deactivate once the dropzone and all children have been left.
      this.dragTargets = this.dragTargets.filter(function (el) {
        return el !== evt.target && _this2.node.contains(el);
      });
      if (this.dragTargets.length > 0) {
        return;
      }

      // Clear dragging files state
      this.setState({
        isDragActive: false,
        draggedFiles: []
      });

      if (this.props.onDragLeave) {
        this.props.onDragLeave.call(this, evt);
      }
    }
  }, {
    key: 'onDrop',
    value: function onDrop(evt) {
      var _this3 = this;

      var _props = this.props,
          onDrop = _props.onDrop,
          onDropAccepted = _props.onDropAccepted,
          onDropRejected = _props.onDropRejected,
          multiple = _props.multiple,
          disablePreview = _props.disablePreview,
          accept = _props.accept;

      var fileList = (0, _utils.getDataTransferItems)(evt);
      var acceptedFiles = [];
      var rejectedFiles = [];

      // Stop default browser behavior
      evt.preventDefault();

      // Reset the counter along with the drag on a drop.
      this.dragTargets = [];
      this.isFileDialogActive = false;

      fileList.forEach(function (file) {
        if (!disablePreview) {
          try {
            file.preview = window.URL.createObjectURL(file); // eslint-disable-line no-param-reassign
          } catch (err) {
            if (process.env.NODE_ENV !== 'production') {
              console.error('Failed to generate preview for file', file, err); // eslint-disable-line no-console
            }
          }
        }

        if ((0, _utils.fileAccepted)(file, accept) && (0, _utils.fileMatchSize)(file, _this3.props.maxSize, _this3.props.minSize)) {
          acceptedFiles.push(file);
        } else {
          rejectedFiles.push(file);
        }
      });

      if (!multiple) {
        // if not in multi mode add any extra accepted files to rejected.
        // This will allow end users to easily ignore a multi file drop in "single" mode.
        rejectedFiles.push.apply(rejectedFiles, _toConsumableArray(acceptedFiles.splice(1)));
      }

      if (onDrop) {
        onDrop.call(this, acceptedFiles, rejectedFiles, evt);
      }

      if (rejectedFiles.length > 0 && onDropRejected) {
        onDropRejected.call(this, rejectedFiles, evt);
      }

      if (acceptedFiles.length > 0 && onDropAccepted) {
        onDropAccepted.call(this, acceptedFiles, evt);
      }

      // Clear files value
      this.draggedFiles = null;

      // Reset drag state
      this.setState({
        isDragActive: false,
        draggedFiles: [],
        acceptedFiles: acceptedFiles,
        rejectedFiles: rejectedFiles
      });
    }
  }, {
    key: 'onClick',
    value: function onClick(evt) {
      var _props2 = this.props,
          onClick = _props2.onClick,
          disableClick = _props2.disableClick;

      if (!disableClick) {
        evt.stopPropagation();

        if (onClick) {
          onClick.call(this, evt);
        }

        // in IE11/Edge the file-browser dialog is blocking, ensure this is behind setTimeout
        // this is so react can handle state changes in the onClick prop above above
        // see: https://github.com/react-dropzone/react-dropzone/issues/450
        setTimeout(this.open.bind(this), 0);
      }
    }
  }, {
    key: 'onInputElementClick',
    value: function onInputElementClick(evt) {
      evt.stopPropagation();
      if (this.props.inputProps && this.props.inputProps.onClick) {
        this.props.inputProps.onClick();
      }
    }
  }, {
    key: 'onFileDialogCancel',
    value: function onFileDialogCancel() {
      // timeout will not recognize context of this method
      var onFileDialogCancel = this.props.onFileDialogCancel;
      var fileInputEl = this.fileInputEl;
      var isFileDialogActive = this.isFileDialogActive;
      // execute the timeout only if the onFileDialogCancel is defined and FileDialog
      // is opened in the browser

      if (onFileDialogCancel && isFileDialogActive) {
        setTimeout(function () {
          // Returns an object as FileList
          var FileList = fileInputEl.files;
          if (!FileList.length) {
            isFileDialogActive = false;
            onFileDialogCancel();
          }
        }, 300);
      }
    }
  }, {
    key: 'setRef',
    value: function setRef(ref) {
      this.node = ref;
    }
  }, {
    key: 'setRefs',
    value: function setRefs(ref) {
      this.fileInputEl = ref;
    }
    /**
     * Open system file upload dialog.
     *
     * @public
     */

  }, {
    key: 'open',
    value: function open() {
      this.isFileDialogActive = true;
      this.fileInputEl.value = null;
      this.fileInputEl.click();
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          accept = _props3.accept,
          acceptClassName = _props3.acceptClassName,
          activeClassName = _props3.activeClassName,
          children = _props3.children,
          disabled = _props3.disabled,
          disabledClassName = _props3.disabledClassName,
          inputProps = _props3.inputProps,
          multiple = _props3.multiple,
          name = _props3.name,
          rejectClassName = _props3.rejectClassName,
          rest = _objectWithoutProperties(_props3, ['accept', 'acceptClassName', 'activeClassName', 'children', 'disabled', 'disabledClassName', 'inputProps', 'multiple', 'name', 'rejectClassName']);

      var acceptStyle = rest.acceptStyle,
          activeStyle = rest.activeStyle,
          className = rest.className,
          disabledStyle = rest.disabledStyle,
          rejectStyle = rest.rejectStyle,
          style = rest.style,
          props = _objectWithoutProperties(rest, ['acceptStyle', 'activeStyle', 'className', 'disabledStyle', 'rejectStyle', 'style']);

      var _state = this.state,
          isDragActive = _state.isDragActive,
          draggedFiles = _state.draggedFiles;

      var filesCount = draggedFiles.length;
      var isMultipleAllowed = multiple || filesCount <= 1;
      var isDragAccept = filesCount > 0 && (0, _utils.allFilesAccepted)(draggedFiles, this.props.accept);
      var isDragReject = filesCount > 0 && (!isDragAccept || !isMultipleAllowed);
      className = className || '';
      var noStyles = !className && !style && !activeStyle && !acceptStyle && !rejectStyle && !disabledStyle;

      if (isDragActive && activeClassName) {
        className += ' ' + activeClassName;
      }
      if (isDragAccept && acceptClassName) {
        className += ' ' + acceptClassName;
      }
      if (isDragReject && rejectClassName) {
        className += ' ' + rejectClassName;
      }
      if (disabled && disabledClassName) {
        className += ' ' + disabledClassName;
      }

      if (noStyles) {
        style = styles.default;
        activeStyle = styles.active;
        acceptStyle = style.active;
        rejectStyle = styles.rejected;
        disabledStyle = styles.disabled;
      }

      var appliedStyle = _extends({}, style);
      if (activeStyle && isDragActive) {
        appliedStyle = _extends({}, style, activeStyle);
      }
      if (acceptStyle && isDragAccept) {
        appliedStyle = _extends({}, appliedStyle, acceptStyle);
      }
      if (rejectStyle && isDragReject) {
        appliedStyle = _extends({}, appliedStyle, rejectStyle);
      }
      if (disabledStyle && disabled) {
        appliedStyle = _extends({}, style, disabledStyle);
      }

      var inputAttributes = {
        accept: accept,
        disabled: disabled,
        type: 'file',
        style: { display: 'none' },
        multiple: _utils.supportMultiple && multiple,
        ref: this.setRefs,
        onChange: this.onDrop,
        autoComplete: 'off'
      };

      if (name && name.length) {
        inputAttributes.name = name;
      }

      // Remove custom properties before passing them to the wrapper div element
      var customProps = ['acceptedFiles', 'preventDropOnDocument', 'disablePreview', 'disableClick', 'activeClassName', 'acceptClassName', 'rejectClassName', 'disabledClassName', 'onDropAccepted', 'onDropRejected', 'onFileDialogCancel', 'maxSize', 'minSize'];
      var divProps = _extends({}, props);
      customProps.forEach(function (prop) {
        return delete divProps[prop];
      });

      return _react2.default.createElement(
        'div',
        _extends({
          className: className,
          style: appliedStyle
        }, divProps /* expand user provided props first so event handlers are never overridden */, {
          onClick: this.composeHandlers(this.onClick),
          onDragStart: this.composeHandlers(this.onDragStart),
          onDragEnter: this.composeHandlers(this.onDragEnter),
          onDragOver: this.composeHandlers(this.onDragOver),
          onDragLeave: this.composeHandlers(this.onDragLeave),
          onDrop: this.composeHandlers(this.onDrop),
          ref: this.setRef,
          'aria-disabled': disabled
        }),
        this.renderChildren(children, isDragActive, isDragAccept, isDragReject),
        _react2.default.createElement('input', _extends({}, inputProps /* expand user provided inputProps first so inputAttributes override them */, inputAttributes))
      );
    }
  }]);

  return Dropzone;
}(_react2.default.Component);

exports.default = Dropzone;

Dropzone.propTypes = {
  /**
   * Allow specific types of files. See https://github.com/okonet/attr-accept for more information.
   * Keep in mind that mime type determination is not reliable across platforms. CSV files,
   * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
   * Windows. In some cases there might not be a mime type set at all.
   * See: https://github.com/react-dropzone/react-dropzone/issues/276
   */
  accept: _propTypes2.default.string,

  /**
   * Contents of the dropzone
   */
  children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),

  /**
   * Disallow clicking on the dropzone container to open file dialog
   */
  disableClick: _propTypes2.default.bool,

  /**
  * Enable/disable the dropzone entirely
  */
  disabled: _propTypes2.default.bool,

  /**
   * Enable/disable preview generation
   */
  disablePreview: _propTypes2.default.bool,

  /**
   * If false, allow dropped items to take over the current browser window
   */
  preventDropOnDocument: _propTypes2.default.bool,

  /**
   * Pass additional attributes to the `<input type="file"/>` tag
   */
  inputProps: _propTypes2.default.object,

  /**
   * Allow dropping multiple files
   */
  multiple: _propTypes2.default.bool,

  /**
   * `name` attribute for the input tag
   */
  name: _propTypes2.default.string,

  /**
   * Maximum file size
   */
  maxSize: _propTypes2.default.number,

  /**
   * Minimum file size
   */
  minSize: _propTypes2.default.number,

  /**
   * className
   */
  className: _propTypes2.default.string,

  /**
   * className for active state
   */
  activeClassName: _propTypes2.default.string,

  /**
   * className for accepted state
   */
  acceptClassName: _propTypes2.default.string,

  /**
   * className for rejected state
   */
  rejectClassName: _propTypes2.default.string,

  /**
   * className for disabled state
   */
  disabledClassName: _propTypes2.default.string,

  /**
   * CSS styles to apply
   */
  style: _propTypes2.default.object,

  /**
   * CSS styles to apply when drag is active
   */
  activeStyle: _propTypes2.default.object,

  /**
   * CSS styles to apply when drop will be accepted
   */
  acceptStyle: _propTypes2.default.object,

  /**
   * CSS styles to apply when drop will be rejected
   */
  rejectStyle: _propTypes2.default.object,

  /**
   * CSS styles to apply when dropzone is disabled
   */
  disabledStyle: _propTypes2.default.object,

  /**
   * onClick callback
   * @param {Event} event
   */
  onClick: _propTypes2.default.func,

  /**
   * onDrop callback
   */
  onDrop: _propTypes2.default.func,

  /**
   * onDropAccepted callback
   */
  onDropAccepted: _propTypes2.default.func,

  /**
   * onDropRejected callback
   */
  onDropRejected: _propTypes2.default.func,

  /**
   * onDragStart callback
   */
  onDragStart: _propTypes2.default.func,

  /**
   * onDragEnter callback
   */
  onDragEnter: _propTypes2.default.func,

  /**
   * onDragOver callback
   */
  onDragOver: _propTypes2.default.func,

  /**
   * onDragLeave callback
   */
  onDragLeave: _propTypes2.default.func,

  /**
   * Provide a callback on clicking the cancel button of the file dialog
   */
  onFileDialogCancel: _propTypes2.default.func
};

Dropzone.defaultProps = {
  preventDropOnDocument: true,
  disabled: false,
  disablePreview: false,
  disableClick: false,
  multiple: true,
  maxSize: Infinity,
  minSize: 0
};


text:
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

### Table of Contents

-   [Nordnet](#nordnet)
    -   [call](#call)
    -   [authenticate](#authenticate)
    -   [subscribe](#subscribe)
    -   [authenticateFeeds](#authenticatefeeds)
    -   [authenticateFeed](#authenticatefeed)
    -   [base64](#base64)
    -   [formatFeedCommand](#formatfeedcommand)
    -   [encryptLogin](#encryptlogin)

## Nordnet

**Extends EventEmitter**

A simple-to-use Node.js wrapper around the Nordnet nExt API.

**Parameters**

-   `config`

### call

Call one of the API endpoints.

**Parameters**

-   `method` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** HTTP method to use when calling.
-   `endpoint` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** The endpoint to call.
-   `data` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** JSON data to send with the request.

Returns **([Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean))** Returns an object upon success or error, or a simple
                          boolean false if this method is called
                          without the client being authenticated.

### authenticate

Authenticate the client and receive a session key. The function also keeps
track of when the session key expires and reauthenticates automatically
just before it does.

**Parameters**

-   `credentials` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Nordnet nExt API credentials.
    -   `credentials.username` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Nordnet nExt API username
    -   `credentials.password` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Nordnet nExt API password

Returns **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** True if the authentication went OK, false otherwise.

### subscribe

Subscribe the public feed to a specific type of events.

**Parameters**

-   `type` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** The type of events to start listening to.
-   `args` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Arguments to pass together with the subscription command.

Returns **[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)** Resolves when the feed is subscribed.

### authenticateFeeds

Authenticate all feeds and start listening for input.

**Parameters**

-   `config` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** The configuration object for all feeds.
    -   `config.FEED_HANDLE` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Configurations for the feed.
        -   `config.FEED_HANDLE.host` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Host address for the feed.
        -   `config.FEED_HANDLE.port` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Port for the feed.

Returns **[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)** Resolves all authenticated feeds.

### authenticateFeed

Authenticate a single feed.

**Parameters**

-   `FEED_HANDLE` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
-   `config` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Configuration for this feed.
    -   `config.host` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Host address for the feed.
    -   `config.port` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Port for the feed.
-   `sessionKey` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** The session key received at login.

Returns **[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)** Description

### base64

Convert a value to base64.

**Parameters**

-   `value` **([string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** Value to encode to base64.

Returns **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** A base64 encoded version of the value.

### formatFeedCommand

Builder to be used when sending commands to the sockets.

**Parameters**

-   `cmd` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** A valid feed command. One of `login`, `subscribe` or `unsibscribe`.
-   `args` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Arguments to pass conjointly with the command.

Returns **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** A stringified verson of the data, with a line break at the end.

### encryptLogin

Base64 encodes the username, password and a timestamp, joins the
strings with colons, encrypts the joined string using Nordnet's
public RSA key, and finally base64 encodes the encrypted string. Phew.

**Parameters**

-   `username` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Your Nordnet nExt username.
-   `password` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Your Nordnet nExt password.

Returns **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** The encrypted, base64 encoded authentication string.

redpajama_set_name: RedPajamaGithub


text:
"""

Contains various base classes used throughout the ORM.

Defines some key base classes prominent within the internals.

This module and the classes within are mostly private, though some attributes
are exposed when inspecting mappings.

"""

from __future__ import annotations

import collections
import dataclasses
import typing
from typing import Any
from typing import Callable
from typing import cast
from typing import ClassVar
from typing import Dict
from typing import Generic
from typing import Iterator
from typing import List
from typing import NamedTuple
from typing import NoReturn
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union

from . import exc as orm_exc
from . import path_registry
from .base import _MappedAttribute as _MappedAttribute
from .base import EXT_CONTINUE as EXT_CONTINUE  # noqa: F401
from .base import EXT_SKIP as EXT_SKIP  # noqa: F401
from .base import EXT_STOP as EXT_STOP  # noqa: F401
from .base import InspectionAttr as InspectionAttr  # noqa: F401
from .base import InspectionAttrInfo as InspectionAttrInfo
from .base import MANYTOMANY as MANYTOMANY  # noqa: F401
from .base import MANYTOONE as MANYTOONE  # noqa: F401
from .base import NO_KEY as NO_KEY  # noqa: F401
from .base import NO_VALUE as NO_VALUE  # noqa: F401
from .base import NotExtension as NotExtension  # noqa: F401
from .base import ONETOMANY as ONETOMANY  # noqa: F401
from .base import RelationshipDirection as RelationshipDirection  # noqa: F401
from .base import SQLORMOperations
from .. import ColumnElement
from .. import exc as sa_exc
from .. import inspection
from .. import util
from ..sql import operators
from ..sql import roles
from ..sql import visitors
from ..sql.base import _NoArg
from ..sql.base import ExecutableOption
from ..sql.cache_key import HasCacheKey
from ..sql.operators import ColumnOperators
from ..sql.schema import Column
from ..sql.type_api import TypeEngine
from ..util.typing import RODescriptorReference
from ..util.typing import TypedDict

if typing.TYPE_CHECKING:
    from ._typing import _EntityType
    from ._typing import _IdentityKeyType
    from ._typing import _InstanceDict
    from ._typing import _InternalEntityType
    from ._typing import _ORMAdapterProto
    from .attributes import InstrumentedAttribute
    from .base import Mapped
    from .context import _MapperEntity
    from .context import ORMCompileState
    from .context import QueryContext
    from .decl_api import RegistryType
    from .loading import _PopulatorDict
    from .mapper import Mapper
    from .path_registry import AbstractEntityRegistry
    from .query import Query
    from .session import Session
    from .state import InstanceState
    from .strategy_options import _LoadElement
    from .util import AliasedInsp
    from .util import ORMAdapter
    from ..engine.result import Result
    from ..sql._typing import _ColumnExpressionArgument
    from ..sql._typing import _ColumnsClauseArgument
    from ..sql._typing import _DMLColumnArgument
    from ..sql._typing import _InfoType
    from ..sql.operators import OperatorType
    from ..sql.visitors import _TraverseInternalsType
    from ..util.typing import _AnnotationScanType

_StrategyKey = Tuple[Any, ...]

_T = TypeVar("_T", bound=Any)

_TLS = TypeVar("_TLS", bound="Type[LoaderStrategy]")

class ORMStatementRole(roles.StatementRole):
    __slots__ = ()
    _role_name = (
        "Executable SQL or text() construct, including ORM " "aware objects"
    )

class ORMColumnsClauseRole(
    roles.ColumnsClauseRole, roles.TypedColumnsClauseRole[_T]
):
    __slots__ = ()
    _role_name = "ORM mapped entity, aliased entity, or Column expression"

class ORMEntityColumnsClauseRole(ORMColumnsClauseRole[_T]):
    __slots__ = ()
    _role_name = "ORM mapped or aliased entity"

class ORMFromClauseRole(roles.StrictFromClauseRole):
    __slots__ = ()
    _role_name = "ORM mapped entity, aliased entity, or FROM expression"

class ORMColumnDescription(TypedDict):
    name: str
    # TODO: add python_type and sql_type here; combining them
    # into "type" is a bad idea
    type: Union[Type[Any], TypeEngine[Any]]
    aliased: bool
    expr: _ColumnsClauseArgument[Any]
    entity: Optional[_ColumnsClauseArgument[Any]]

class _IntrospectsAnnotations:
    __slots__ = ()

    def found_in_pep593_annotated(self) -> Any:
        """return a copy of this object to use in declarative when the
        object is found inside of an Annotated object."""

        raise NotImplementedError(
            f"Use of the {self.__class__} construct inside of an "
            f"Annotated object is not yet supported."
        )

    def declarative_scan(
        self,
        registry: RegistryType,
        cls: Type[Any],
        originating_module: Optional[str],
        key: str,
        mapped_container: Optional[Type[Mapped[Any]]],
        annotation: Optional[_AnnotationScanType],
        extracted_mapped_annotation: Optional[_AnnotationScanType],
        is_dataclass_field: bool,
    ) -> None:
        """Perform class-specific initializaton at early declarative scanning
        time.

        .. versionadded:: 2.0

        """

    def _raise_for_required(self, key: str, cls: Type[Any]) -> NoReturn:
        raise sa_exc.ArgumentError(
            f"Python typing annotation is required for attribute "
            f'"{cls.__name__}.{key}" when primary argument(s) for '
            f'"{self.__class__.__name__}" construct are None or not present'
        )

class _AttributeOptions(NamedTuple):
    """define Python-local attribute behavior options common to all
    :class:`.MapperProperty` objects.

    Currently this includes dataclass-generation arguments.

    .. versionadded:: 2.0

    """

    dataclasses_init: Union[_NoArg, bool]
    dataclasses_repr: Union[_NoArg, bool]
    dataclasses_default: Union[_NoArg, Any]
    dataclasses_default_factory: Union[_NoArg, Callable[[], Any]]
    dataclasses_kw_only: Union[_NoArg, bool]

    def _as_dataclass_field(self) -> Any:
        """Return a ``dataclasses.Field`` object given these arguments."""

        kw: Dict[str, Any] = {}
        if self.dataclasses_default_factory is not _NoArg.NO_ARG:
            kw["default_factory"] = self.dataclasses_default_factory
        if self.dataclasses_default is not _NoArg.NO_ARG:
            kw["default"] = self.dataclasses_default
        if self.dataclasses_init is not _NoArg.NO_ARG:
            kw["init"] = self.dataclasses_init
        if self.dataclasses_repr is not _NoArg.NO_ARG:
            kw["repr"] = self.dataclasses_repr
        if self.dataclasses_kw_only is not _NoArg.NO_ARG:
            kw["kw_only"] = self.dataclasses_kw_only

        return dataclasses.field(**kw)

    @classmethod
    def _get_arguments_for_make_dataclass(
        cls,
        key: str,
        annotation: _AnnotationScanType,
        mapped_container: Optional[Any],
        elem: _T,
    ) -> Union[
        Tuple[str, _AnnotationScanType],
        Tuple[str, _AnnotationScanType, dataclasses.Field[Any]],
    ]:
        """given attribute key, annotation, and value from a class, return
        the argument tuple we would pass to dataclasses.make_dataclass()
        for this attribute.

        """
        if isinstance(elem, (MapperProperty, _MapsColumns)):
            dc_field = elem._attribute_options._as_dataclass_field()

            return (key, annotation, dc_field)
        elif elem is not _NoArg.NO_ARG:
            # why is typing not erroring on this?
            return (key, annotation, elem)
        elif mapped_container is not None:
            # it's Mapped[], but there's no "element", which means declarative
            # did not actually do anything for this field.  this shouldn't
            # happen.
            # previously, this would occur because _scan_attributes would
            # skip a field that's on an already mapped superclass, but it
            # would still include it in the annotations, leading
            # to issue #8718

            assert False, "Mapped[] received without a mapping declaration"

        else:
            # plain dataclass field, not mapped.  Is only possible
            # if __allow_unmapped__ is set up.  I can see this mode causing
            # problems...
            return (key, annotation)

_DEFAULT_ATTRIBUTE_OPTIONS = _AttributeOptions(
    _NoArg.NO_ARG, _NoArg.NO_ARG, _NoArg.NO_ARG, _NoArg.NO_ARG, _NoArg.NO_ARG
)

class _MapsColumns(_MappedAttribute[_T]):
    """interface for declarative-capable construct that delivers one or more
    Column objects to the declarative process to be part of a Table.
    """

    __slots__ = ()

    _attribute_options: _AttributeOptions
    _has_dataclass_arguments: bool

    @property
    def mapper_property_to_assign(self) -> Optional[MapperProperty[_T]]:
        """return a MapperProperty to be assigned to the declarative mapping"""
        raise NotImplementedError()

    @property
    def columns_to_assign(self) -> List[Column[_T]]:
        """A list of Column objects that should be declaratively added to the
        new Table object.

        """
        raise NotImplementedError()

# NOTE: MapperProperty needs to extend _MappedAttribute so that declarative
# typing works, i.e. "Mapped[A] = relationship()".   This introduces an
# inconvenience which is that all the MapperProperty objects are treated
# as descriptors by typing tools, which are misled by this as assignment /
# access to a descriptor attribute wants to move through __get__.
# Therefore, references to MapperProperty as an instance variable, such
# as in PropComparator, may have some special typing workarounds such as the
# use of sqlalchemy.util.typing.DescriptorReference to avoid mis-interpretation
# by typing tools
@inspection._self_inspects
class MapperProperty(
    HasCacheKey,
    _MappedAttribute[_T],
    InspectionAttrInfo,
    util.MemoizedSlots,
):
    """Represent a particular class attribute mapped by :class:`_orm.Mapper`.

    The most common occurrences of :class:`.MapperProperty` are the
    mapped :class:`_schema.Column`, which is represented in a mapping as
    an instance of :class:`.ColumnProperty`,
    and a reference to another class produced by :func:`_orm.relationship`,
    represented in the mapping as an instance of
    :class:`.Relationship`.

    """

    __slots__ = (
        "_configure_started",
        "_configure_finished",
        "_attribute_options",
        "_has_dataclass_arguments",
        "parent",
        "key",
        "info",
        "doc",
    )

    _cache_key_traversal: _TraverseInternalsType = [
        ("parent", visitors.ExtendedInternalTraversal.dp_has_cache_key),
        ("key", visitors.ExtendedInternalTraversal.dp_string),
    ]

    if not TYPE_CHECKING:
        cascade = None

    is_property = True
    """Part of the InspectionAttr interface; states this object is a
    mapper property.

    """

    comparator: PropComparator[_T]
    """The :class:`_orm.PropComparator` instance that implements SQL
    expression construction on behalf of this mapped attribute."""

    key: str
    """name of class attribute"""

    parent: Mapper[Any]
    """the :class:`.Mapper` managing this property."""

    _is_relationship = False

    _links_to_entity: bool
    """True if this MapperProperty refers to a mapped entity.

    Should only be True for Relationship, False for all others.

    """

    doc: Optional[str]
    """optional documentation string"""

    _attribute_options: _AttributeOptions
    """behavioral options for ORM-enabled Python attributes

    .. versionadded:: 2.0

    """

    info: _InfoType
    """Info dictionary associated with the object, allowing user-defined
    data to be associated with this :class:`.InspectionAttr`.

    The dictionary is generated when first accessed.  Alternatively,
    it can be specified as a constructor argument to the
    :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite`
    functions.

    .. versionchanged:: 1.0.0 :attr:`.InspectionAttr.info` moved
        from :class:`.MapperProperty` so that it can apply to a wider
        variety of ORM and extension constructs.

    .. seealso::

        :attr:`.QueryableAttribute.info`

        :attr:`.SchemaItem.info`

    """

    _has_dataclass_arguments: bool

    def _memoized_attr_info(self) -> _InfoType:
        """Info dictionary associated with the object, allowing user-defined
        data to be associated with this :class:`.InspectionAttr`.

        The dictionary is generated when first accessed.  Alternatively,
        it can be specified as a constructor argument to the
        :func:`.column_property`, :func:`_orm.relationship`, or
        :func:`.composite`
        functions.

        .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also
           available on extension types via the
           :attr:`.InspectionAttrInfo.info` attribute, so that it can apply
           to a wider variety of ORM and extension constructs.

        .. seealso::

            :attr:`.QueryableAttribute.info`

            :attr:`.SchemaItem.info`

        """
        return {}

    def setup(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        """Called by Query for the purposes of constructing a SQL statement.

        Each MapperProperty associated with the target mapper processes the
        statement referenced by the query context, adding columns and/or
        criterion as appropriate.

        """

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        """Produce row processing functions and append to the given
        set of populators lists.

        """

    def cascade_iterator(
        self,
        type_: str,
        state: InstanceState[Any],
        dict_: _InstanceDict,
        visited_states: Set[InstanceState[Any]],
        halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
    ) -> Iterator[
        Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
    ]:
        """Iterate through instances related to the given instance for
        a particular 'cascade', starting with this MapperProperty.

        Return an iterator3-tuples (instance, mapper, state).

        Note that the 'cascade' collection on this MapperProperty is
        checked first for the given type before cascade_iterator is called.

        This method typically only applies to Relationship.

        """

        return iter(())

    def set_parent(self, parent: Mapper[Any], init: bool) -> None:
        """Set the parent mapper that references this MapperProperty.

        This method is overridden by some subclasses to perform extra
        setup when the mapper is first known.

        """
        self.parent = parent

    def instrument_class(self, mapper: Mapper[Any]) -> None:
        """Hook called by the Mapper to the property to initiate
        instrumentation of the class attribute managed by this
        MapperProperty.

        The MapperProperty here will typically call out to the
        attributes module to set up an InstrumentedAttribute.

        This step is the first of two steps to set up an InstrumentedAttribute,
        and is called early in the mapper setup process.

        The second step is typically the init_class_attribute step,
        called from StrategizedProperty via the post_instrument_class()
        hook.  This step assigns additional state to the InstrumentedAttribute
        (specifically the "impl") which has been determined after the
        MapperProperty has determined what kind of persistence
        management it needs to do (e.g. scalar, object, collection, etc).

        """

    def __init__(
        self, attribute_options: Optional[_AttributeOptions] = None
    ) -> None:
        self._configure_started = False
        self._configure_finished = False
        if (
            attribute_options
            and attribute_options != _DEFAULT_ATTRIBUTE_OPTIONS
        ):
            self._has_dataclass_arguments = True
            self._attribute_options = attribute_options
        else:
            self._has_dataclass_arguments = False
            self._attribute_options = _DEFAULT_ATTRIBUTE_OPTIONS

    def init(self) -> None:
        """Called after all mappers are created to assemble
        relationships between mappers and perform other post-mapper-creation
        initialization steps.

        """
        self._configure_started = True
        self.do_init()
        self._configure_finished = True

    @property
    def class_attribute(self) -> InstrumentedAttribute[_T]:
        """Return the class-bound descriptor corresponding to this
        :class:`.MapperProperty`.

        This is basically a ``getattr()`` call::

            return getattr(self.parent.class_, self.key)

        I.e. if this :class:`.MapperProperty` were named ``addresses``,
        and the class to which it is mapped is ``User``, this sequence
        is possible::

            >>> from sqlalchemy import inspect
            >>> mapper = inspect(User)
            >>> addresses_property = mapper.attrs.addresses
            >>> addresses_property.class_attribute is User.addresses
            True
            >>> User.addresses.property is addresses_property
            True

        """

        return getattr(self.parent.class_, self.key)  # type: ignore

    def do_init(self) -> None:
        """Perform subclass-specific initialization post-mapper-creation
        steps.

        This is a template method called by the ``MapperProperty``
        object's init() method.

        """

    def post_instrument_class(self, mapper: Mapper[Any]) -> None:
        """Perform instrumentation adjustments that need to occur
        after init() has completed.

        The given Mapper is the Mapper invoking the operation, which
        may not be the same Mapper as self.parent in an inheritance
        scenario; however, Mapper will always at least be a sub-mapper of
        self.parent.

        This method is typically used by StrategizedProperty, which delegates
        it to LoaderStrategy.init_class_attribute() to perform final setup
        on the class-bound InstrumentedAttribute.

        """

    def merge(
        self,
        session: Session,
        source_state: InstanceState[Any],
        source_dict: _InstanceDict,
        dest_state: InstanceState[Any],
        dest_dict: _InstanceDict,
        load: bool,
        _recursive: Dict[Any, object],
        _resolve_conflict_map: Dict[_IdentityKeyType[Any], object],
    ) -> None:
        """Merge the attribute represented by this ``MapperProperty``
        from source to destination object.

        """

    def __repr__(self) -> str:
        return "<%s at 0x%x; %s>" % (
            self.__class__.__name__,
            id(self),
            getattr(self, "key", "no key"),
        )

@inspection._self_inspects
class PropComparator(SQLORMOperations[_T], Generic[_T], ColumnOperators):
    r"""Defines SQL operations for ORM mapped attributes.

    SQLAlchemy allows for operators to
    be redefined at both the Core and ORM level.  :class:`.PropComparator`
    is the base class of operator redefinition for ORM-level operations,
    including those of :class:`.ColumnProperty`,
    :class:`.Relationship`, and :class:`.Composite`.

    User-defined subclasses of :class:`.PropComparator` may be created. The
    built-in Python comparison and math operator methods, such as
    :meth:`.operators.ColumnOperators.__eq__`,
    :meth:`.operators.ColumnOperators.__lt__`, and
    :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide
    new operator behavior. The custom :class:`.PropComparator` is passed to
    the :class:`.MapperProperty` instance via the ``comparator_factory``
    argument. In each case,
    the appropriate subclass of :class:`.PropComparator` should be used::

        # definition of custom PropComparator subclasses

        from sqlalchemy.orm.properties import \
                                ColumnProperty,\
                                Composite,\
                                Relationship

        class MyColumnComparator(ColumnProperty.Comparator):
            def __eq__(self, other):
                return self.__clause_element__() == other

        class MyRelationshipComparator(Relationship.Comparator):
            def any(self, expression):
                "define the 'any' operation"
                # ...

        class MyCompositeComparator(Composite.Comparator):
            def __gt__(self, other):
                "redefine the 'greater than' operation"

                return sql.and_(*[a>b for a, b in
                                  zip(self.__clause_element__().clauses,
                                      other.__composite_values__())])

        # application of custom PropComparator subclasses

        from sqlalchemy.orm import column_property, relationship, composite
        from sqlalchemy import Column, String

        class SomeMappedClass(Base):
            some_column = column_property(Column("some_column", String),
                                comparator_factory=MyColumnComparator)

            some_relationship = relationship(SomeOtherClass,
                                comparator_factory=MyRelationshipComparator)

            some_composite = composite(
                    Column("a", String), Column("b", String),
                    comparator_factory=MyCompositeComparator
                )

    Note that for column-level operator redefinition, it's usually
    simpler to define the operators at the Core level, using the
    :attr:`.TypeEngine.comparator_factory` attribute.  See
    :ref:`types_operators` for more detail.

    .. seealso::

        :class:`.ColumnProperty.Comparator`

        :class:`.Relationship.Comparator`

        :class:`.Composite.Comparator`

        :class:`.ColumnOperators`

        :ref:`types_operators`

        :attr:`.TypeEngine.comparator_factory`

    """
    __slots__ = "prop", "_parententity", "_adapt_to_entity"

    __visit_name__ = "orm_prop_comparator"

    _parententity: _InternalEntityType[Any]
    _adapt_to_entity: Optional[AliasedInsp[Any]]
    prop: RODescriptorReference[MapperProperty[_T]]

    def __init__(
        self,
        prop: MapperProperty[_T],
        parentmapper: _InternalEntityType[Any],
        adapt_to_entity: Optional[AliasedInsp[Any]] = None,
    ):
        self.prop = prop
        self._parententity = adapt_to_entity or parentmapper
        self._adapt_to_entity = adapt_to_entity

    @util.non_memoized_property
    def property(self) -> MapperProperty[_T]:
        """Return the :class:`.MapperProperty` associated with this
        :class:`.PropComparator`.

        Return values here will commonly be instances of
        :class:`.ColumnProperty` or :class:`.Relationship`.

        """
        return self.prop

    def __clause_element__(self) -> roles.ColumnsClauseRole:
        raise NotImplementedError("%r" % self)

    def _bulk_update_tuples(
        self, value: Any
    ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
        """Receive a SQL expression that represents a value in the SET
        clause of an UPDATE statement.

        Return a tuple that can be passed to a :class:`_expression.Update`
        construct.

        """

        return [(cast("_DMLColumnArgument", self.__clause_element__()), value)]

    def adapt_to_entity(
        self, adapt_to_entity: AliasedInsp[Any]
    ) -> PropComparator[_T]:
        """Return a copy of this PropComparator which will use the given
        :class:`.AliasedInsp` to produce corresponding expressions.
        """
        return self.__class__(self.prop, self._parententity, adapt_to_entity)

    @util.ro_non_memoized_property
    def _parentmapper(self) -> Mapper[Any]:
        """legacy; this is renamed to _parententity to be
        compatible with QueryableAttribute."""
        return self._parententity.mapper

    def _criterion_exists(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[Any]:
        return self.prop.comparator._criterion_exists(criterion, **kwargs)

    @util.ro_non_memoized_property
    def adapter(self) -> Optional[_ORMAdapterProto]:
        """Produce a callable that adapts column expressions
        to suit an aliased version of this comparator.

        """
        if self._adapt_to_entity is None:
            return None
        else:
            return self._adapt_to_entity._orm_adapt_element

    @util.ro_non_memoized_property
    def info(self) -> _InfoType:
        return self.prop.info

    @staticmethod
    def _any_op(a: Any, b: Any, **kwargs: Any) -> Any:
        return a.any(b, **kwargs)

    @staticmethod
    def _has_op(left: Any, other: Any, **kwargs: Any) -> Any:
        return left.has(other, **kwargs)

    @staticmethod
    def _of_type_op(a: Any, class_: Any) -> Any:
        return a.of_type(class_)

    any_op = cast(operators.OperatorType, _any_op)
    has_op = cast(operators.OperatorType, _has_op)
    of_type_op = cast(operators.OperatorType, _of_type_op)

    if typing.TYPE_CHECKING:

        def operate(
            self, op: OperatorType, *other: Any, **kwargs: Any
        ) -> ColumnElement[Any]:
            ...

        def reverse_operate(
            self, op: OperatorType, other: Any, **kwargs: Any
        ) -> ColumnElement[Any]:
            ...

    def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T]:
        r"""Redefine this object in terms of a polymorphic subclass,
        :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased`
        construct.

        Returns a new PropComparator from which further criterion can be
        evaluated.

        e.g.::

            query.join(Company.employees.of_type(Engineer)).\
               filter(Engineer.name=='foo')

        :param \class_: a class or mapper indicating that criterion will be
            against this specific subclass.

        .. seealso::

            :ref:`orm_queryguide_joining_relationships_aliased` - in the
            :ref:`queryguide_toplevel`

            :ref:`inheritance_of_type`

        """

        return self.operate(PropComparator.of_type_op, class_)  # type: ignore

    def and_(
        self, *criteria: _ColumnExpressionArgument[bool]
    ) -> PropComparator[bool]:
        """Add additional criteria to the ON clause that's represented by this
        relationship attribute.

        E.g.::

            stmt = select(User).join(
                User.addresses.and_(Address.email_address != 'foo')
            )

            stmt = select(User).options(
                joinedload(User.addresses.and_(Address.email_address != 'foo'))
            )

        .. versionadded:: 1.4

        .. seealso::

            :ref:`orm_queryguide_join_on_augmented`

            :ref:`loader_option_criteria`

            :func:`.with_loader_criteria`

        """
        return self.operate(operators.and_, *criteria)  # type: ignore

    def any(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[bool]:
        r"""Return a SQL expression representing true if this element
        references a member which meets the given criterion.

        The usual implementation of ``any()`` is
        :meth:`.Relationship.Comparator.any`.

        :param criterion: an optional ClauseElement formulated against the
          member class' table or attributes.

        :param \**kwargs: key/value pairs corresponding to member class
          attribute names which will be compared via equality to the
          corresponding values.

        """

        return self.operate(  # type: ignore
            PropComparator.any_op, criterion, **kwargs
        )

    def has(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[bool]:
        r"""Return a SQL expression representing true if this element
        references a member which meets the given criterion.

        The usual implementation of ``has()`` is
        :meth:`.Relationship.Comparator.has`.

        :param criterion: an optional ClauseElement formulated against the
          member class' table or attributes.

        :param \**kwargs: key/value pairs corresponding to member class
          attribute names which will be compared via equality to the
          corresponding values.

        """

        return self.operate(  # type: ignore
            PropComparator.has_op, criterion, **kwargs
        )

class StrategizedProperty(MapperProperty[_T]):
    """A MapperProperty which uses selectable strategies to affect
    loading behavior.

    There is a single strategy selected by default.  Alternate
    strategies can be selected at Query time through the usage of
    ``StrategizedOption`` objects via the Query.options() method.

    The mechanics of StrategizedProperty are used for every Query
    invocation for every mapped attribute participating in that Query,
    to determine first how the attribute will be rendered in SQL
    and secondly how the attribute will retrieve a value from a result
    row and apply it to a mapped object.  The routines here are very
    performance-critical.

    """

    __slots__ = (
        "_strategies",
        "strategy",
        "_wildcard_token",
        "_default_path_loader_key",
        "strategy_key",
    )
    inherit_cache = True
    strategy_wildcard_key: ClassVar[str]

    strategy_key: _StrategyKey

    _strategies: Dict[_StrategyKey, LoaderStrategy]

    def _memoized_attr__wildcard_token(self) -> Tuple[str]:
        return (
            f"{self.strategy_wildcard_key}:{path_registry._WILDCARD_TOKEN}",
        )

    def _memoized_attr__default_path_loader_key(
        self,
    ) -> Tuple[str, Tuple[str]]:
        return (
            "loader",
            (f"{self.strategy_wildcard_key}:{path_registry._DEFAULT_TOKEN}",),
        )

    def _get_context_loader(
        self, context: ORMCompileState, path: AbstractEntityRegistry
    ) -> Optional[_LoadElement]:

        load: Optional[_LoadElement] = None

        search_path = path[self]

        # search among: exact match, "attr.*", "default" strategy
        # if any.
        for path_key in (
            search_path._loader_key,
            search_path._wildcard_path_loader_key,
            search_path._default_path_loader_key,
        ):
            if path_key in context.attributes:
                load = context.attributes[path_key]
                break

                # note that if strategy_options.Load is placing non-actionable
                # objects in the context like defaultload(), we would
                # need to continue the loop here if we got such an
                # option as below.
                # if load.strategy or load.local_opts:
                #    break

        return load

    def _get_strategy(self, key: _StrategyKey) -> LoaderStrategy:
        try:
            return self._strategies[key]
        except KeyError:
            pass

        # run outside to prevent transfer of exception context
        cls = self._strategy_lookup(self, *key)
        # this previously was setting self._strategies[cls], that's
        # a bad idea; should use strategy key at all times because every
        # strategy has multiple keys at this point
        self._strategies[key] = strategy = cls(self, key)
        return strategy

    def setup(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        loader = self._get_context_loader(context, path)
        if loader and loader.strategy:
            strat = self._get_strategy(loader.strategy)
        else:
            strat = self.strategy
        strat.setup_query(
            context, query_entity, path, loader, adapter, **kwargs
        )

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        loader = self._get_context_loader(context, path)
        if loader and loader.strategy:
            strat = self._get_strategy(loader.strategy)
        else:
            strat = self.strategy
        strat.create_row_processor(
            context,
            query_entity,
            path,
            loader,
            mapper,
            result,
            adapter,
            populators,
        )

    def do_init(self) -> None:
        self._strategies = {}
        self.strategy = self._get_strategy(self.strategy_key)

    def post_instrument_class(self, mapper: Mapper[Any]) -> None:
        if (
            not self.parent.non_primary
            and not mapper.class_manager._attr_has_impl(self.key)
        ):
            self.strategy.init_class_attribute(mapper)

    _all_strategies: collections.defaultdict[
        Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]]
    ] = collections.defaultdict(dict)

    @classmethod
    def strategy_for(cls, **kw: Any) -> Callable[[_TLS], _TLS]:
        def decorate(dec_cls: _TLS) -> _TLS:
            # ensure each subclass of the strategy has its
            # own _strategy_keys collection
            if "_strategy_keys" not in dec_cls.__dict__:
                dec_cls._strategy_keys = []
            key = tuple(sorted(kw.items()))
            cls._all_strategies[cls][key] = dec_cls
            dec_cls._strategy_keys.append(key)
            return dec_cls

        return decorate

    @classmethod
    def _strategy_lookup(
        cls, requesting_property: MapperProperty[Any], *key: Any
    ) -> Type[LoaderStrategy]:
        requesting_property.parent._with_polymorphic_mappers

        for prop_cls in cls.__mro__:
            if prop_cls in cls._all_strategies:
                if TYPE_CHECKING:
                    assert issubclass(prop_cls, MapperProperty)
                strategies = cls._all_strategies[prop_cls]
                try:
                    return strategies[key]
                except KeyError:
                    pass

        for property_type, strats in cls._all_strategies.items():
            if key in strats:
                intended_property_type = property_type
                actual_strategy = strats[key]
                break
        else:
            intended_property_type = None
            actual_strategy = None

        raise orm_exc.LoaderStrategyException(
            cls,
            requesting_property,
            intended_property_type,
            actual_strategy,
            key,
        )

class ORMOption(ExecutableOption):
    """Base class for option objects that are passed to ORM queries.

    These options may be consumed by :meth:`.Query.options`,
    :meth:`.Select.options`, or in a more general sense by any
    :meth:`.Executable.options` method.   They are interpreted at
    statement compile time or execution time in modern use.  The
    deprecated :class:`.MapperOption` is consumed at ORM query construction
    time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    _is_legacy_option = False

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" SELECT statements that occur for relationship
    lazy loaders as well as attribute load / refresh operations.

    """

    _is_core = False

    _is_user_defined = False

    _is_compile_state = False

    _is_criteria_option = False

    _is_strategy_option = False

    def _adapt_cached_option_to_uncached_option(
        self, context: QueryContext, uncached_opt: ORMOption
    ) -> ORMOption:
        """adapt this option to the "uncached" version of itself in a
        loader strategy context.

        given "self" which is an option from a cached query, as well as the
        corresponding option from the uncached version of the same query,
        return the option we should use in a new query, in the context of a
        loader strategy being asked to load related rows on behalf of that
        cached query, which is assumed to be building a new query based on
        entities passed to us from the cached query.

        Currently this routine chooses between "self" and "uncached" without
        manufacturing anything new. If the option is itself a loader strategy
        option which has a path, that path needs to match to the entities being
        passed to us by the cached query, so the :class:`_orm.Load` subclass
        overrides this to return "self". For all other options, we return the
        uncached form which may have changing state, such as a
        with_loader_criteria() option which will very often have new state.

        This routine could in the future involve
        generating a new option based on both inputs if use cases arise,
        such as if with_loader_criteria() needed to match up to
        ``AliasedClass`` instances given in the parent query.

        However, longer term it might be better to restructure things such that
        ``AliasedClass`` entities are always matched up on their cache key,
        instead of identity, in things like paths and such, so that this whole
        issue of "the uncached option does not match the entities" goes away.
        However this would make ``PathRegistry`` more complicated and difficult
        to debug as well as potentially less performant in that it would be
        hashing enormous cache keys rather than a simple AliasedInsp. UNLESS,
        we could get cache keys overall to be reliably hashed into something
        like an md5 key.

        .. versionadded:: 1.4.41

        """
        if uncached_opt is not None:
            return uncached_opt
        else:
            return self

class CompileStateOption(HasCacheKey, ORMOption):
    """base for :class:`.ORMOption` classes that affect the compilation of
    a SQL query and therefore need to be part of the cache key.

    .. note::  :class:`.CompileStateOption` is generally non-public and
       should not be used as a base class for user-defined options; instead,
       use :class:`.UserDefinedOption`, which is easier to use as it does not
       interact with ORM compilation internals or caching.

    :class:`.CompileStateOption` defines an internal attribute
    ``_is_compile_state=True`` which has the effect of the ORM compilation
    routines for SELECT and other statements will call upon these options when
    a SQL string is being compiled. As such, these classes implement
    :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal``
    structures.

    The :class:`.CompileStateOption` class is used to implement the ORM
    :class:`.LoaderOption` and :class:`.CriteriaOption` classes.

    .. versionadded:: 1.4.28

    """

    __slots__ = ()

    _is_compile_state = True

    def process_compile_state(self, compile_state: ORMCompileState) -> None:
        """Apply a modification to a given :class:`.ORMCompileState`.

        This method is part of the implementation of a particular
        :class:`.CompileStateOption` and is only invoked internally
        when an ORM query is compiled.

        """

    def process_compile_state_replaced_entities(
        self,
        compile_state: ORMCompileState,
        mapper_entities: Sequence[_MapperEntity],
    ) -> None:
        """Apply a modification to a given :class:`.ORMCompileState`,
        given entities that were replaced by with_only_columns() or
        with_entities().

        This method is part of the implementation of a particular
        :class:`.CompileStateOption` and is only invoked internally
        when an ORM query is compiled.

        .. versionadded:: 1.4.19

        """

class LoaderOption(CompileStateOption):
    """Describe a loader modification to an ORM statement at compilation time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    def process_compile_state_replaced_entities(
        self,
        compile_state: ORMCompileState,
        mapper_entities: Sequence[_MapperEntity],
    ) -> None:
        self.process_compile_state(compile_state)

class CriteriaOption(CompileStateOption):
    """Describe a WHERE criteria modification to an ORM statement at
    compilation time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    _is_criteria_option = True

    def get_global_criteria(self, attributes: Dict[str, Any]) -> None:
        """update additional entity criteria options in the given
        attributes dictionary.

        """

class UserDefinedOption(ORMOption):
    """Base class for a user-defined option that can be consumed from the
    :meth:`.SessionEvents.do_orm_execute` event hook.

    """

    __slots__ = ("payload",)

    _is_legacy_option = False

    _is_user_defined = True

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" Query objects produced during lazy loads
    or refresh operations.

    """

    def __init__(self, payload: Optional[Any] = None):
        self.payload = payload

@util.deprecated_cls(
    "1.4",
    "The :class:`.MapperOption class is deprecated and will be removed "
    "in a future release.   For "
    "modifications to queries on a per-execution basis, use the "
    ":class:`.UserDefinedOption` class to establish state within a "
    ":class:`.Query` or other Core statement, then use the "
    ":meth:`.SessionEvents.before_orm_execute` hook to consume them.",
    constructor=None,
)
class MapperOption(ORMOption):
    """Describe a modification to a Query"""

    __slots__ = ()

    _is_legacy_option = True

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" Query objects produced during lazy loads
    or refresh operations.

    """

    def process_query(self, query: Query[Any]) -> None:
        """Apply a modification to the given :class:`_query.Query`."""

    def process_query_conditionally(self, query: Query[Any]) -> None:
        """same as process_query(), except that this option may not
        apply to the given query.

        This is typically applied during a lazy load or scalar refresh
        operation to propagate options stated in the original Query to the
        new Query being used for the load.  It occurs for those options that
        specify propagate_to_loaders=True.

        """

        self.process_query(query)

class LoaderStrategy:
    """Describe the loading behavior of a StrategizedProperty object.

    The ``LoaderStrategy`` interacts with the querying process in three
    ways:

    * it controls the configuration of the ``InstrumentedAttribute``
      placed on a class to handle the behavior of the attribute.  this
      may involve setting up class-level callable functions to fire
      off a select operation when the attribute is first accessed
      (i.e. a lazy load)

    * it processes the ``QueryContext`` at statement construction time,
      where it can modify the SQL statement that is being produced.
      For example, simple column attributes will add their represented
      column to the list of selected columns, a joined eager loader
      may establish join clauses to add to the statement.

    * It produces "row processor" functions at result fetching time.
      These "row processor" functions populate a particular attribute
      on a particular mapped instance.

    """

    __slots__ = (
        "parent_property",
        "is_class_level",
        "parent",
        "key",
        "strategy_key",
        "strategy_opts",
    )

    _strategy_keys: ClassVar[List[_StrategyKey]]

    def __init__(
        self, parent: MapperProperty[Any], strategy_key: _StrategyKey
    ):
        self.parent_property = parent
        self.is_class_level = False
        self.parent = self.parent_property.parent
        self.key = self.parent_property.key
        self.strategy_key = strategy_key
        self.strategy_opts = dict(strategy_key)

    def init_class_attribute(self, mapper: Mapper[Any]) -> None:
        pass

    def setup_query(
        self,
        compile_state: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        loadopt: Optional[_LoadElement],
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        """Establish column and other state for a given QueryContext.

        This method fulfills the contract specified by MapperProperty.setup().

        StrategizedProperty delegates its setup() method
        directly to this method.

        """

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        loadopt: Optional[_LoadElement],
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        """Establish row processing functions for a given QueryContext.

        This method fulfills the contract specified by
        MapperProperty.create_row_processor().

        StrategizedProperty delegates its create_row_processor() method
        directly to this method.

        """

    def __str__(self) -> str:
        return str(self.parent_property)


text:
package cz.mjanys.iface.converter;

import cz.mjanys.core.database.EntityReferenceFactory;
import cz.mjanys.core.entity.ArticleEntity;
import cz.mjanys.core.entity.PageEntity;
import cz.mjanys.iface.converter.generic.AbstractExtendedConverter;
import cz.mjanys.iface.dto.Article;
import cz.mjanys.iface.dto.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author Martin Janys
 */
@Component
public class PageEntityConverter extends AbstractExtendedConverter<Page, PageEntity> {

    @Autowired
    private EntityReferenceFactory referenceFactory;

    @Override
    public PageEntity newTarget() {
        return new PageEntity();
    }

    @Override
    public PageEntity convert(Page source, PageEntity target) {
        Assert.notNull(source);
        Assert.notNull(target);

        target.setId(source.getId());
        target.setTitle(source.getTitle());
        target.setFriendlyUrl(source.getFriendlyUrl());
        target.setOrder(source.getOrder());
        target.setArticles(referenceFactory.getReferences(ArticleEntity.class, source.getArticles()));
        target.setLayout(source.getLayout());
        target.setArticleLayout(source.getArticleLayout());
        target.setVisible(source.isVisible());
        Long parentId = source.getParent().getId();
        if (parentId != null && parentId != 0)
            target.setParent(referenceFactory.getReference(PageEntity.class, parentId));
        target.setChilds(referenceFactory.getReferences(PageEntity.class, source.getChilds()));
        return target;
    }
}


text:
#include "terminal_interface.h"

#include <map>

#include "debug.h"

namespace util {

namespace {

const std::map<uint32_t, speed_t> kBaudRateMap = {
  {0,      B0     },
  {50,     B50    },
  {75,     B75    },
  {110,    B110   },
  {134,    B134   },
  {150,    B150   },
  {200,    B200   },
  {300,    B300   },
  {600,    B600   },
  {1200,   B1200  },
  {1800,   B1800  },
  {2400,   B2400  },
  {4800,   B4800  },
  {9600,   B9600  },
  {19200,  B19200 },
  {38400,  B38400 },
  {57600,  B57600 },
  {115200, B115200},
  {230400, B230400},
};

}  // namespace

TerminalInterface::TerminalInterface(const int32_t &fd)
  : fd_(fd),
    current_terminal_(),
    backup_terminal_() {
      (void)TerminalInterface::BackupSettings();
}

TerminalInterface::~TerminalInterface() {
  DEBUG_PRINTF("Call the destructor of TerminalInterface (fd: %d)", fd_);
  (void)Flush();
  (void)RevertSettings();
}

common::status_t TerminalInterface::SetRawMode() {
  cfmakeraw(&current_terminal_);
  return common::status_t::kSuccess;
}

common::status_t TerminalInterface::SetBaudRate(const uint32_t &baud_rate,
                                                direction_t direction) {
  auto itr = kBaudRateMap.find(baud_rate);
  if (itr == kBaudRateMap.end())
    return common::status_t::kFailure;
  if (direction == direction_t::kIn) {
    if (cfsetispeed(&current_terminal_, itr->second))
      return common::status_t::kFailure;
  } else if (direction == direction_t::kOut) {
    if (cfsetospeed(&current_terminal_, itr->second))
      return common::status_t::kFailure;
  }
  return common::status_t::kSuccess;
}

common::status_t TerminalInterface::Flush() {
  if (tcflush(fd_, TCIOFLUSH))
    return common::status_t::kFailure;
  return common::status_t::kSuccess;
}

common::status_t TerminalInterface::BackupSettings() {
  if (tcgetattr(fd_, &backup_terminal_))
    return common::status_t::kFailure;
  return common::status_t::kSuccess;
}

common::status_t TerminalInterface::RevertSettings() {
  if (tcsetattr(fd_, TCSANOW, &backup_terminal_))
    return common::status_t::kFailure;
  return common::status_t::kSuccess;
}

common::status_t TerminalInterface::SetNow() {
  if (tcsetattr(fd_, TCSANOW, &current_terminal_))
    return common::status_t::kFailure;
  return common::status_t::kSuccess;
}

}  // namespace util


text:
bitcoin-arbitrage-php
=====================


text:
package org.apache.beam.runners.dataflow.worker;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState;

import java.util.ArrayList;
import java.util.List;
import org.apache.beam.runners.core.DoFnRunner;
import org.apache.beam.runners.core.DoFnRunners;
import org.apache.beam.runners.core.DoFnRunners.OutputManager;
import org.apache.beam.runners.core.KeyedWorkItem;
import org.apache.beam.runners.core.KeyedWorkItems;
import org.apache.beam.runners.core.LateDataDroppingDoFnRunner;
import org.apache.beam.runners.core.SideInputReader;
import org.apache.beam.runners.core.TimerInternals;
import org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoFn;
import org.apache.beam.runners.dataflow.worker.util.common.worker.Receiver;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.StreamingOptions;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.WindowingStrategy;
import org.checkerframework.checker.nullness.qual.Nullable;

/** A specialized {@link ParDoFn} for GroupAlsoByWindow related {@link GroupAlsoByWindowFn}'s. */
@SuppressWarnings({
  "nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public class GroupAlsoByWindowsParDoFn<InputT, K, V, W extends BoundedWindow> implements ParDoFn {
  private final PipelineOptions options;

  private final SideInputReader sideInputReader;
  private final TupleTag<KV<K, Iterable<V>>> mainOutputTag;
  private final DataflowExecutionContext.DataflowStepContext stepContext;
  private final GroupAlsoByWindowFn<InputT, KV<K, Iterable<V>>> doFn;
  private final WindowingStrategy<?, W> windowingStrategy;
  private final Iterable<PCollectionView<?>> sideInputViews;
  private final Coder<InputT> inputCoder;

  // TODO: do not share this class, or refactor, in a way such that the guts need to do
  // different things based on whether it is streaming/batch, or what kind of GABW
  // function it is invoking
  private final boolean acceptsKeyedWorkItems;

  // Various DoFn helpers, null between bundles
  private @Nullable DoFnRunner<InputT, KV<K, Iterable<V>>> fnRunner;
  private @Nullable Receiver receiver;

  /**
   * Creates a {@link GroupAlsoByWindowsParDoFn} using basic information about the {@link
   * GroupAlsoByWindowFn} and the step being executed.
   */
  GroupAlsoByWindowsParDoFn(
      PipelineOptions options,
      GroupAlsoByWindowFn<InputT, KV<K, Iterable<V>>> doFn,
      WindowingStrategy<?, W> windowingStrategy,
      Iterable<PCollectionView<?>> sideInputViews,
      Coder<InputT> inputCoder,
      SideInputReader sideInputReader,
      TupleTag<KV<K, Iterable<V>>> mainOutputTag,
      DataflowExecutionContext.DataflowStepContext stepContext) {
    this.options = options;

    this.sideInputReader = sideInputReader;
    this.mainOutputTag = mainOutputTag;
    this.stepContext = stepContext;
    this.doFn = doFn;
    this.windowingStrategy = windowingStrategy;
    this.sideInputViews = sideInputViews;
    this.inputCoder = inputCoder;

    this.acceptsKeyedWorkItems = inputCoder instanceof WindmillKeyedWorkItem.FakeKeyedWorkItemCoder;
  }

  @Override
  public void startBundle(Receiver... receivers) throws Exception {
    checkState(fnRunner == null, "bundle already started (or not properly finished)");
    checkState(
        receivers.length == 1,
        "%s.startBundle() called with %s receivers, expected exactly 1. "
            + "This is a bug in the Dataflow service",
        getClass().getSimpleName(),
        receivers.length);
    receiver = receivers[0];
    fnRunner = createRunner();
    fnRunner.startBundle();
  }

  @Override
  @SuppressWarnings("unchecked")
  public void processElement(Object untypedElem) throws Exception {
    checkState(fnRunner != null);

    // TODO: do not do this with an "if"
    if (!acceptsKeyedWorkItems) {
      // The straightforward case: we don't need to mess with timers
      fnRunner.processElement((WindowedValue<InputT>) untypedElem);
    } else {
      // Gather timers just for this step
      Coder<W> windowCoder = windowingStrategy.getWindowFn().windowCoder();
      TimerInternals.TimerData timer;
      List<TimerInternals.TimerData> firedTimers = new ArrayList<>();
      while ((timer = stepContext.getNextFiredTimer(windowCoder)) != null) {
        firedTimers.add(timer);
      }

      // Build a new input with just the timers we should process
      WindowedValue<KeyedWorkItem<K, V>> typedElem =
          (WindowedValue<KeyedWorkItem<K, V>>) untypedElem;
      KeyedWorkItem<K, V> keyedWorkItemWithAllTheTimers = typedElem.getValue();
      KeyedWorkItem<K, V> keyedWorkItemWithJustMyTimers =
          KeyedWorkItems.workItem(
              keyedWorkItemWithAllTheTimers.key(),
              firedTimers,
              keyedWorkItemWithAllTheTimers.elementsIterable());

      fnRunner.processElement(
          (WindowedValue<InputT>) typedElem.withValue(keyedWorkItemWithJustMyTimers));
    }
  }

  @Override
  public void processTimers() throws Exception {
    // TODO: call ReduceFnRunner.onTimers here, without all the intervening
    // layers, or else process timers one key at a time and have access to
    // it here to build a KeyedWorkItem
  }

  @Override
  public void finishBundle() throws Exception {
    checkState(fnRunner != null);
    fnRunner.finishBundle();
    fnRunner = null;
  }

  @Override
  public void abort() throws Exception {
    fnRunner = null;
  }

  /**
   * Composes and returns a {@link DoFnRunner} based on the parameters.
   *
   *
A {@code SimpleOldDoFnRunner} executes the {@link GroupAlsoByWindowFn}.
   *
   *
A {@link LateDataDroppingDoFnRunner} handles late data dropping for a {@link
   * StreamingGroupAlsoByWindowViaWindowSetFn}.
   *
   *
A {@link StreamingSideInputDoFnRunner} handles streaming side inputs.
   *
   *
A {@link StreamingKeyedWorkItemSideInputDoFnRunner} handles streaming side inputs for a
   * {@link StreamingGroupAlsoByWindowViaWindowSetFn}.
   */
  private DoFnRunner<InputT, KV<K, Iterable<V>>> createRunner() {
    OutputManager outputManager =
        new OutputManager() {
          @Override
          public <T> void output(TupleTag<T> tag, WindowedValue<T> output) {
            checkState(
                tag.equals(mainOutputTag),
                "Must only output to main output tag (%s), but was %s",
                tag,
                mainOutputTag);
            try {
              receiver.process(output);
            } catch (Throwable t) {
              throw new RuntimeException(t);
            }
          }
        };

    boolean hasStreamingSideInput =
        options.as(StreamingOptions.class).isStreaming() && !sideInputReader.isEmpty();

    DoFnRunner<InputT, KV<K, Iterable<V>>> basicRunner =
        new GroupAlsoByWindowFnRunner<>(
            options, doFn, sideInputReader, outputManager, mainOutputTag, stepContext);

    if (doFn instanceof StreamingGroupAlsoByWindowViaWindowSetFn) {
      DoFnRunner<KeyedWorkItem<K, V>, KV<K, Iterable<V>>> streamingGABWRunner =
          (DoFnRunner<KeyedWorkItem<K, V>, KV<K, Iterable<V>>>) basicRunner;

      if (hasStreamingSideInput) {
        @SuppressWarnings("unchecked")
        WindmillKeyedWorkItem.FakeKeyedWorkItemCoder<K, V> keyedWorkItemCoder =
            (WindmillKeyedWorkItem.FakeKeyedWorkItemCoder<K, V>) inputCoder;
        StreamingSideInputFetcher<V, W> sideInputFetcher =
            new StreamingSideInputFetcher<>(
                sideInputViews,
                keyedWorkItemCoder.getElementCoder(),
                windowingStrategy,
                (StreamingModeExecutionContext.StreamingModeStepContext) stepContext);

        streamingGABWRunner =
            new StreamingKeyedWorkItemSideInputDoFnRunner<>(
                streamingGABWRunner,
                keyedWorkItemCoder.getKeyCoder(),
                sideInputFetcher,
                stepContext);
      }
      return (DoFnRunner<InputT, KV<K, Iterable<V>>>)
          DoFnRunners.<K, V, Iterable<V>, W>lateDataDroppingRunner(
              streamingGABWRunner, stepContext.timerInternals(), windowingStrategy);
    } else {
      if (hasStreamingSideInput) {
        return new StreamingSideInputDoFnRunner<>(
            basicRunner,
            new StreamingSideInputFetcher<>(
                sideInputViews,
                inputCoder,
                windowingStrategy,
                (StreamingModeExecutionContext.StreamingModeStepContext) stepContext));
      } else {
        return basicRunner;
      }
    }
  }
}


text:
namespace blink {

class ExceptionState;
class ReadableByteStreamController;
class ScriptPromise;
class ScriptState;

// Interface to be implemented by C++ code that needs to create a
// ReadableByteStream. Based on the JavaScript [UnderlyingSource
// API](https://streams.spec.whatwg.org/#underlying-source-api). Errors should
// be signalled by exceptions or promise rejections.
class CORE_EXPORT UnderlyingByteSourceBase
    : public GarbageCollected<UnderlyingByteSourceBase> {
 public:
  UnderlyingByteSourceBase() = default;
  UnderlyingByteSourceBase(const UnderlyingByteSourceBase&) = delete;
  UnderlyingByteSourceBase& operator=(const UnderlyingByteSourceBase&) = delete;
  virtual ~UnderlyingByteSourceBase() = default;

  virtual ScriptPromise Pull(ReadableByteStreamController* controller,
                             ExceptionState&) = 0;

  virtual ScriptPromise Cancel(ExceptionState&) = 0;
  virtual ScriptPromise Cancel(v8::Local<v8::Value> reason,
                               ExceptionState&) = 0;

  // Returns the ScriptState associated with this UnderlyingByteSource.
  virtual ScriptState* GetScriptState() = 0;

  virtual void Trace(Visitor*) const {}
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_UNDERLYING_BYTE_SOURCE_BASE_H_


text:
var packet = require('./')
var dgram = require('dgram')

var socket = dgram.createSocket('udp4')

var buf = packet.encode({
  type: 'query',
  id: 1,
  flags: packet.RECURSION_DESIRED,
  questions: [{
    type: 'A',
    name: 'google.com'
  }]
})

socket.on('message', function (message, rinfo) {
  console.log(rinfo)
  console.log(packet.decode(message)) // prints out a response from google dns
})

socket.send(buf, 0, buf.length, 53, '8.8.8.8')


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.martiansoftware.jsap.stringparsers (JSAP: the Java Simple Argument Parser)
</TITLE>

<META NAME="keywords" CONTENT="com.martiansoftware.jsap.stringparsers package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.martiansoftware.jsap.stringparsers

Class Summary

BigDecimalStringParser
A StringParser for parsing BigDecimals.

BigIntegerStringParser
A StringParser for parsing BigIntegers.

BooleanStringParser
A StringParser for parsing Booleans.

ByteStringParser
A StringParser for parsing Bytes.

CharacterStringParser
A StringParser for parsing Characters.

ClassStringParser
A StringParser for parsing Class objects.

ColorStringParser
A StringParser for parsing java.awt.Color objects.

DateStringParser
A StringParser for parsing java.util.Date objects.

DoubleStringParser
A StringParser for parsing Doubles.

EnumeratedStringParser
A StringParser that enforces a limited set of String options for its
 values.

FileStringParser
A StringParser for parsing File objects.

FloatStringParser
A StringParser for parsing Floats.

ForNameStringParser
A StringParser that passes the
 argument to a static method of signature forName(String) of a specified class.

InetAddressStringParser
A StringParser for parsing java.net.InetAddress objects.

IntegerStringParser
A StringParser for parsing Integers.

IntSizeStringParser
A StringParser that works like LongSizeStringParser, but
 additionally checks that the result is not larger than Integer.MAX_VALUE.

LongSizeStringParser
A StringParser that lets the user specify sizes with an optional unit.

LongStringParser
A StringParser for parsing Longs.

PackageStringParser
A StringParser for parsing Packages.

ShortStringParser
A StringParser for parsing Shorts.

StringStringParser
A StringParser for parsing Strings.

TestAll
Contains all of the tests in the stringparsers package.

TestColorStringParser
A series of tests for the ColorStringParser

TestLongStringParser
A series of tests for the LongStringParser

URLStringParser
A StringParser for parsing java.net.URL objects.

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2006, Martian Software, Inc..  All Rights Reserved.
For the latest version and documentation, please visit http://www.martiansoftware.com/jsap


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Indian Phytopath. 22(4): 513 (1970)

#### Original name
Pleurophragmium verruculosum D.P. Tiwari

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
        backupGlobals="false"
        backupStaticAttributes="false"
        bootstrap="tests/bootstrap.php"
        colors="true"
        convertErrorsToExceptions="true"
        convertNoticesToExceptions="true"
        convertWarningsToExceptions="true"
        >

    <testsuites>
        <testsuite name="src">
            <directory>./tests/src</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="coverage-html"
             target="tests/log/coverage"
             charset="UTF-8"
             yui="true"
             highlight="false"
             lowUpperBound="70"
             highLowerBound="90"
                />
        <log type="testdox-html" target="tests/log/testdox.html"/>
        <log type="coverage-clover" target="tests/log/coverage.xml" />
    </logging>
    <php>
        <ini name="error_reporting" value="E_ALL" />
    </php>
</phpunit>


text:
<template id="rx-drawboard" >

  <slot></slot>

    <button id="undoStroke">
      </button>
    <button id="redoStroke">
      </button>
    <lively-crayoncolors id="backgroundColor" title="background"></lively-crayoncolors>
    <lively-crayoncolors id="penColor" title="pen"></lively-crayoncolors>
    <lively-penchooser id="penSize"></lively-penchooser>
    <button id="loadFile"></button>
    <button id="activateSave"></button>

    <button id="close"></button>

  <lively-resizer></lively-resizer>

</template>


text:
/* STRUCTURES */

typedef struct list list;

/* LIST */

//Create a new list.
list* _list_new(standard_library_context*, size_t); //COMPLETE

//Delete a list.
void _list_delete(list*); //COMPLETE

//Add an item to the list.
void _list_add(list*, void*); //COMPLETE

//Get an item from the list.
void* _list_get(list*, size_t); //COMPLETE

//Remove an item from the list.
bool _list_remove(list*, size_t); //COMPLETE

//Reset the iterator.
void _list_reset_iterator(list*); //COMPLETE

//See if there are items left to be iterated through.
bool _list_has_next(list*); //COMPLETE

//Get the next item in the list.
void* _list_get_next(list*); //COMPLETE

//Set an item in the list.
bool _list_set(list*, size_t, void*);

//Merge two lists.
bool _list_merge(list*, list*);

#ifndef GENLIB_LINK_OBJECT_NCOMP

	#include "list_structs.c"
	#include "list.c"

#endif


text:
package org.hisp.dhis.android.core.indicator.internal;

import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter;
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkChildStore;
import org.hisp.dhis.android.core.arch.db.stores.internal.StoreFactory;
import org.hisp.dhis.android.core.arch.db.stores.projections.internal.LinkTableChildProjection;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.dataset.DataSet;
import org.hisp.dhis.android.core.indicator.DataSetIndicatorLinkTableInfo;
import org.hisp.dhis.android.core.indicator.Indicator;
import org.hisp.dhis.android.core.indicator.IndicatorTableInfo;

public final class DataSetIndicatorChildrenAppender extends ChildrenAppender<DataSet> {

    private static final LinkTableChildProjection CHILD_PROJECTION = new LinkTableChildProjection(
            IndicatorTableInfo.TABLE_INFO,
            DataSetIndicatorLinkTableInfo.Columns.DATA_SET,
            DataSetIndicatorLinkTableInfo.Columns.INDICATOR);
    private final LinkChildStore<DataSet, Indicator> linkChildStore;

    private DataSetIndicatorChildrenAppender(
            LinkChildStore<DataSet, Indicator> linkChildStore) {
        this.linkChildStore = linkChildStore;
    }

    @Override
    public DataSet appendChildren(DataSet dataSet) {
        DataSet.Builder builder = dataSet.toBuilder();
        builder.indicators(linkChildStore.getChildren(dataSet));
        return builder.build();
    }

    public static ChildrenAppender<DataSet> create(DatabaseAdapter databaseAdapter) {
        return new DataSetIndicatorChildrenAppender(
                StoreFactory.linkChildStore(
                        databaseAdapter,
                        DataSetIndicatorLinkTableInfo.TABLE_INFO,
                        CHILD_PROJECTION,
                        Indicator::create)
        );
    }
}


text:
namespace PcapDotNet.Packets
{
    /// <summary>
    /// A simple layer is a layer that doesn't care what is the length of its payload, what layer comes after it and what layer comes before it.
    /// </summary>
    public abstract class SimpleLayer : Layer
    {
        /// <summary>
        /// Writes the layer to the buffer.
        /// </summary>
        /// <param name="buffer">The buffer to write the layer to.</param>
        /// <param name="offset">The offset in the buffer to start writing the layer at.</param>
        /// <param name="payloadLength">The length of the layer's payload (the number of bytes after the layer in the packet).</param>
        /// <param name="previousLayer">The layer that comes before this layer. null if this is the first layer.</param>
        /// <param name="nextLayer">The layer that comes after this layer. null if this is the last layer.</param>
        public sealed override void Write(byte[] buffer, int offset, int payloadLength, ILayer previousLayer, ILayer nextLayer)
        {
            Write(buffer, offset);
        }

        /// <summary>
        /// Writes the layer to the buffer.
        /// This method ignores the payload length, and the previous and next layers.
        /// </summary>
        /// <param name="buffer">The buffer to write the layer to.</param>
        /// <param name="offset">The offset in the buffer to start writing the layer at.</param>
        protected abstract void Write(byte[] buffer, int offset);
    }
}


text:
/**
 * Slick
 * @see http://kenwheeler.github.io/slick/
 */

class SlickComponent {
  constructor(el, options = {}) {
    this.options = Object.assign({}, options);
    this.$slideshow = $(el);

    this.$slideshow.on('afterChange', this.autoPlayVideo);
    this.$slideshow.on('init', this.autoPlayVideo);

    if (this.checkVisibility()) {
      this.init();
    }

    $(window).on('changed.zf.mediaquery down.zf.accordion', () => {
      if (!this.isVisible() && this.checkVisibility()) {
        this.init();
      }
    });
  }

  init() {
    if (!this.$slideshow.hasClass('slick--no-slider')) {
      this.$slideshow.slick(this.options);
    }
  }

  isVisible() {
    return this._isVisible;
  }

  checkVisibility() {
    this._isVisible = this.$slideshow.is(':visible');
    return this.isVisible();
  }

  autoPlayVideo(e, slick) {
    const $slide = slick.$slides.eq(slick.currentSlide);
    const $video = $slide.find('video');
    if ($video.length) {
      $video[0].play();
    }
  }
}

export default function (selector = '.slick', options = {}) {
  $(selector)
    .each((i, el) => new SlickComponent(el, options));
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_bg_for_title"/>
</selector>


text:
package edu.pitt.apollo.libraryservicerestfrontend.methods;

import edu.pitt.apollo.exception.LibraryServiceException;
import edu.pitt.apollo.exception.UnsupportedAuthorizationTypeException;
import edu.pitt.apollo.library_service_types.v4_0_2.GetMembersOfCollectionResult;
import edu.pitt.apollo.services_common.v4_0_2.SerializationFormat;
import edu.pitt.isg.objectserializer.exceptions.SerializationException;
import edu.pitt.isg.objectserializer.exceptions.UnsupportedSerializationFormatException;
import org.springframework.http.HttpStatus;

/**
 * Created by jdl50 on 8/11/15.
 */
public class GetMembersOfCollectionMethod extends BaseLibraryServiceAccessorMethod {

	public GetMembersOfCollectionMethod(SerializationFormat serializationFormat, String authorizationHeader) throws UnsupportedSerializationFormatException, UnsupportedAuthorizationTypeException {
		super(serializationFormat, GetMembersOfCollectionResult.class, authorizationHeader);
	}

	public String getMembers(int urn, Integer version, Boolean includeUnreleasedItems) {

        GetMembersOfCollectionResult result;
        if (includeUnreleasedItems == null) {
            includeUnreleasedItems = false;
        }
		try {
			result = impl.getMembersOfCollection(urn, version, includeUnreleasedItems, authentication);
		} catch (LibraryServiceException ex) {
			responseBuilder.setStatus(HttpStatus.INTERNAL_SERVER_ERROR, ex.getClass().getName() + ": " + ex.getMessage());
			try {
				return serializer.serializeObject(responseBuilder.getResponse());
			} catch (SerializationException e1) {
				return "Error: " + e1.getClass().getName() + ": " + e1.getMessage();
			}
		}

		return getResponseAsString(result);

	}

}


text:
package info.debatty.java.stringsimilarity;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

/**
 *
 * @author Thibault Debatty
 */
public class DamerauTest {

    /**
     * Test of distance method, of class Damerau.
     */
    @Test
    public final void testDistance() {
        System.out.println("distance");
        Damerau instance = new Damerau();
        assertEquals(1.0, instance.distance("ABCDEF", "ABDCEF"), 0.0);
        assertEquals(2.0, instance.distance("ABCDEF", "BACDFE"), 0.0);
        assertEquals(1.0, instance.distance("ABCDEF", "ABCDE"), 0.0);
    }
}