text:
import * as React from "react";
import { DraggableEventHandler, default as DraggableRoot } from "react-draggable";
import { Enable, Resizable, ResizeDirection } from "re-resizable";

// FIXME: https://github.com/mzabriskie/react-draggable/issues/381
//         I can not find `scale` too...
type $TODO = any;
const Draggable: any = DraggableRoot;

export type Grid = [number, number];

export type Position = {
  x: number;
  y: number;
};

export type DraggableData = {
  node: HTMLElement;
  deltaX: number;
  deltaY: number;
  lastX: number;
  lastY: number;
} & Position;

export type RndDragCallback = DraggableEventHandler;

export type RndDragEvent =
  | React.MouseEvent<HTMLElement | SVGElement>
  | React.TouchEvent<HTMLElement | SVGElement>
  | MouseEvent
  | TouchEvent;

export type RndResizeStartCallback = (
  e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>,
  dir: ResizeDirection,
  elementRef: HTMLElement,
) => void | boolean;

export type ResizableDelta = {
  width: number;
  height: number;
};

export type RndResizeCallback = (
  e: MouseEvent | TouchEvent,
  dir: ResizeDirection,
  elementRef: HTMLElement,
  delta: ResizableDelta,
  position: Position,
) => void;

type Size = {
  width: string | number;
  height: string | number;
};

type State = {
  resizing: boolean;
  bounds: {
    top: number;
    right: number;
    bottom: number;
    left: number;
  };
  maxWidth?: number | string;
  maxHeight?: number | string;
};

type MaxSize = {
  maxWidth: number | string;
  maxHeight: number | string;
};

export type ResizeEnable =
  | {
      bottom?: boolean;
      bottomLeft?: boolean;
      bottomRight?: boolean;
      left?: boolean;
      right?: boolean;
      top?: boolean;
      topLeft?: boolean;
      topRight?: boolean;
    }
  | boolean;

export type HandleClasses = {
  bottom?: string;
  bottomLeft?: string;
  bottomRight?: string;
  left?: string;
  right?: string;
  top?: string;
  topLeft?: string;
  topRight?: string;
};

export type HandleStyles = {
  bottom?: React.CSSProperties;
  bottomLeft?: React.CSSProperties;
  bottomRight?: React.CSSProperties;
  left?: React.CSSProperties;
  right?: React.CSSProperties;
  top?: React.CSSProperties;
  topLeft?: React.CSSProperties;
  topRight?: React.CSSProperties;
};

export type HandleComponent = {
  top?: React.ReactElement<any>;
  right?: React.ReactElement<any>;
  bottom?: React.ReactElement<any>;
  left?: React.ReactElement<any>;
  topRight?: React.ReactElement<any>;
  bottomRight?: React.ReactElement<any>;
  bottomLeft?: React.ReactElement<any>;
  topLeft?: React.ReactElement<any>;
};

export interface Props {
  dragGrid?: Grid;
  default?: {
    x: number;
    y: number;
  } & Size;
  position?: {
    x: number;
    y: number;
  };
  size?: Size;
  resizeGrid?: Grid;
  bounds?: string;
  onMouseDown?: (e: MouseEvent) => void;
  onMouseUp?: (e: MouseEvent) => void;
  onResizeStart?: RndResizeStartCallback;
  onResize?: RndResizeCallback;
  onResizeStop?: RndResizeCallback;
  onDragStart?: RndDragCallback;
  onDrag?: RndDragCallback;
  onDragStop?: RndDragCallback;
  className?: string;
  style?: React.CSSProperties;
  children?: React.ReactNode;
  enableResizing?: ResizeEnable;
  resizeHandleClasses?: HandleClasses;
  resizeHandleStyles?: HandleStyles;
  resizeHandleWrapperClass?: string;
  resizeHandleWrapperStyle?: React.CSSProperties;
  resizeHandleComponent?: HandleComponent;
  lockAspectRatio?: boolean | number;
  lockAspectRatioExtraWidth?: number;
  lockAspectRatioExtraHeight?: number;
  maxHeight?: number | string;
  maxWidth?: number | string;
  minHeight?: number | string;
  minWidth?: number | string;
  dragAxis?: "x" | "y" | "both" | "none";
  dragHandleClassName?: string;
  disableDragging?: boolean;
  cancel?: string;
  enableUserSelectHack?: boolean;
  allowAnyClick?: boolean;
  scale?: number;
  [key: string]: any;
}

const resizableStyle = {
  width: "auto" as "auto",
  height: "auto" as "auto",
  display: "inline-block" as "inline-block",
  position: "absolute" as "absolute",
  top: 0,
  left: 0,
};

const getEnableResizingByFlag = (flag: boolean): Enable => ({
  bottom: flag,
  bottomLeft: flag,
  bottomRight: flag,
  left: flag,
  right: flag,
  top: flag,
  topLeft: flag,
  topRight: flag,
});

interface DefaultProps {
  maxWidth: number;
  maxHeight: number;
  onResizeStart: RndResizeStartCallback;
  onResize: RndResizeCallback;
  onResizeStop: RndResizeCallback;
  onDragStart: RndDragCallback;
  onDrag: RndDragCallback;
  onDragStop: RndDragCallback;
  scale: number;
}

export class Rnd extends React.PureComponent<Props, State> {
  public static defaultProps: DefaultProps = {
    maxWidth: Number.MAX_SAFE_INTEGER,
    maxHeight: Number.MAX_SAFE_INTEGER,
    scale: 1,
    onResizeStart: () => {},
    onResize: () => {},
    onResizeStop: () => {},
    onDragStart: () => {},
    onDrag: () => {},
    onDragStop: () => {},
  };
  resizable!: Resizable;
  draggable!: $TODO; // Draggable;
  resizingPosition = { x: 0, y: 0 };
  offsetFromParent = { left: 0, top: 0 };
  resizableElement: { current: HTMLElement | null } = { current: null };
  originalPosition = { x: 0, y: 0 };

  constructor(props: Props) {
    super(props);
    this.state = {
      resizing: false,
      bounds: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
      },
      maxWidth: props.maxWidth,
      maxHeight: props.maxHeight,
    };

    this.onResizeStart = this.onResizeStart.bind(this);
    this.onResize = this.onResize.bind(this);
    this.onResizeStop = this.onResizeStop.bind(this);
    this.onDragStart = this.onDragStart.bind(this);
    this.onDrag = this.onDrag.bind(this);
    this.onDragStop = this.onDragStop.bind(this);
    this.getMaxSizesFromProps = this.getMaxSizesFromProps.bind(this);
  }

  componentDidMount() {
    this.updateOffsetFromParent();
    const { left, top } = this.offsetFromParent;
    const { x, y } = this.getDraggablePosition();
    this.draggable.setState({
      x: x - left,
      y: y - top,
    });
    // HACK: Apply position adjustment
    this.forceUpdate();
  }

  // HACK: To get `react-draggable` state x and y.
  getDraggablePosition(): { x: number; y: number } {
    const { x, y } = (this.draggable as any).state;
    return { x, y };
  }

  getParent() {
    return this.resizable && (this.resizable as any).parentNode;
  }

  getParentSize(): { width: number; height: number } {
    return (this.resizable as any).getParentSize();
  }

  getMaxSizesFromProps(): MaxSize {
    const maxWidth = typeof this.props.maxWidth === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxWidth;
    const maxHeight = typeof this.props.maxHeight === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxHeight;
    return { maxWidth, maxHeight };
  }

  getSelfElement(): HTMLElement | null {
    return this.resizable && this.resizable.resizable;
  }

  getOffsetHeight(boundary: HTMLElement) {
    const scale = this.props.scale as number;
    switch (this.props.bounds) {
      case "window":
        return window.innerHeight / scale;
      case "body":
        return document.body.offsetHeight / scale;
      default:
        return boundary.offsetHeight;
    }
  }

  getOffsetWidth(boundary: HTMLElement) {
    const scale = this.props.scale as number;
    switch (this.props.bounds) {
      case "window":
        return window.innerWidth / scale;
      case "body":
        return document.body.offsetWidth / scale;
      default:
        return boundary.offsetWidth;
    }
  }

  onDragStart(e: RndDragEvent, data: DraggableData) {
    if (this.props.onDragStart) {
      this.props.onDragStart(e, data);
    }
    const pos = this.getDraggablePosition();
    this.originalPosition = pos;
    if (!this.props.bounds) return;
    const parent = this.getParent();
    const scale = this.props.scale as number;
    let boundary;
    if (this.props.bounds === "parent") {
      boundary = parent;
    } else if (this.props.bounds === "body") {
      const parentRect = parent.getBoundingClientRect();
      const parentLeft = parentRect.left;
      const parentTop = parentRect.top;
      const bodyRect = document.body.getBoundingClientRect();
      const left = -(parentLeft - parent.offsetLeft * scale - bodyRect.left) / scale;
      const top = -(parentTop - parent.offsetTop * scale - bodyRect.top) / scale;
      const right = (document.body.offsetWidth - this.resizable.size.width * scale) / scale + left;
      const bottom = (document.body.offsetHeight - this.resizable.size.height * scale) / scale + top;
      return this.setState({ bounds: { top, right, bottom, left } });
    } else if (this.props.bounds === "window") {
      if (!this.resizable) return;
      const parentRect = parent.getBoundingClientRect();
      const parentLeft = parentRect.left;
      const parentTop = parentRect.top;
      const left = -(parentLeft - parent.offsetLeft * scale) / scale;
      const top = -(parentTop - parent.offsetTop * scale) / scale;
      const right = (window.innerWidth - this.resizable.size.width * scale) / scale + left;
      const bottom = (window.innerHeight - this.resizable.size.height * scale) / scale + top;
      return this.setState({ bounds: { top, right, bottom, left } });
    } else {
      boundary = document.querySelector(this.props.bounds);
    }
    if (!(boundary instanceof HTMLElement) || !(parent instanceof HTMLElement)) {
      return;
    }
    const boundaryRect = boundary.getBoundingClientRect();
    const boundaryLeft = boundaryRect.left;
    const boundaryTop = boundaryRect.top;
    const parentRect = parent.getBoundingClientRect();
    const parentLeft = parentRect.left;
    const parentTop = parentRect.top;
    const left = (boundaryLeft - parentLeft) / scale;
    const top = boundaryTop - parentTop;
    if (!this.resizable) return;
    this.updateOffsetFromParent();
    const offset = this.offsetFromParent;
    this.setState({
      bounds: {
        top: top - offset.top,
        right: left + (boundary.offsetWidth - this.resizable.size.width) - offset.left / scale,
        bottom: top + (boundary.offsetHeight - this.resizable.size.height) - offset.top,
        left: left - offset.left / scale,
      },
    });
  }

  onDrag(e: RndDragEvent, data: DraggableData) {
    if (!this.props.onDrag) return;
    const { left, top } = this.offsetFromParent;
    if (!this.props.dragAxis || this.props.dragAxis === "both") {
      return this.props.onDrag(e, { ...data, x: data.x - left, y: data.y - top });
    } else if (this.props.dragAxis === "x") {
      return this.props.onDrag(e, { ...data, x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 });
    } else if (this.props.dragAxis === "y") {
      return this.props.onDrag(e, { ...data, x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 });
    }
  }

  onDragStop(e: RndDragEvent, data: DraggableData) {
    if (!this.props.onDragStop) return;
    const { left, top } = this.offsetFromParent;
    if (!this.props.dragAxis || this.props.dragAxis === "both") {
      return this.props.onDragStop(e, { ...data, x: data.x + left, y: data.y + top });
    } else if (this.props.dragAxis === "x") {
      return this.props.onDragStop(e, { ...data, x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 });
    } else if (this.props.dragAxis === "y") {
      return this.props.onDragStop(e, { ...data, x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 });
    }
  }

  onResizeStart(
    e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>,
    dir: ResizeDirection,
    elementRef: HTMLElement,
  ) {
    e.stopPropagation();
    this.setState({
      resizing: true,
    });
    const scale = this.props.scale as number;
    const offset = this.offsetFromParent;
    const pos = this.getDraggablePosition();
    this.resizingPosition = { x: pos.x + offset.left, y: pos.y + offset.top };
    this.originalPosition = pos;

    if (this.props.bounds) {
      const parent = this.getParent();
      let boundary;
      if (this.props.bounds === "parent") {
        boundary = parent;
      } else if (this.props.bounds === "body") {
        boundary = document.body;
      } else if (this.props.bounds === "window") {
        boundary = window;
      } else {
        boundary = document.querySelector(this.props.bounds);
      }

      const self = this.getSelfElement();
      if (
        self instanceof Element &&
        (boundary instanceof HTMLElement || boundary === window) &&
        parent instanceof HTMLElement
      ) {
        let { maxWidth, maxHeight } = this.getMaxSizesFromProps();
        const parentSize = this.getParentSize();
        if (maxWidth && typeof maxWidth === "string") {
          if (maxWidth.endsWith("%")) {
            const ratio = Number(maxWidth.replace("%", "")) / 100;
            maxWidth = parentSize.width * ratio;
          } else if (maxWidth.endsWith("px")) {
            maxWidth = Number(maxWidth.replace("px", ""));
          }
        }
        if (maxHeight && typeof maxHeight === "string") {
          if (maxHeight.endsWith("%")) {
            const ratio = Number(maxHeight.replace("%", "")) / 100;
            maxHeight = parentSize.width * ratio;
          } else if (maxHeight.endsWith("px")) {
            maxHeight = Number(maxHeight.replace("px", ""));
          }
        }
        const selfRect = self.getBoundingClientRect();
        const selfLeft = selfRect.left;
        const selfTop = selfRect.top;
        const boundaryRect = this.props.bounds === "window" ? { left: 0, top: 0 } : boundary.getBoundingClientRect();
        const boundaryLeft = boundaryRect.left;
        const boundaryTop = boundaryRect.top;
        const offsetWidth = this.getOffsetWidth(boundary);
        const offsetHeight = this.getOffsetHeight(boundary);
        const hasLeft = dir.toLowerCase().endsWith("left");
        const hasRight = dir.toLowerCase().endsWith("right");
        const hasTop = dir.startsWith("top");
        const hasBottom = dir.startsWith("bottom");

        if ((hasLeft || hasTop) && this.resizable) {
          const max = (selfLeft - boundaryLeft) / scale + this.resizable.size.width;
          this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
        }
        // INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story.
        if (hasRight || (this.props.lockAspectRatio && !hasLeft && !hasTop)) {
          const max = offsetWidth + (boundaryLeft - selfLeft) / scale;
          this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
        }
        if ((hasTop || hasLeft) && this.resizable) {
          const max = (selfTop - boundaryTop) / scale + this.resizable.size.height;
          this.setState({
            maxHeight: max > Number(maxHeight) ? maxHeight : max,
          });
        }
        // INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story.
        if (hasBottom || (this.props.lockAspectRatio && !hasTop && !hasLeft)) {
          const max = offsetHeight + (boundaryTop - selfTop) / scale;
          this.setState({
            maxHeight: max > Number(maxHeight) ? maxHeight : max,
          });
        }
      }
    } else {
      this.setState({
        maxWidth: this.props.maxWidth,
        maxHeight: this.props.maxHeight,
      });
    }
    if (this.props.onResizeStart) {
      this.props.onResizeStart(e, dir, elementRef);
    }
  }

  onResize(
    e: MouseEvent | TouchEvent,
    direction: ResizeDirection,
    elementRef: HTMLElement,
    delta: { height: number; width: number },
  ) {
    // INFO: Apply x and y position adjustments caused by resizing to draggable
    const newPos = { x: this.originalPosition.x, y: this.originalPosition.y };
    const left = -delta.width;
    const top = -delta.height;
    const directions = ["top", "left", "topLeft", "bottomLeft", "topRight"];

    if (directions.indexOf(direction) !== -1) {
      if (direction === "bottomLeft") {
        newPos.x += left;
      } else if (direction === "topRight") {
        newPos.y += top;
      } else {
        newPos.x += left;
        newPos.y += top;
      }
    }

    if (newPos.x !== this.draggable.state.x || newPos.y !== this.draggable.state.y) {
      this.draggable.setState(newPos);
    }

    this.updateOffsetFromParent();
    const offset = this.offsetFromParent;
    const x = this.getDraggablePosition().x + offset.left;
    const y = this.getDraggablePosition().y + offset.top;

    this.resizingPosition = { x, y };
    if (!this.props.onResize) return;
    this.props.onResize(e, direction, elementRef, delta, {
      x,
      y,
    });
  }

  onResizeStop(
    e: MouseEvent | TouchEvent,
    direction: ResizeDirection,
    elementRef: HTMLElement,
    delta: { height: number; width: number },
  ) {
    this.setState({
      resizing: false,
    });
    const { maxWidth, maxHeight } = this.getMaxSizesFromProps();
    this.setState({ maxWidth, maxHeight });
    if (this.props.onResizeStop) {
      this.props.onResizeStop(e, direction, elementRef, delta, this.resizingPosition);
    }
  }

  updateSize(size: { width: number | string; height: number | string }) {
    if (!this.resizable) return;
    this.resizable.updateSize({ width: size.width, height: size.height });
  }

  updatePosition(position: Position) {
    this.draggable.setState(position);
  }

  updateOffsetFromParent() {
    const scale = this.props.scale as number;
    const parent = this.getParent();
    const self = this.getSelfElement();
    if (!parent || self === null) {
      return {
        top: 0,
        left: 0,
      };
    }
    const parentRect = parent.getBoundingClientRect();
    const parentLeft = parentRect.left;
    const parentTop = parentRect.top;
    const selfRect = self.getBoundingClientRect();
    const position = this.getDraggablePosition();
    const scrollLeft = parent.scrollLeft;
    const scrollTop = parent.scrollTop;
    this.offsetFromParent = {
      left: selfRect.left - parentLeft + scrollLeft - position.x * scale,
      top: selfRect.top - parentTop + scrollTop - position.y * scale,
    };

  }

  refDraggable = (c: $TODO) => {
    if (!c) return;
    this.draggable = c;
  };

  refResizable = (c: Resizable | null) => {
    if (!c) return;
    this.resizable = c;
    this.resizableElement.current = c.resizable;
  };

  render() {
    const {
      disableDragging,
      style,
      dragHandleClassName,
      position,
      onMouseDown,
      onMouseUp,
      dragAxis,
      dragGrid,
      bounds,
      enableUserSelectHack,
      cancel,
      children,
      onResizeStart,
      onResize,
      onResizeStop,
      onDragStart,
      onDrag,
      onDragStop,
      resizeHandleStyles,
      resizeHandleClasses,
      resizeHandleComponent,
      enableResizing,
      resizeGrid,
      resizeHandleWrapperClass,
      resizeHandleWrapperStyle,
      scale,
      allowAnyClick,
      ...resizableProps
    } = this.props;
    const defaultValue = this.props.default ? { ...this.props.default } : undefined;
    // Remove unknown props, see also https://reactjs.org/warnings/unknown-prop.html
    delete resizableProps.default;

    const cursorStyle = disableDragging || dragHandleClassName ? { cursor: "auto" } : { cursor: "move" };
    const innerStyle = {
      ...resizableStyle,
      ...cursorStyle,
      ...style,
    };
    const { left, top } = this.offsetFromParent;
    let draggablePosition;
    if (position) {
      draggablePosition = {
        x: position.x - left,
        y: position.y - top,
      };
    }
    // INFO: Make uncontorolled component when resizing to control position by setPostion.
    const pos = this.state.resizing ? undefined : draggablePosition;
    const dragAxisOrUndefined = this.state.resizing ? "both" : dragAxis;

    return (
      <Draggable
        ref={this.refDraggable}
        handle={dragHandleClassName ? `.${dragHandleClassName}` : undefined}
        defaultPosition={defaultValue}
        onMouseDown={onMouseDown}
        onMouseUp={onMouseUp}
        onStart={this.onDragStart}
        onDrag={this.onDrag}
        onStop={this.onDragStop}
        axis={dragAxisOrUndefined}
        disabled={disableDragging}
        grid={dragGrid}
        bounds={bounds ? this.state.bounds : undefined}
        position={pos}
        enableUserSelectHack={enableUserSelectHack}
        cancel={cancel}
        scale={scale}
        allowAnyClick={allowAnyClick}
        nodeRef={this.resizableElement}
      >
        <Resizable
          {...resizableProps}
          ref={this.refResizable}
          defaultSize={defaultValue}
          size={this.props.size}
          enable={typeof enableResizing === "boolean" ? getEnableResizingByFlag(enableResizing) : enableResizing}
          onResizeStart={this.onResizeStart}
          onResize={this.onResize}
          onResizeStop={this.onResizeStop}
          style={innerStyle}
          minWidth={this.props.minWidth}
          minHeight={this.props.minHeight}
          maxWidth={this.state.resizing ? this.state.maxWidth : this.props.maxWidth}
          maxHeight={this.state.resizing ? this.state.maxHeight : this.props.maxHeight}
          grid={resizeGrid}
          handleWrapperClass={resizeHandleWrapperClass}
          handleWrapperStyle={resizeHandleWrapperStyle}
          lockAspectRatio={this.props.lockAspectRatio}
          lockAspectRatioExtraWidth={this.props.lockAspectRatioExtraWidth}
          lockAspectRatioExtraHeight={this.props.lockAspectRatioExtraHeight}
          handleStyles={resizeHandleStyles}
          handleClasses={resizeHandleClasses}
          handleComponent={resizeHandleComponent}
          scale={this.props.scale}
        >
          {children}
        </Resizable>
      </Draggable>
    );
  }
}


text:
package ma.glasnost.orika.test.object;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.test.MappingUtil;
import org.junit.Assert;
import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

public class InverseMappingTestCase {

    @Test
    public void testInverseOneToOneMapping() {
        MapperFactory mapperFactory = MappingUtil.getMapperFactory();

        ClassMapBuilder<PersonDTO, Person> classMapBuilder = mapperFactory.classMap(PersonDTO.class, Person.class);
        classMapBuilder.fieldMap("address").bInverse("person").add();
        mapperFactory.registerClassMap(classMapBuilder.byDefault().toClassMap());

        MapperFacade mapper = mapperFactory.getMapperFacade();

        AddressDTO addressDTO = new AddressDTO();
        addressDTO.setLine1("5 rue Blida");
        addressDTO.setLine2("20100 Casablanca");

        PersonDTO personDTO = new PersonDTO();
        personDTO.setFirstName("Khalil");
        personDTO.setLastName("Gibran");
        personDTO.setAddress(addressDTO);

        Person person = mapper.map(personDTO, Person.class);

        Assert.assertEquals(personDTO.getFirstName(), person.getFirstName());
        Assert.assertEquals(personDTO.getAddress().getLine1(), person.getAddress().getLine1());

        Assert.assertTrue(person == person.getAddress().getPerson());
    }

    @Test
    public void testInverseOneToManyMapping() {
        MapperFactory mapperFactory = MappingUtil.getMapperFactory();

        ClassMapBuilder<PublisherDTO, Publisher> classMapBuilder = mapperFactory.classMap(PublisherDTO.class, Publisher.class);
        classMapBuilder.fieldMap("books").bInverse("publisher").add();
        mapperFactory.registerClassMap(classMapBuilder.byDefault().toClassMap());

        MapperFacade mapper = mapperFactory.getMapperFacade();

        BookDTO parisNoirDTO = new BookDTO();
        parisNoirDTO.setTitle("Paris Noir");

        BookDTO chiensFousDTO = new BookDTO();
        chiensFousDTO.setTitle("Chiens Fous");

        PublisherDTO publisherDTO = new PublisherDTO();
        publisherDTO.setName("Asphalte Editions");
        publisherDTO.getBooks().add(parisNoirDTO);
        publisherDTO.getBooks().add(chiensFousDTO);

        Publisher publisher = mapper.map(publisherDTO, Publisher.class);

        Assert.assertTrue(publisher == publisher.getBooks().iterator().next().getPublisher());
    }

    @Test
    public void testInverseManyToOneMapping() {
        MapperFactory mapperFactory = MappingUtil.getMapperFactory();

        ClassMapBuilder<BookDTO, Book> classMapBuilder = mapperFactory.classMap(BookDTO.class, Book.class);
        classMapBuilder.fieldMap("author").bInverse("books").add();
        mapperFactory.registerClassMap(classMapBuilder.byDefault().toClassMap());

        MapperFacade mapper = mapperFactory.getMapperFacade();

        AuthorDTO authorDTO = new AuthorDTO();
        authorDTO.setFirstName("Khalil");
        authorDTO.setLastName("Gibran");

        BookDTO bookDTO = new BookDTO();
        bookDTO.setTitle("The Prophet");
        bookDTO.setAuthor(authorDTO);

        Book book = mapper.map(bookDTO, Book.class);

        Assert.assertTrue(book.getAuthor().getBooks().contains(book));
    }

    @Test
    public void testInverseManyToManyMapping() {
        MapperFactory mapperFactory = MappingUtil.getMapperFactory();

        ClassMapBuilder<ReaderDTO, Reader> classMapBuilder = mapperFactory.classMap(ReaderDTO.class, Reader.class);
        classMapBuilder.fieldMap("books").bInverse("readers").add();
        mapperFactory.registerClassMap(classMapBuilder.byDefault().toClassMap());

        MapperFacade mapper = mapperFactory.getMapperFacade();

        Set<BookDTO> bookDTOs = new HashSet<>();
        BookDTO bookDTO = new BookDTO();
        bookDTO.setTitle("The Prophet");
        bookDTOs.add(bookDTO);
        bookDTO = new BookDTO();
        bookDTO.setTitle("More Effective Java");
        bookDTOs.add(bookDTO);

        ReaderDTO readerDTO = new ReaderDTO();
        readerDTO.setFirstName("Jennifer");
        readerDTO.setLastName("Lopez");
        readerDTO.setBooks(bookDTOs);

        Reader reader = mapper.map(readerDTO, Reader.class);

        for (Book book : reader.getBooks()) {
            Assert.assertTrue(book.getReaders().contains(reader));
        }
    }

    public static class Person {

        private String firstName;

        private String lastName;

        private Address address;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }

    }

    public static class Address {

        private String line1;

        private String line2;

        private Person person;

        public String getLine1() {
            return line1;
        }

        public void setLine1(String line1) {
            this.line1 = line1;
        }

        public String getLine2() {
            return line2;
        }

        public void setLine2(String line2) {
            this.line2 = line2;
        }

        public Person getPerson() {
            return person;
        }

        public void setPerson(Person person) {
            this.person = person;
        }

    }

    public static class Book {

        private String title;

        private Author author;

        private Publisher publisher;

        private Set<Reader> readers;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Author getAuthor() {
            return author;
        }

        public void setAuthor(Author author) {
            this.author = author;
        }

        public Publisher getPublisher() {
            return publisher;
        }

        public void setPublisher(Publisher publisher) {
            this.publisher = publisher;
        }

        public Set<Reader> getReaders() {
            return readers;
        }

        public void setReaders(Set<Reader> readers) {
            this.readers = readers;
        }

    }

    public static class Author extends Person {

        private Set<Book> books;

        public Set<Book> getBooks() {
            return books;
        }

        public void setBooks(Set<Book> books) {
            this.books = books;
        }

    }

    public static class Reader extends Person {

        private Set<Book> books;

        public Set<Book> getBooks() {
            return books;
        }

        public void setBooks(Set<Book> books) {
            this.books = books;
        }

    }

    public static class Publisher {

        private String name;

        private Set<Book> books;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Set<Book> getBooks() {
            return books;
        }

        public void setBooks(Set<Book> books) {
            this.books = books;
        }

    }

    public static class PersonDTO {

        private String firstName;

        private String lastName;

        private AddressDTO address;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public AddressDTO getAddress() {
            return address;
        }

        public void setAddress(AddressDTO address) {
            this.address = address;
        }

    }

    public static class AddressDTO {

        private String line1;

        private String line2;

        public String getLine1() {
            return line1;
        }

        public void setLine1(String line1) {
            this.line1 = line1;
        }

        public String getLine2() {
            return line2;
        }

        public void setLine2(String line2) {
            this.line2 = line2;
        }

    }

    public static class BookDTO {

        private String title;

        private AuthorDTO author;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public AuthorDTO getAuthor() {
            return author;
        }

        public void setAuthor(AuthorDTO author) {
            this.author = author;
        }

    }

    public static class AuthorDTO extends PersonDTO {

    }

    public static class ReaderDTO extends PersonDTO {

        private Set<BookDTO> books;

        public Set<BookDTO> getBooks() {
            return books;
        }

        public void setBooks(Set<BookDTO> books) {
            this.books = books;
        }

    }

    public static class PublisherDTO {

        private String name;

        private Set<BookDTO> books = new HashSet<>();

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Set<BookDTO> getBooks() {
            return books;
        }

        public void setBooks(Set<BookDTO> books) {
            this.books = books;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
CLIFFHANGER

    <uib-alert ng-repeat="alert in alerts" type="danger" close="closeAlert($index)" dismiss-on-timeout="5000">{{alert}}</uib-alert>

Login

                <form class="form" role="form" id="login-form" name="loginForm">

                        Username
                        <input ng-model="username" type="text" class="form-control" id="inputUsername" placeholder="Username" required>

                        Password
                        <input ng-model="password" type="password" class="form-control" id="inputPassword" placeholder="Password" required>

                        <button ng-click="login()" type="submit" class="btn btn-primary btn-block" ng-disabled="loginForm.$invalid">Sign In</button>

                </form>

New Account

                <form class="form" role="form" id="register-form" name="registerForm">

                        Username
                        <input ng-model="newUser.username" type="text" class="form-control" id="inputNewUsername" placeholder="Username" required>

                        Password
                        <input ng-model="newUser.password" type="password" class="form-control" id="inputNewPassword1" placeholder="Password" required>

                    <div class="alert alert-danger" ng-show="newUser.password.length < 6">Passwords must be at least 6 characters long.

                        Confirm Password
                        <input ng-model="newUser.passwordConfirm" type="password" class="form-control" id="inputNewPassword2" placeholder="Password" required>

Passwords must match

                    Select a user role:

                        Analyst
                        Developer

                        <button ng-click="register()" type="submit" class="btn btn-success btn-block" ng-disabled="invalidRole || passwordMismatch || registerForm.$invalid">Create</button>

                </form>


text:
<?php namespace App\Services\Providers\Lastfm;

use App\Services\HttpClient;
use App\Services\Search\SearchInterface;

class LastfmSearch implements SearchInterface {

    /**
     * @var HttpClient
     */
    private $httpClient;

    /**
     * @var mixed
     */
    private $apiKey;

    /**
     * Create new SpotifySearch instance.
     */
    public function __construct() {
        $this->httpClient = new HttpClient(['base_uri' => 'http://ws.audioscrobbler.com/2.0/']);
        $this->apiKey = config('site.lastfm.key');
    }

    /**
     * Search using last.fm api and given params.
     *
     * @param string  $q
     * @param int     $limit
     *
     * @return array
     */
    public function search($q, $limit = 10)
    {
        $queryString = "$q&api_key={$this->apiKey}&format=json&limit=$limit&autocorrect=1";

        $artists = $this->httpClient->get('?method=artist.search&artist='.$queryString);
        $tracks  = $this->httpClient->get('?method=track.search&track='.$queryString);
        $albums  = $this->httpClient->get('?method=album.search&album='.$queryString);

        return $this->formatResponse([
            'artists' => head($artists['results']['artistmatches']),
            'albums'  => head($albums['results']['albummatches']),
            'tracks'  => $this->getFullTracks(head($tracks['results']['trackmatches'])),
        ]);
    }

    /**
     * Format and normalize lastfm response for use in our app.
     *
     * @param array   $response
     *
     * @return array
     */
    private function formatResponse($response) {

        $formatted = ['albums' => [], 'tracks' => [], 'artists' => []];

        $formatted['albums'] = array_map(function($album) {
            return [
                'name' => $album['name'],
                'image' => ! empty($album['image']) ? last($album['image'])['#text'] : null,
                'artist'  => [
                    'name' => $album['artist'],
                    'fully_scraped' => 0
                ]
            ];
        }, $response['albums']);

        $formatted['tracks'] = array_map(function($track) {
            return [
                'name' => $track['name'],
                'image' => ! empty($track['album']['image']) ? head($track['album']['image'])['#text'] : null,
                'lastfm_popularity' => (int) $track['listeners'],
                'duration' => (int) $track['duration'],
                'artists'  => [$track['artist']],
                'number'   => 0,
                'album'    => [
                    'name' => $track['album']['title'],
                    'artist' => $track['album']['artist'],
                ],
            ];
        }, $response['tracks']);

        $formatted['artists'] = array_map(function($artist) {
            return [
                'name' => $artist['name'],
                'image_small' => ! empty($artist['image']) ? $artist['image'][1]['#text'] : null,
                'image_large' => ! empty($artist['image']) ? last($artist['image'])['#text'] : null,
                'lastfm_popularity' => (int) $artist['listeners']
            ];
        }, $response['artists']);

        return $formatted;
    }

    private function getFullTracks($tracks) {
        $ids = array_map(function($t) { return $t['mbid']; }, $tracks);

        return array_map(function($id) {
            return head($this->httpClient->get("?method=track.getInfo&mbid=$id&api_key={$this->apiKey}&format=json"));
        }, $ids);
    }
}


text:
#ifndef ELEKTRA_ERROR_HPP
#define ELEKTRA_ERROR_HPP

#include "errors/warning.hpp"
#include <vector>

namespace kdb
{
namespace tools
{

namespace errors
{

class Error : public BaseNotification
{
public:
	/* inherit constructors */
	using BaseNotification::BaseNotification;
	virtual ~Error ();

	/**
	 * @brief Add a warning to an error
	 *
	 * The warning is copied to make it independent from the source object.
	 * This way the same warning added to two different errors can be
	 * changed independently.
	 *
	 * An object of type `Error` can contain 0 to n warnings,
	 * like Keys in the C-API can contain one error,
	 * but multiple warnings.
	 *
	 * @param warning the warning to add
	 */
	void addWarning (Warning & warning);

	/* getters */
	kdb::long_t warningCount ();

	/* iterator functionality */
	std::vector<Warning *>::iterator begin ()
	{
		return warnings.begin ();
	}
	std::vector<Warning *>::iterator end ()
	{
		return warnings.end ();
	}
	std::vector<Warning *>::const_iterator begin () const
	{
		return warnings.begin ();
	}
	std::vector<Warning *>::const_iterator end () const
	{
		return warnings.begin ();
	}
	std::vector<Warning *>::const_iterator cbegin () const
	{
		return warnings.cbegin ();
	}
	std::vector<Warning *>::const_iterator cend () const
	{
		return warnings.cend ();
	}

	/* get warning by index */
	Warning & operator[] (int index);

private:
	std::vector<Warning *> warnings;

protected:
	/**
	 * @brief Compare errors
	 *
	 * The comparison of data fields is done by operator== in the BaseNotification class.
	 * This function compares an errors warnings in addition to the notification fields.
	 *
	 * @param other the notification to compare to
	 *
	 * @return true if objects are equal
	 */
	bool compare (const BaseNotification & other) const override;

	/**
	 * @brief Create a text representation of the Error
	 *
	 * A string that contains the text representation
	 * defined by baseNotification.cpp as well as the
	 * text representation of all warnings that the
	 * Error object contains appended to the given stream.
	 *
	 * @param outputStream The stream were the string representations
	 * should be appended.
	 *
	 * @return The given stream with the created string
	 * written to it.
	 */
	std::ostream & toString (std::ostream & outputStream) const override;
};
} // namespace errors
} // namespace tools
} // namespace kdb

#endif // ELEKTRA_ERROR_HPP


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.EmployerAccounts.Commands.AuditCommand;
using SFA.DAS.EmployerAccounts.Commands.PublishGenericEvent;
using SFA.DAS.EmployerAccounts.Commands.RemoveLegalEntity;
using SFA.DAS.EmployerAccounts.Data;
using SFA.DAS.EmployerAccounts.Events.Agreement;
using SFA.DAS.EmployerAccounts.Factories;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.MarkerInterfaces;
using SFA.DAS.EmployerAccounts.Messages.Events;
using SFA.DAS.EmployerAccounts.Models.Account;
using SFA.DAS.EmployerAccounts.Models.AccountTeam;
using SFA.DAS.EmployerAccounts.Models.EmployerAgreement;
using SFA.DAS.Events.Api.Types;
using SFA.DAS.HashingService;
using SFA.DAS.NLog.Logger;
using SFA.DAS.NServiceBus.Services;
using SFA.DAS.Validation;

namespace SFA.DAS.EmployerAccounts.UnitTests.Commands.RemoveLegalEntityTests
{
    public class WhenIRemoveALegalEntity
    {
        private RemoveLegalEntityCommandHandler _handler;
        private Mock<IValidator<RemoveLegalEntityCommand>> _validator;
        private Mock<ILog> _logger;
        private Mock<IEmployerAgreementRepository> _repository;
        private RemoveLegalEntityCommand _command;
        private Mock<IMediator> _mediator;
        private Mock<IHashingService> _hashingService;
        private Mock<IAccountLegalEntityPublicHashingService> _accountLegalEntityPublicHashingService;
        private Mock<IGenericEventFactory> _genericEventHandler;
        private Mock<IEmployerAgreementEventFactory> _employerAgreementEventFactory;
        private Mock<IMembershipRepository> _membershipRepository;
        private Mock<IEventPublisher> _eventPublisher;
        private Mock<ICommitmentsV2ApiClient> _commitmentsV2ApiClient;

        private const string ExpectedHashedAccountId = "34RFD";
        private const long ExpectedAccountId = 123455;
        private const long ExpectedLegalEntityId = 98854;
        private const string ExpectedLegalEntityName = "Hogwarts";
        private const long ExpectedAccountLegalEntityId = 2017;
        private readonly string _expectedUserId = Guid.NewGuid().ToString();
        private EmployerAgreementView _expectedAgreement;
        private const long ExpectedEmployerAgreementId = 5533678;
        private const string ExpectedHashedEmployerAgreementId = "FGDFH45645";
        private const string ExpectedHashedAccountLegalEntityId = "HDHFFS";

        [SetUp]
        public void Arrange()
        {
            _validator = new Mock<IValidator<RemoveLegalEntityCommand>>();
            _validator.Setup(x => x.ValidateAsync(It.IsAny<RemoveLegalEntityCommand>())).ReturnsAsync(new ValidationResult());

            _logger = new Mock<ILog>();

            _mediator = new Mock<IMediator>();

            _repository = new Mock<IEmployerAgreementRepository>();
            _repository.Setup(r => r.GetAccountLegalEntityAgreements(ExpectedAccountLegalEntityId))
                .ReturnsAsync(new List<EmployerAgreement>
                {
                    new EmployerAgreement
                    {
                        AccountLegalEntityId = ExpectedAccountLegalEntityId,
                        TemplateId = 1,
                        Id = ExpectedEmployerAgreementId,
                        SignedDate = DateTime.Now
                    }
                });

            _expectedAgreement = new EmployerAgreementView
            {
                AccountLegalEntityId = ExpectedAccountLegalEntityId,
                LegalEntityId = ExpectedLegalEntityId,
                LegalEntityName = ExpectedLegalEntityName,
                Status = EmployerAgreementStatus.Signed,
                LegalEntityCode = "test_code"
            };

            _repository.Setup(r => r.GetEmployerAgreement(ExpectedEmployerAgreementId)).ReturnsAsync(_expectedAgreement);

            _hashingService = new Mock<IHashingService>();
            _hashingService.Setup(x => x.DecodeValue(ExpectedHashedAccountId)).Returns(ExpectedAccountId);
            _hashingService.Setup(x => x.DecodeValue(ExpectedHashedEmployerAgreementId)).Returns(ExpectedEmployerAgreementId);
            _hashingService.Setup(x => x.HashValue(ExpectedEmployerAgreementId)).Returns(ExpectedHashedEmployerAgreementId);

            _accountLegalEntityPublicHashingService = new Mock<IAccountLegalEntityPublicHashingService>();
            _accountLegalEntityPublicHashingService.Setup(x => x.DecodeValue(ExpectedHashedAccountLegalEntityId)).Returns(ExpectedAccountLegalEntityId);

            _employerAgreementEventFactory = new Mock<IEmployerAgreementEventFactory>();
            _employerAgreementEventFactory.Setup(x => x.RemoveAgreementEvent(ExpectedHashedEmployerAgreementId)).Returns(new AgreementRemovedEvent { HashedAgreementId = ExpectedHashedEmployerAgreementId });
            _genericEventHandler = new Mock<IGenericEventFactory>();
            _genericEventHandler.Setup(x => x.Create(It.Is<AgreementRemovedEvent>(c => c.HashedAgreementId.Equals(ExpectedHashedEmployerAgreementId)))).Returns(new GenericEvent { Payload = ExpectedHashedEmployerAgreementId });

            _membershipRepository = new Mock<IMembershipRepository>();
            _membershipRepository
                .Setup(mr => mr.GetCaller(ExpectedAccountId, _expectedUserId))
                .Returns<long, string>((accountId, userRef) => Task.FromResult(new MembershipView {AccountId = ExpectedAccountId, FirstName = "Harry", LastName = "Potter"}));

            _eventPublisher = new Mock<IEventPublisher>();

            _commitmentsV2ApiClient = new Mock<ICommitmentsV2ApiClient>();
            _commitmentsV2ApiClient
              .Setup(x => x.GetEmployerAccountSummary(ExpectedAccountId))
              .ReturnsAsync(new GetApprenticeshipStatusSummaryResponse()
              {
                  ApprenticeshipStatusSummaryResponse = new List<ApprenticeshipStatusSummaryResponse>()
                  {
                        new ApprenticeshipStatusSummaryResponse()
                        {
                            ActiveCount = 0,
                            PausedCount = 0,
                            PendingApprovalCount = 0,
                            CompletedCount = 0,
                            LegalEntityIdentifier = _expectedAgreement.LegalEntityCode
                        }
                  }

              });

            _command = new RemoveLegalEntityCommand { HashedAccountId = ExpectedHashedAccountId, UserId = _expectedUserId, HashedAccountLegalEntityId = ExpectedHashedAccountLegalEntityId };

            _handler = new RemoveLegalEntityCommandHandler(
                _validator.Object,
                _logger.Object,
                _repository.Object,
                _mediator.Object,
                _accountLegalEntityPublicHashingService.Object,
                _hashingService.Object,
                _genericEventHandler.Object,
                _employerAgreementEventFactory.Object,
                _membershipRepository.Object,
                _eventPublisher.Object,
                _commitmentsV2ApiClient.Object);
        }

        [Test]
        public void ThenTheValidatorIsCalledAndAnInvalidRequestExceptionThrownIfItIsNotValid()
        {
            //Arrange
            _validator.Setup(x => x.ValidateAsync(It.IsAny<RemoveLegalEntityCommand>())).ReturnsAsync(new ValidationResult { ValidationDictionary = new Dictionary<string, string> { { "", "" } } });

            //Act Assert
            Assert.ThrowsAsync<InvalidRequestException>(async () => await _handler.Handle(new RemoveLegalEntityCommand()));
        }

        [Test]
        public void ThenTheValidatorIsCalledAndAnUnauthorizedAccessExceptionIsThrownIfItIsNotAuthorized()
        {
            //Arrange
            _validator.Setup(x => x.ValidateAsync(It.IsAny<RemoveLegalEntityCommand>())).ReturnsAsync(new ValidationResult { IsUnauthorized = true });

            //Act Assert
            Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await _handler.Handle(new RemoveLegalEntityCommand()));
            _logger.Verify(x => x.Info(It.IsAny<string>()));
        }

        [Test]
        public async Task ThenTheRepositoryIsCalled()
        {
            //Act
            await _handler.Handle(_command);

            //Assert
            _validator.Verify(x => x.ValidateAsync(It.Is<RemoveLegalEntityCommand>(c =>
                                                                          c.HashedAccountId.Equals(ExpectedHashedAccountId)
                                                                          && c.UserId.Equals(_expectedUserId))));

            _repository.Verify(x => x.GetAccountLegalEntityAgreements(ExpectedAccountLegalEntityId));
            _repository.Verify(x => x.GetEmployerAgreement(ExpectedEmployerAgreementId));
            _repository.Verify(x => x.RemoveLegalEntityFromAccount(ExpectedEmployerAgreementId));
        }

        [Test]
        public async Task ThenTheAuditIsWrittenToWhenTheItemIsRemoved()
        {
            //Act
            await _handler.Handle(_command);

            //Assert
            _mediator.Verify(x => x.SendAsync(It.Is<CreateAuditCommand>(c =>
                      c.EasAuditMessage.ChangedProperties.SingleOrDefault(y => y.PropertyName.Equals("Status") && y.NewValue.Equals(EmployerAgreementStatus.Removed.ToString())) != null
                    )));
            _mediator.Verify(x => x.SendAsync(It.Is<CreateAuditCommand>(c =>
                      c.EasAuditMessage.Description.Equals($"EmployerAgreement {ExpectedHashedEmployerAgreementId} removed from account {ExpectedAccountId}"))));
            _mediator.Verify(x => x.SendAsync(It.Is<CreateAuditCommand>(c =>
                      c.EasAuditMessage.RelatedEntities.SingleOrDefault(y => y.Id.Equals(ExpectedAccountId.ToString()) && y.Type.Equals("Account")) != null
                    )));
            _mediator.Verify(x => x.SendAsync(It.Is<CreateAuditCommand>(c =>
                    c.EasAuditMessage.AffectedEntity.Id.Equals(ExpectedHashedEmployerAgreementId.ToString()) &&
                    c.EasAuditMessage.AffectedEntity.Type.Equals("EmployerAgreement")
                    )));
        }

        [Test]
        public async Task ThenTheEventIsFired()
        {
            //Act
            await _handler.Handle(_command);

            //Assert
            _genericEventHandler.Verify(x => x.Create(It.IsAny<AgreementRemovedEvent>()), Times.Once);
            _mediator.Verify(x => x.SendAsync(It.Is<PublishGenericEventCommand>(c => c.Event.Payload.Equals(ExpectedHashedEmployerAgreementId))));
        }

        [Test]
        public async Task ThenTheRemovedLegalEntityEventIsPublished()
        {
            await _handler.Handle(_command);

            _eventPublisher.Verify(ep => ep.Publish(It.Is<RemovedLegalEntityEvent>(e =>
                e.AccountId.Equals(ExpectedAccountId)
                && e.AgreementId.Equals(ExpectedEmployerAgreementId)
                && e.LegalEntityId.Equals(ExpectedLegalEntityId)
                && e.AgreementSigned.Equals(true)
                && e.OrganisationName.Equals(ExpectedLegalEntityName)
                && e.AccountLegalEntityId.Equals(ExpectedAccountLegalEntityId)
                && e.UserName.Equals("Harry Potter")
                && e.UserRef.Equals(Guid.Parse(_expectedUserId))
                )));
        }

        [Test]
        public async Task ThenTheAgreementIsCheckedToSeeIfItHasBeenSignedAndHasActiveCommitments()
        {
            _commitmentsV2ApiClient
                  .Setup(x => x.GetEmployerAccountSummary(ExpectedAccountId))
                  .ReturnsAsync(new GetApprenticeshipStatusSummaryResponse()
                  {
                      ApprenticeshipStatusSummaryResponse = new List<ApprenticeshipStatusSummaryResponse>()
                      {
                           new ApprenticeshipStatusSummaryResponse()
                           {
                                ActiveCount = 1,
                                PausedCount = 1,
                                PendingApprovalCount = 1,
                                LegalEntityIdentifier = _expectedAgreement.LegalEntityCode
                           }
                      }
                  });

            Assert.ThrowsAsync<InvalidRequestException>(() => _handler.Handle(_command));
        }

        [Test]
        public async Task ThenTheAgreementIsCheckedToSeeIfItHasBeenSignedAndHasWithdrawnCommitments()
        {
            _commitmentsV2ApiClient
              .Setup(x => x.GetEmployerAccountSummary(ExpectedAccountId))
              .ReturnsAsync(new GetApprenticeshipStatusSummaryResponse()
              {
                  ApprenticeshipStatusSummaryResponse = new List<ApprenticeshipStatusSummaryResponse>()
                  {
                      new ApprenticeshipStatusSummaryResponse()
                      {
                            WithdrawnCount = 1,
                            LegalEntityIdentifier = _expectedAgreement.LegalEntityCode
                      }
                  }
              });

            Assert.ThrowsAsync<InvalidRequestException>(() => _handler.Handle(_command));
        }
    }
}


text:
package org.apache.ignite.internal.processors.odbc.jdbc;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.binary.BinaryReaderExImpl;
import org.apache.ignite.internal.processors.authentication.AuthorizationContext;
import org.apache.ignite.internal.processors.odbc.ClientListenerConnectionContext;
import org.apache.ignite.internal.processors.odbc.ClientListenerMessageParser;
import org.apache.ignite.internal.processors.odbc.ClientListenerProtocolVersion;
import org.apache.ignite.internal.processors.odbc.ClientListenerRequestHandler;
import org.apache.ignite.internal.util.GridSpinBusyLock;
import org.apache.ignite.internal.util.typedef.F;

/**
 * JDBC Connection Context.
 */
public class JdbcConnectionContext implements ClientListenerConnectionContext {
    /** Version 2.1.0. */
    private static final ClientListenerProtocolVersion VER_2_1_0 = ClientListenerProtocolVersion.create(2, 1, 0);

    /** Version 2.1.5: added "lazy" flag. */
    private static final ClientListenerProtocolVersion VER_2_1_5 = ClientListenerProtocolVersion.create(2, 1, 5);

    /** Version 2.3.1: added "multiple statements query" feature. */
    static final ClientListenerProtocolVersion VER_2_3_0 = ClientListenerProtocolVersion.create(2, 3, 0);

    /** Version 2.4.0: adds default values for columns feature. */
    static final ClientListenerProtocolVersion VER_2_4_0 = ClientListenerProtocolVersion.create(2, 4, 0);

    /** Version 2.5.0. */
    private static final ClientListenerProtocolVersion VER_2_5_0 = ClientListenerProtocolVersion.create(2, 5, 0);

    /** Current version. */
    private static final ClientListenerProtocolVersion CURRENT_VER = VER_2_5_0;

    /** Supported versions. */
    private static final Set<ClientListenerProtocolVersion> SUPPORTED_VERS = new HashSet<>();

    /** Context. */
    private final GridKernalContext ctx;

    /** Shutdown busy lock. */
    private final GridSpinBusyLock busyLock;

    /** Maximum allowed cursors. */
    private final int maxCursors;

    /** Message parser. */
    private JdbcMessageParser parser = null;

    /** Request handler. */
    private JdbcRequestHandler handler = null;

    static {
        SUPPORTED_VERS.add(CURRENT_VER);
        SUPPORTED_VERS.add(VER_2_5_0);
        SUPPORTED_VERS.add(VER_2_4_0);
        SUPPORTED_VERS.add(VER_2_3_0);
        SUPPORTED_VERS.add(VER_2_1_5);
        SUPPORTED_VERS.add(VER_2_1_0);
    }

    /**
     * Constructor.
     * @param ctx Kernal Context.
     * @param busyLock Shutdown busy lock.
     * @param maxCursors Maximum allowed cursors.
     */
    public JdbcConnectionContext(GridKernalContext ctx, GridSpinBusyLock busyLock, int maxCursors) {
        this.ctx = ctx;
        this.busyLock = busyLock;
        this.maxCursors = maxCursors;
    }

    /** {@inheritDoc} */
    @Override public boolean isVersionSupported(ClientListenerProtocolVersion ver) {
        return SUPPORTED_VERS.contains(ver);
    }

    /** {@inheritDoc} */
    @Override public ClientListenerProtocolVersion currentVersion() {
        return CURRENT_VER;
    }

    /** {@inheritDoc} */
    @Override public void initializeFromHandshake(ClientListenerProtocolVersion ver, BinaryReaderExImpl reader)
        throws IgniteCheckedException {
        assert SUPPORTED_VERS.contains(ver): "Unsupported JDBC protocol version.";

        boolean distributedJoins = reader.readBoolean();
        boolean enforceJoinOrder = reader.readBoolean();
        boolean collocated = reader.readBoolean();
        boolean replicatedOnly = reader.readBoolean();
        boolean autoCloseCursors = reader.readBoolean();

        boolean lazyExec = false;

        if (ver.compareTo(VER_2_1_5) >= 0)
            lazyExec = reader.readBoolean();

        boolean skipReducerOnUpdate = false;

        if (ver.compareTo(VER_2_3_0) >= 0)
            skipReducerOnUpdate = reader.readBoolean();

        AuthorizationContext actx = null;

        try {
            if (reader.available() > 0) {
                String user = reader.readString();
                String passwd = reader.readString();

                if (F.isEmpty(user) && ctx.authentication().enabled())
                    throw new IgniteCheckedException("Unauthenticated sessions are prohibited");

                actx = ctx.authentication().authenticate(user, passwd);

                if (actx == null)
                    throw new IgniteCheckedException("Unknown authentication error");
            }
            else {
                if (ctx.authentication().enabled())
                    throw new IgniteCheckedException("Unauthenticated sessions are prohibited");
            }
        }
        catch (Exception e) {
            throw new IgniteCheckedException("Handshake error: " + e.getMessage(), e);
        }

        handler = new JdbcRequestHandler(ctx, busyLock, maxCursors, distributedJoins, enforceJoinOrder,
            collocated, replicatedOnly, autoCloseCursors, lazyExec, skipReducerOnUpdate, actx, ver);

        parser = new JdbcMessageParser(ctx);
    }

    /** {@inheritDoc} */
    @Override public ClientListenerRequestHandler handler() {
        return handler;
    }

    /** {@inheritDoc} */
    @Override public ClientListenerMessageParser parser() {
        return parser;
    }

    /** {@inheritDoc} */
    @Override public void onDisconnected() {
        handler.onDisconnect();
    }
}


text:
<?php
return array(
    'controllers' => array(
        'invokables' => array(
            'SalesObjects\Controller\Hotels' => 'SalesObjects\Controller\HotelsController',
        	'SalesObjects\Controller\Rooms' => 'SalesObjects\Controller\RoomsController',
        	'SalesObjects\Controller\Cruises' => 'SalesObjects\Controller\CruisesController',
        	'SalesObjects\Controller\Cabins' => 'SalesObjects\Controller\CabinsController',
        	'SalesObjects\Controller\Ports' => 'SalesObjects\Controller\PortsController',
        	'SalesObjects\Controller\Iterary' => 'SalesObjects\Controller\IteraryController',
                'SalesObjects\Controller\Events' => 'SalesObjects\Controller\EventsController',
            'SalesObjects\Controller\Ajax' => 'SalesObjects\Controller\AjaxController',
        ),
    ),
    'router' => array(
        'routes' => array(
            'sales-objects' => array(
                'type'    => 'Literal',
                'options' => array(
                    // Change this to something specific to your module
                    'route'    => '/hotels',
                    'defaults' => array(
                        // Change this value to reflect the namespace in which
                        // the controllers for your module are found
                        '__NAMESPACE__' => 'SalesObjects\Controller',
                        'controller'    => 'Hotels',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    // This route is a sane default when developing a module;
                    // as you solidify the routes for your module, however,
                    // you may want to remove it and replace it with more
                    // specific routes.
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),

        		'hotels' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/resorts',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Hotels',
        								'action'        => 'index',
        						),
        				),
        		),

        		'hotels-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/resorts/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Hotels',
        								'action'        => 'add',
        						),
        				),
        		),

        		'hotels-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/resorts/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Hotels',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'hotels-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/resorts/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Hotels',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

        		'rooms' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/rooms',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Rooms',
        								'action'        => 'index',
        						),
        				),
        		),

        		'rooms-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/rooms/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Rooms',
        								'action'        => 'add',
        						),
        				),
        		),

        		'rooms-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/rooms/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Rooms',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'rooms-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/rooms/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Rooms',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

        		'cruises' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruises',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cruises',
        								'action'        => 'index',
        						),
        				),
        		),

        		'cruises-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruises/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cruises',
        								'action'        => 'add',
        						),
        				),
        		),

        		'cruises-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruises/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cruises',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'cruises-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruises/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cruises',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

        		'cabins' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/cabins',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cabins',
        								'action'        => 'index',
        						),
        				),
        		),

        		'cabins-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/cabins/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cabins',
        								'action'        => 'add',
        						),
        				),
        		),

        		'cabins-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/cabins/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cabins',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'cabins-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/cabins/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Cabins',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

        		'ports' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/ports',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ports',
        								'action'        => 'index',
        						),
        				),
        		),

        		'ports-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/ports/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ports',
        								'action'        => 'add',
        						),
        				),
        		),

        		'ports-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/ports/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ports',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'ports-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/ports/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ports',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

				'itineraries' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/itineraries',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Itinerary',
        								'action'        => 'index',
        						),
        				),
        		),

        		'itineraries-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/itineraries/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Itinerary',
        								'action'        => 'add',
        						),
        				),
        		),

        		'itineraries-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/itineraries/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Itinerary',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'itineraries-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruise/itineraries/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Itinerary',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

                        'events' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/events',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Events',
        								'action'        => 'index',
        						),
        				),
        		),

        		'events-add' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/events/add',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Events',
        								'action'        => 'add',
        						),
        				),
        		),

        		'events-edit' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/events/edit/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Events',
        								'action'        => 'edit',
        								'id'			=> 0,
        						),
        				),
        		),

        		'events-delete' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/events/delete/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Events',
        								'action'        => 'delete',
        								'id'			=> 0,
        						),
        				),
        		),

                        'ajax-resorts-item' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/resort/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ajax',
        								'action'        => 'resort',
                                                                        'id'		=> 0,
        						),
        				),
        		),

                        'ajax-cruises-item' => array(
        				'type'    => 'Segment',
        				'options' => array(
        						// Change this to something specific to your module
        						'route'    => '/admin/cruises/item/:id',
        						'defaults' => array(
        								// Change this value to reflect the namespace in which
        								// the controllers for your module are found
        								'__NAMESPACE__' => 'SalesObjects\Controller',
        								'controller'    => 'Ajax',
        								'action'        => 'cruise',
                                                                        'id'		=> 0,
        						),
        				),
        		),

        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'SalesObjects' => __DIR__ . '/../view',
        ),
    ),

		'doctrine' => array(

				// Metadata Mapping driver configuration
				'driver' => array(
						'Avp_Driver' => array(
								'class' => '\Doctrine\ORM\Mapping\Driver\AnnotationDriver',
								'cache' => 'array',
								'paths' => array(__DIR__ . '/../../Base/src/Base/Entity/Avp')
						),
						'orm_avp' => array(
								'class'   => 'Doctrine\ORM\Mapping\Driver\DriverChain',
								'drivers' => array(
										'Base\Entity\Avp' => 'Avp_Driver'
								)
						)
				),

				'configuration' => array(
						// Configuration for service `doctrine.configuration.orm_avp` service
						'orm_avp' => array(
								// metadata cache instance to use. The retrieved service name will
								// be `doctrine.cache.$thisSetting`
								'metadata_cache'    => 'array',

								// DQL queries parsing cache instance to use. The retrieved service
								// name will be `doctrine.cache.$thisSetting`
								'query_cache'       => 'array',

								// ResultSet cache to use.  The retrieved service name will be
								// `doctrine.cache.$thisSetting`
								'result_cache'      => 'array',

								// Mapping driver instance to use. Change this only if you don't want
								// to use the default chained driver. The retrieved service name will
								// be `doctrine.driver.$thisSetting`
								'driver'            => 'orm_avp',

								// Generate proxies automatically (turn off for production)
								'generate_proxies'  => true,

								// directory where proxies will be stored. By default, this is in
								// the `data` directory of your application
								'proxy_dir'         => 'data/DoctrineORMModule/Proxy',

								// namespace for generated proxy classes
								'proxy_namespace'   => 'DoctrineORMModule\Proxy',

								// SQL filters.
								'filters'           => array()
						)
				),

				// Entity Manager instantiation settings
				'entitymanager' => array(
						// configuration for the `doctrine.entitymanager.orm_avp` service
						'orm_avp' => array(
								// connection instance to use. The retrieved service name will
								// be `doctrine.connection.$thisSetting`
								'connection'    => 'orm_avp',

								// configuration instance to use. The retrieved service name will
								// be `doctrine.configuration.$thisSetting`
								'configuration' => 'orm_avp',
						)
				),

				'eventmanager' => array(
						// configuration for the `doctrine.eventmanager.orm_avp` service
						'orm_avp' => array()
				),

				// collector SQL logger, used when ZendDeveloperTools and its toolbar are active
				'sql_logger_collector' => array(
						// configuration for the `doctrine.sql_logger_collector.orm_avp` service
						'orm_avp' => array(),
				),

				// entity resolver configuration, allows mapping associations to interfaces
				'entity_resolver' => array(
						// configuration for the `doctrine.entity_resolver.orm_avp` service
						'orm_avp' => array()
				),

				// authentication service configuration
// 				'authentication' => array(
// 						// configuration for the `doctrine.authentication.orm_avp` authentication service
// 						'orm_avp' => array(
// 								// name of the object manager to use. By default, the EntityManager is used
// 								'objectManager' => 'doctrine.entitymanager.orm_avp'
// 						),
// 				)
		),

		'service_manager' => array(
				'factories' => array(
						//'doctrine.authenticationadapter.orm_avp' => new DoctrineModule\Service\Authentication\AdapterFactory('orm_avp'),
						//'doctrine.authenticationstorage.orm_avp' => new DoctrineModule\Service\Authentication\StorageFactory('orm_avp'),
						//'doctrine.authenticationservice.orm_avp' => new DoctrineModule\Service\Authentication\AuthenticationServiceFactory('orm_avp'),
						'doctrine.connection.orm_avp' => new DoctrineORMModule\Service\DBALConnectionFactory('orm_avp'),
						'doctrine.configuration.orm_avp' => new DoctrineORMModule\Service\ConfigurationFactory('orm_avp'),
						'doctrine.entitymanager.orm_avp' => new DoctrineORMModule\Service\EntityManagerFactory('orm_avp'),
						'doctrine.driver.orm_avp' => new DoctrineModule\Service\DriverFactory('orm_avp'),
						'doctrine.eventmanager.orm_avp' => new DoctrineModule\Service\EventManagerFactory('orm_avp'),
						'doctrine.entity_resolver.orm_avp' => new DoctrineORMModule\Service\EntityResolverFactory('orm_avp'),
						'doctrine.sql_logger_collector.orm_avp' => new DoctrineORMModule\Service\SQLLoggerCollectorFactory('orm_avp'),
						'doctrine.mapping_collector.orm_avp' => function (Zend\ServiceManager\ServiceLocatorInterface $sl) {
							$em = $sl->get('doctrine.entitymanager.orm_avp');

							return new DoctrineORMModule\Collector\MappingCollector($em->getMetadataFactory(), 'orm_avp_mappings');
						},
						'DoctrineORMModule\Form\Annotation\AnnotationBuilder' => function(Zend\ServiceManager\ServiceLocatorInterface $sl) {
							return new DoctrineORMModule\Form\Annotation\AnnotationBuilder($sl->get('doctrine.entitymanager.orm_avp'));
						},
				),
		),
);


text:
import { normalize, virtualFs } from '../virtual-fs';

export interface WorkspaceHost {
  readFile(path: string): Promise<string>;
  writeFile(path: string, data: string): Promise<void>;

  isDirectory(path: string): Promise<boolean>;
  isFile(path: string): Promise<boolean>;

  // Potential future additions
  // readDirectory?(path: string): Promise<string[]>;
}

export function createWorkspaceHost(host: virtualFs.Host): WorkspaceHost {
  const workspaceHost: WorkspaceHost = {
    async readFile(path: string): Promise<string> {
      const data = await host.read(normalize(path)).toPromise();

      return virtualFs.fileBufferToString(data);
    },
    async writeFile(path: string, data: string): Promise<void> {
      return host.write(normalize(path), virtualFs.stringToFileBuffer(data)).toPromise();
    },
    async isDirectory(path: string): Promise<boolean> {
      try {
        return await host.isDirectory(normalize(path)).toPromise();
      } catch {
        // some hosts throw if path does not exist
        return false;
      }
    },
    async isFile(path: string): Promise<boolean> {
      try {
        return await host.isFile(normalize(path)).toPromise();
      } catch {
        // some hosts throw if path does not exist
        return false;
      }
    },
  };

  return workspaceHost;
}


text:
BEGIN_ROOT_NAMESPACE(zuki::storage)

//---------------------------------------------------------------------------
// GptPartitionList Constructor (internal)
//
// Arguments:
//
//	disk		- Parent Disk object (must be GptDisk)

GptPartitionList::GptPartitionList(Disk^ disk) : PartitionList(disk)
{
	if(disk == nullptr) throw gcnew ArgumentNullException("disk");

	// Cast the Disk instance into GptDisk (will throw on invalid conversion)
	m_disk = safe_cast<GptDisk^>(disk);
}

//---------------------------------------------------------------------------
// GptPartitionList::Add
//
// Automatically adds a new partition that consumes the largest available
// chunk of free space on the disk (this is how tools like DISKPART behave)
//
// Arguments:
//
//	type		- Type of GPT partition to be added

GptPartition^ GptPartitionList::Add(GptPartitionType type)
{
	GptPartition^		partition;			// New partition
	__int64				offset;				// New partition offset
	__int64				length;				// New partition length

	// Locate the largest block of available free space on the disk
	offset = FindAlignedLargestFreeSpace(length);
	if(offset < 0) throw gcnew Exception("Insufficient free space exists for the partition");

	// Construct a new GptPartition and add it to the collection
	partition = gcnew GptPartition(type, FindAvailablePartitionNumber(), length, offset, Guid::NewGuid());
	Add(partition);

	return partition;			// Return reference for additional specialization
}

//---------------------------------------------------------------------------
// GptPartitionList::Add
//
// Automatically adds a new partition of the specified length into the first
// available contiguous block of empty disk space that can fit it.  Note that
// the length will be aligned DOWN to the current default alignment
//
// Arguments:
//
//	type			- Type of GPT partition to be added
//	length			- Requested partition length; may be aligned down

GptPartition^ GptPartitionList::Add(GptPartitionType type, __int64 length)
{
	return Add(type, length, Guid::NewGuid());
}

//---------------------------------------------------------------------------
// GptPartitionList::Add
//
// Automatically adds a new partition of the specified length into the first
// available contiguous block of empty disk space that can fit it.  Note that
// the length will be aligned DOWN to the current default alignment
//
// Arguments:
//
//	type			- Type of GPT partition to be added
//	length			- Requested partition length; may be aligned down
//	partitionId		- Partition identifier GUID

GptPartition^ GptPartitionList::Add(GptPartitionType type, __int64 length, Guid partitionId)
{
	GptPartition^		partition;		// New partition
	__int64				offset;			// Calculated offset for the partition

	if(length <= 0) throw gcnew ArgumentOutOfRangeException("length");

	// Align the requested length down to the nearest boundary
	length = DiskUtil::AlignDown(length, m_alignment);

	// Locate an aligned offset that will fit a partition of the requested length
	offset = FindAlignedStartingOffsetForLength(length);
	if(offset < 0) throw gcnew Exception("Insufficient free space exists for the partition");

	// Construct a new GptPartition and add it to the collection
	partition = gcnew GptPartition(type, FindAvailablePartitionNumber(), length, offset, partitionId);
	Add(partition);

	return partition;			// Return reference for additional specialization
}

//---------------------------------------------------------------------------
// GptPartitionList::FindAlignedLargestFreeSpace (private)
//
// Locates the largest available block of free space on the disk and returns
// an aligned offset and length for it
//
// Arguments:
//
//	length			- [OUT] receives the aligned length of the free space

__int64 GptPartitionList::FindAlignedLargestFreeSpace(__int64% length)
{
	List<KeyValuePair<__int64, __int64>>^	freeSpace;		// Free space list
	__int64									offset = -1;	// Offset to return

	// Generate a view of the collection sorted by starting offset
	array<Partition^>^ sorted = this->ToArray();
	Array::Sort(sorted, gcnew Comparison<Partition^>(Partition::CompareByStartingOffset));

	// Construct the collection to hold all the free space
	freeSpace = gcnew List<KeyValuePair<__int64, __int64>>();

	// Start with the extents of the empty disk
	__int64	start = DiskUtil::AlignUp(m_disk->StartingUsableOffset, m_alignment);
	__int64	end = DiskUtil::AlignDown(m_disk->StartingUsableOffset + m_disk->UsableLength, m_alignment);

	// Iterate over each partition to find the free space
	for(int index = 0; index < sorted->Length; index++) {

		// Free space detected -- add it to the collection
		if(sorted[index]->StartingOffset > start)
			freeSpace->Add(KeyValuePair<__int64, __int64>(start, sorted[index]->StartingOffset - start));

		// Move start to the end of this partition
		start = DiskUtil::AlignUp(sorted[index]->StartingOffset + sorted[index]->PartitionLength, m_alignment);
	}

	// If we didn't reach the end of the disk during enumeration, there is free space left
	if(start < end) freeSpace->Add(KeyValuePair<__int64, __int64>(start, end - start));

	// Iterate over the collection to find the largest space
	for each(KeyValuePair<__int64, __int64> pair in freeSpace)
		if(pair.Value > length) { offset = pair.Key; length = pair.Value; }

	// Align the largest length down and if it's still usable
	length = DiskUtil::AlignDown(length, m_alignment);
	return (length > 0) ? offset : -1;
}

//---------------------------------------------------------------------------
// GptPartitionList::FindAlignedStartingOffsetForLength (private)
//
// Scans the current partition table and locates a valid starting offset
// with which to place a partition of the specified length
//
// Arguments:
//
//	length			- Requested partition length

__int64 GptPartitionList::FindAlignedStartingOffsetForLength(__int64 length)
{
	// Generate a view of the collection sorted by starting offset
	array<Partition^>^ sorted = this->ToArray();
	Array::Sort(sorted, gcnew Comparison<Partition^>(Partition::CompareByStartingOffset));

	// Start with the extents of the empty disk
	__int64	start = DiskUtil::AlignUp(m_disk->StartingUsableOffset, m_alignment);
	__int64	end = DiskUtil::AlignDown(start + m_disk->UsableLength, m_alignment);

	// Iterate over all of the current partitions on the disk
	for(int index = 0; index < sorted->Length; index++) {

		// If there is free space that will fit the requested length, we're done
		if((sorted[index]->StartingOffset > start) && ((sorted[index]->StartingOffset - start) > length)) return start;

		// Not free space or length won't fit; move start to the end of this partition
		start = DiskUtil::AlignUp(sorted[index]->StartingOffset + sorted[index]->PartitionLength, m_alignment);
	}

	// Reached the end of current partitioned data without finding a free block,
	// check to see if there is room after the partitioned data for the length
	return ((end - start) >= length) ? start : -1;
}

//---------------------------------------------------------------------------
// GptPartitionList::FindAvailablePartitionNumber (private)
//
// Locates an available partition number
//
// Arguments:
//
//	NONE

int GptPartitionList::FindAvailablePartitionNumber(void)
{
	int					number = 0;					// Start at zero

	// Generate a view of the collection sorted by partition number
	array<Partition^>^ sorted = this->ToArray();
	Array::Sort(sorted, gcnew Comparison<Partition^>(Partition::CompareByPartitionNumber));

	// Iterate over all the existing partitions until a free number is located
	for(int index = 0; index < sorted->Length; index++) {

		if(sorted[index]->PartitionNumber <= number) number++;
		else break;
	}

	return number;
}

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

END_ROOT_NAMESPACE(zuki::storage)

#pragma warning(pop)


text:
namespace Parser.Common.Interceptors.Contracts
{
    public interface IHttpContextCacheReturnValues
    {
    }
}


text:
import optproblems.cec2005
import numpy as np
import time
from ICA import *
import os

if __name__ == "__main__":
    dim = 30
    repeats = 10
    evaluations = 10000*dim
    countries = 30
    imperialists = 6

    if not os.path.exists('results'):
        os.makedirs('results')

    if not os.path.exists('convergence'):
        os.makedirs('convergence')

    np.random.seed(10)

    f1 = optproblems.cec2005.F1(dim)

    time1 = time.time()
    results = np.array([ICA(f1, dim=dim, evaluation_criteria=True,
        max_eval=evaluations, ncountries=countries, nimperialists=imperialists,
        lower_bound=-100, upper_bound=100) for _ in range(repeats)])
    total_time = time.time() - time1

    means = results.mean(axis=0)
    solutions = results[:,-1]
    mean_best = means[-1]
    min_sol = np.min(solutions)
    max_sol = np.max(solutions)
    marks = means[0:-1]

    with open("results/ICA-results-30-1.txt", "w") as file:
        print("F1: Shifted Sphere Function", file=file)
        print("Min\t Max\t Mean\t Mean time", file=file)
        print("_______________________________________________", file=file)
        print("{} {} {} {}".format(min_sol, max_sol, mean_best, total_time / repeats), file=file)

    with open("convergence/ICA-convergence-30-1.csv", "w") as file:
        for i in range(len(marks)):
            print("{},{}".format(10000*i, marks[i]), file=file)

    np.random.seed(10)

    f6 = optproblems.cec2005.F6(dim)

    time1 = time.time()
    results = np.array([ICA(f6, dim=dim, evaluation_criteria=True,
        max_eval=evaluations, ncountries=countries, nimperialists=imperialists,
        lower_bound=-100, upper_bound=100) for _ in range(repeats)])
    total_time = time.time() - time1

    means = results.mean(axis=0)
    solutions = results[:,-1]
    mean_best = means[-1]
    min_sol = np.min(solutions)
    max_sol = np.max(solutions)
    marks = means[0:-1]

    with open("results/ICA-results-30-6.txt", "w") as file:
        print("F6: Shifted Rosenbrock's Function", file=file)
        print("Min\t Max\t Mean\t Mean time", file=file)
        print("_______________________________________________", file=file)
        print("{} {} {} {}".format(min_sol, max_sol, mean_best, total_time / repeats), file=file)

    with open("convergence/ICA-convergence-30-6.csv", "w") as file:
        for i in range(len(marks)):
            print("{},{}".format(10000*i, marks[i]), file=file)

    np.random.seed(10)

    f14 = optproblems.cec2005.F14(dim)

    time1 = time.time()
    results = np.array([ICA(f14, dim=dim, evaluation_criteria=True,
        max_eval=evaluations, ncountries=countries, nimperialists=imperialists,
        lower_bound=-100, upper_bound=100) for _ in range(repeats)])
    total_time = time.time() - time1

    means = results.mean(axis=0)
    solutions = results[:,-1]
    mean_best = means[-1]
    min_sol = np.min(solutions)
    max_sol = np.max(solutions)
    marks = means[0:-1]

    with open("results/ICA-results-30-14.txt", "w") as file:
        print("F14: Shifted Rotated Expanded Scaffer's F6", file=file)
        print("Min\t Max\t Mean\t Mean time", file=file)
        print("_______________________________________________", file=file)
        print("{} {} {} {}".format(min_sol, max_sol, mean_best, total_time / repeats), file=file)

    with open("convergence/ICA-convergence-30-14.csv", "w") as file:
        for i in range(len(marks)):
            print("{},{}".format(10000*i, marks[i]), file=file)

    np.random.seed(10)

    f15 = optproblems.cec2005.F15(dim)

    time1 = time.time()
    results = np.array([ICA(f15, dim=dim, evaluation_criteria=True,
        max_eval=evaluations, ncountries=countries, nimperialists=imperialists,
        lower_bound=-5, upper_bound=5) for _ in range(repeats)])
    total_time = time.time() - time1

    means = results.mean(axis=0)
    solutions = results[:,-1]
    mean_best = means[-1]
    min_sol = np.min(solutions)
    max_sol = np.max(solutions)
    marks = means[0:-1]

    with open("results/ICA-results-30-15.txt", "w") as file:
        print("F15: Hybrid Composition Function", file=file)
        print("Min\t Max\t Mean\t Mean time", file=file)
        print("_______________________________________________", file=file)
        print("{} {} {} {}".format(min_sol, max_sol, mean_best, total_time / repeats), file=file)

    with open("convergence/ICA-convergence-30-15.csv", "w") as file:
        for i in range(len(marks)):
            print("{},{}".format(10000*i, marks[i]), file=file)

    np.random.seed(10)

    f16 = optproblems.cec2005.F16(dim)

    time1 = time.time()
    results = np.array([ICA(f16, dim=dim, evaluation_criteria=True,
        max_eval=evaluations, ncountries=countries, nimperialists=imperialists,
        lower_bound=-5, upper_bound=5) for _ in range(repeats)])
    total_time = time.time() - time1

    means = results.mean(axis=0)
    solutions = results[:,-1]
    mean_best = means[-1]
    min_sol = np.min(solutions)
    max_sol = np.max(solutions)
    marks = means[0:-1]

    with open("results/ICA-results-30-16.txt", "w") as file:
        print("F16: Rotated Hybrid Composition Function", file=file)
        print("Min\t Max\t Mean\t Mean time", file=file)
        print("_______________________________________________", file=file)
        print("{} {} {} {}".format(min_sol, max_sol, mean_best, total_time / repeats), file=file)

    with open("convergence/ICA-convergence-30-16.csv", "w") as file:
        for i in range(len(marks)):
            print("{},{}".format(10000*i, marks[i]), file=file)