text:
"""Script to extract the fst between two populations.

Usage: python3 fst_to_genomic_score.py 1 2 < popoolation2.fst > pop1_2.fst
Output is chr, pos, fst
"""

import sys
from numpy import sqrt

def triangular_number(number):
    '''Finds if a number is triangular, and if so, computer the base of that
    triangle. It is necessary to know the number of populations involved in the
    analysis of the Fst.

    >>> triangular_number(1)
    1
    >>> triangular_number(3)
    3
    >>> triangular_number(2)
    -1
    '''
    base = (1 + sqrt(1 + 8 * number))/2
    if base.is_integer():
        return int(base)
    return -1

def populations_to_index(pop1, pop2, npop):
    """Get the index of the column of a pair of populations in the fst file from
    popoolation2.

    Columns in the fst file are
    chromosome, center of the window, number of snps, covered fraction,
    coverage, fst 1:2, fst 1:3, ..., fst 1:n, fst 2:3, ..., fst 2:n, ...,
    fst  n-1:n

    Got from here: https://stackoverflow.com/a/27088560/4730336

    >>> populations_to_index(1, 2, 2)
    1
    >>> populations_to_index(1, 2, 22)
    1
    >>> populations_to_index(2, 3, 22)
    22
    >>> populations_to_index(21, 22, 22)
    231
    """
    pop1 = pop1 - 1
    pop2 = pop2 - 1
    big_triangle = int(npop * (npop - 1) / 2)
    small_triangle = int((npop - pop1) * (npop - pop1 - 1) / 2)
    k = big_triangle - small_triangle + pop2 - pop1
    return k

if __name__ == '__main__':

    POPULATION_1 = int(sys.argv[1])
    POPULATION_2 = int(sys.argv[2])

    if POPULATION_1 == POPULATION_2:
        raise SystemExit("Populations must be different")

    # Swap
    if POPULATION_1 >= POPULATION_2:
        POPULATION_1, POPULATION_2 = POPULATION_2, POPULATION_1

    NPOP = None

    for line in sys.stdin:
        line = line.strip().split("\t")
        n_analysis = len(line) - 5
        if not NPOP:
            NPOP = int(triangular_number(n_analysis))
        chromosome, position, _, _, _, *analysis = line
        if POPULATION_2 >= NPOP + 1:
            raise SystemExit("Error with analysis to be extracted, exitting")
        # index = pop1 + pop2 - 1
        index = populations_to_index(POPULATION_1, POPULATION_2, NPOP) - 1
        #sys.stderr.write(f"{index}")

        fst = analysis[index]
        fst = fst.split("=")[1]
        sys.stdout.write(f"{chromosome}\t{position}\t{fst}\n")


text:
import { Injectable } from '@angular/core';

import { LineNumberingMode } from 'app/site/motions/motions.constants';

/**
 * Shape of line number objects
 */
interface LineNumberObject {
    lineNumber: number;
    marginBottom?: number;
}

/**
 * Converts HTML strings to pdfmake compatible document definition.
 *
 * TODO: Bring back upstream to pdfmake, so other projects may benefit from this converter and
 *       to exclude complex code from OpenSlides.
 *       Everything OpenSlides specific, such as line numbering and change recommendations,
 *       should be excluded from this and handled elsewhere.
 *
 * @example
 * ```
 * const dd = htmlToPdfService.convertHtml('<h3>Hello World!</h3>');
 * ```
 */
@Injectable({
    providedIn: 'root'
})
export class HtmlToPdfService {
    /**
     * holds the desired line number mode
     */
    private lineNumberingMode: LineNumberingMode;

    /**
     * Normal line height for paragraphs
     */
    private LINE_HEIGHT = 1.25;

    /**
     * space between paragraphs
     */
    private P_MARGIN_BOTTOM = 4.0;

    /**
     * Space above H
     */
    private H_MARGIN_TOP = 10.0;

    /**
     * Conversion of HTML tags into pdfmake directives
     */
    private elementStyles = {
        // should be the same for most HTML code
        b: ['font-weight:bold'],
        strong: ['font-weight:bold'],
        u: ['text-decoration:underline'],
        em: ['font-style:italic'],
        i: ['font-style:italic'],
        h1: ['font-size:14', 'font-weight:bold'],
        h2: ['font-size:12', 'font-weight:bold'],
        h3: ['font-size:10', 'font-weight:bold'],
        h4: ['font-size:10', 'font-style:italic'],
        h5: ['font-size:10'],
        h6: ['font-size:10'],
        a: ['color:blue', 'text-decoration:underline'],
        strike: ['text-decoration:line-through'],
        // Pretty specific stuff that might be excluded for other projects than OpenSlides
        del: ['color:red', 'text-decoration:line-through'],
        ins: ['color:green', 'text-decoration:underline']
    };

    /**
     * Treatment of required CSS-Classes
     * Checking CSS is not possible
     */
    private classStyles = {
        delete: ['color:red', 'text-decoration:line-through'],
        insert: ['color:green', 'text-decoration:underline'],
        paragraphcontext: ['color:grey']
    };

    /**
     * Constructor
     */
    public constructor() {}

    /**
     * Determine the ideal top margin for a given node
     *
     * @param nodeName the node to parse
     * @returns the margin tip as number
     */
    private getMarginTop(nodeName: string): number {
        switch (nodeName) {
            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6': {
                return this.H_MARGIN_TOP;
            }
            default: {
                return 0;
            }
        }
    }

    /**
     * Determine the ideal margin for a given node
     *
     * @param nodeName the node to parse
     * @returns the margin bottom as number
     */
    private getMarginBottom(nodeName: string): number {
        switch (nodeName) {
            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6': {
                return this.P_MARGIN_BOTTOM;
            }
            case 'li': {
                return this.P_MARGIN_BOTTOM;
            }
            default: {
                return this.P_MARGIN_BOTTOM;
            }
        }
    }

    /**
     * Function to convert plain html text without linenumbering.
     *
     * @param text The html text that should be converted to PDF.
     *
     * @returns {object} The converted html as DocDef.
     */
    public addPlainText(text: string): object {
        return {
            columns: [{ stack: this.convertHtml(text, LineNumberingMode.None) }]
        };
    }

    /**
     * Takes an HTML string, converts to HTML using a DOM parser and recursivly parses
     * the content into pdfmake compatible doc definition
     *
     * @param htmlText the html text to translate as string
     * @param lnMode determines the line numbering
     * @returns pdfmake doc definition as object
     */
    public convertHtml(htmlText: string, lnMode?: LineNumberingMode): object {
        const docDef = [];
        this.lineNumberingMode = lnMode || LineNumberingMode.None;

        // Cleanup of dirty html would happen here

        // Create a HTML DOM tree out of html string
        const parser = new DOMParser();
        const parsedHtml = parser.parseFromString(htmlText, 'text/html');
        // Since the spread operator did not work for HTMLCollection, use Array.from
        const htmlArray = Array.from(parsedHtml.body.childNodes) as Element[];

        // Parse the children of the current HTML element
        for (const child of htmlArray) {
            const parsedElement = this.parseElement(child);
            docDef.push(parsedElement);
        }

        // DEBUG: printing the following. Do not remove, just comment out
        // console.log('MakePDF doc :\n---\n', JSON.stringify(docDef), '\n---\n');

        return docDef;
    }

    /**
     * Converts a single HTML element to pdfmake, calls itself recursively for child html elements
     *
     * @param element can be an HTML element (<p>) or plain text ("Hello World")
     * @param currentParagraph usually holds the parent element, to allow nested structures
     * @param styles holds the style attributes of HTML elements (`<div style="color: green">...`)
     * @returns the doc def to the given element in consideration to the given paragraph and styles
     */
    public parseElement(element: Element, styles?: string[]): any {
        const nodeName = element.nodeName.toLowerCase();
        const childNodes = Array.from(element.childNodes) as Element[];
        const directChildIsCrNode = childNodes.some(child => this.isCrElement(child));
        let classes = [];
        let newParagraph: any;

        // extract explicit style information
        styles = styles || [];

        // to leave out plain text elements
        if (element.getAttribute) {
            const nodeStyle = element.getAttribute('style');
            const nodeClass = element.getAttribute('class');

            // add styles like `color:#ff00ff` content into styles array
            if (nodeStyle) {
                styles = nodeStyle
                    .split(';')
                    .map(style => style.replace(/\s/g, ''))
                    .concat(styles);
            }

            // Handle CSS classes
            if (nodeClass) {
                classes = nodeClass.toLowerCase().split(' ');

                for (const cssClass of classes) {
                    if (this.classStyles[cssClass]) {
                        this.classStyles[cssClass].forEach(style => {
                            styles.push(style);
                        });
                    }
                }
            }
        }

        switch (nodeName) {
            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6':
            case 'li':
            case 'p':
            case 'div': {
                const children = this.parseChildren(element, styles);

                if (
                    this.lineNumberingMode === LineNumberingMode.Outside &&
                    !classes.includes('insert') &&
                    !(nodeName === 'li' && directChildIsCrNode)
                ) {
                    //
                    newParagraph = this.create('stack');
                    newParagraph.stack = children;
                } else {
                    newParagraph = this.create('text');
                    newParagraph.text = children;
                }

                newParagraph.margin = [0, 0, 0, 0];

                // determine the "normal" top and button margins
                newParagraph.margin[1] = this.getMarginTop(nodeName);
                newParagraph.margin[3] = this.getMarginBottom(nodeName);

                if (this.lineNumberingMode === LineNumberingMode.Outside) {
                    // that is usually the case for inserted change which should appear
                    // under a set of line numbers with correct alignment
                    if (classes.includes('insert')) {
                        newParagraph.margin[0] = 20;
                        newParagraph.margin[3] = this.P_MARGIN_BOTTOM;
                    }
                }

                // stop enumeration if the list was inserted
                if (classes.includes('os-split-before')) {
                    newParagraph.listType = 'none';
                }

                // if the list ends (usually due to a new insert cr) prevent margins
                if (classes.includes('os-split-after') || this.withSublist(element)) {
                    newParagraph.margin[3] = 0;
                }

                newParagraph.lineHeight = this.LINE_HEIGHT;
                newParagraph = {
                    ...newParagraph,
                    ...this.computeStyle(styles),
                    ...this.computeStyle(this.elementStyles[nodeName])
                };
                // if the ol list has specific list type
                if (nodeName === 'li' && element.parentNode.nodeName === 'OL') {
                    const type = element.parentElement.getAttribute('type');
                    switch (type) {
                        case 'a':
                            newParagraph.listType = 'lower-alpha';
                            break;
                        case 'A':
                            newParagraph.listType = 'upper-alpha';
                            break;
                        case 'i':
                            newParagraph.listType = 'lower-roman';
                            break;
                        case 'I':
                            newParagraph.listType = 'upper-roman';
                            break;
                        default:
                            break;
                    }
                }
                break;
            }
            case 'a':
            case 'b':
            case 'strong':
            case 'u':
            case 'em':
            case 'i':
            case 'ins':
            case 'del':
            case 'strike': {
                const children = this.parseChildren(element, styles.concat(this.elementStyles[nodeName]));
                newParagraph = this.create('text');
                newParagraph.text = children;
                break;
            }
            case 'span': {
                // Line numbering feature, will prevent compatibility to most other projects
                if (element.getAttribute('data-line-number') && !this.isInsideAList(element)) {
                    if (this.lineNumberingMode === LineNumberingMode.Inside) {
                        // TODO: algorithm for "inline" line numbers is not yet implemented
                    } else if (this.lineNumberingMode === LineNumberingMode.Outside) {
                        const currentLineNumber = element.getAttribute('data-line-number');
                        newParagraph = {
                            columns: [
                                // the line number column
                                this.getLineNumberObject({ lineNumber: +currentLineNumber }),
                                {
                                    text: []
                                }
                            ]
                        };
                    }
                } else {
                    const children = this.parseChildren(element, styles);

                    newParagraph = {
                        ...this.create('text'),
                        ...this.computeStyle(styles)
                    };

                    newParagraph.text = children;
                }
                break;
            }
            case 'br': {
                if (
                    (this.lineNumberingMode === LineNumberingMode.None && classes.includes('os-line-break')) ||
                    (this.lineNumberingMode === LineNumberingMode.Outside && this.isInsideAList(element))
                ) {
                    break;
                } else {
                    newParagraph = this.create('text');
                    // yep thats all
                    newParagraph.text = '\n';
                    newParagraph.lineHeight = this.LINE_HEIGHT;
                }
                break;
            }
            case 'ul':
            case 'ol': {
                const list = this.create(nodeName);

                // keep the numbers of the ol list
                if (nodeName === 'ol') {
                    const start = element.getAttribute('start');
                    if (start) {
                        list.start = parseInt(start, 10);
                    }
                }

                // in case of line numbers and only of the list is not nested in another list.
                if (this.lineNumberingMode === LineNumberingMode.Outside) {
                    const lines = this.extractLineNumbers(element);

                    const cleanedChildDom = this.cleanLineNumbers(element);
                    const cleanedChildren = this.parseChildren(cleanedChildDom, styles);

                    if (lines.length > 0) {
                        const listCol = {
                            columns: [
                                {
                                    width: 20,
                                    stack: []
                                }
                            ],
                            margin: [0, 0, 0, 0]
                        };

                        // if this is a "fake list" lower put it close to the element above
                        if (this.isFakeList(element)) {
                            listCol.margin[3] = -this.P_MARGIN_BOTTOM;
                        }

                        for (const line of lines) {
                            listCol.columns[0].stack.push(this.getLineNumberObject(line));
                        }

                        list[nodeName] = cleanedChildren;
                        listCol.columns.push(list);
                        newParagraph = listCol;
                    } else {
                        // that is usually the case for "inserted" lists during change recomendations
                        list.margin = [20, 0, 0, 0];
                        newParagraph = list;
                        newParagraph[nodeName] = cleanedChildren;
                    }
                } else {
                    const children = this.parseChildren(element, styles);
                    newParagraph = list;
                    newParagraph[nodeName] = children;
                }
                break;
            }
            default: {
                newParagraph = {
                    ...this.create('text', element.textContent.replace(/\n/g, '')),
                    ...this.computeStyle(styles)
                };
                break;
            }
        }
        return newParagraph;
    }

    /**
     * Helper routine to parse an elements children and return the children as parsed pdfmake doc string
     *
     * @param element the parent element to parse
     * @param currentParagraph the context of the element
     * @param styles the styles array, usually just to parse back into the `parseElement` function
     * @returns an array of parsed children
     */
    private parseChildren(element: Element, styles?: string[]): Element[] {
        const childNodes = Array.from(element.childNodes) as Element[];
        const paragraph = [];
        if (childNodes.length > 0) {
            for (const child of childNodes) {
                // skip empty child nodes
                if (!(child.nodeName === '#text' && child.textContent.trim() === '')) {
                    const parsedElement = this.parseElement(child, styles);
                    const firstChild = element.firstChild as Element;

                    if (
                        // add the line number column
                        this.lineNumberingMode === LineNumberingMode.Outside &&
                        child &&
                        child.classList &&
                        child.classList.contains('os-line-number')
                    ) {
                        paragraph.push(parsedElement);
                    } else if (
                        // if the first child of the parsed element is line number
                        this.lineNumberingMode === LineNumberingMode.Outside &&
                        firstChild &&
                        firstChild.classList &&
                        firstChild.classList.contains('os-line-number')
                    ) {
                        const currentLine = paragraph.pop();
                        // push the parsed element into the "text" array
                        currentLine.columns[1].text.push(parsedElement);
                        paragraph.push(currentLine);
                    } else {
                        paragraph.push(parsedElement);
                    }
                }
            }
        }
        return paragraph;
    }

    /**
     * Helper function to make a line-number object
     *
     * @param line and object in the shape: { lineNumber: X }
     * @returns line number as pdfmake-object
     */
    private getLineNumberObject(line: LineNumberObject): object {
        return {
            width: 20,
            text: [
                {
                    // Add a blank with the normal font size here, so in rare cases the text
                    // is rendered on the next page and the line number on the previous page.
                    text: ' ',
                    decoration: ''
                },
                {
                    text: line.lineNumber,
                    color: 'gray',
                    fontSize: 8
                }
            ],
            marginBottom: line.marginBottom,
            lineHeight: this.LINE_HEIGHT
        };
    }

    /**
     * Checks if a given LI has a sublist
     */
    private withSublist(element: Element): boolean {
        if (element.nodeName.toLowerCase() === 'li') {
            const hasUl = Array.from(element.children).some(child => child.nodeName.toLowerCase() === 'ul');
            return hasUl;
        }
        return false;
    }

    /**
     * Cleans the elements children from line-number spans
     *
     * @param element a html dom tree
     * @returns a DOM element without line number spans
     */
    private cleanLineNumbers(element: Element): Element {
        const elementCopy = element.cloneNode(true) as Element;
        const children = elementCopy.childNodes;

        // using for-of did not work as expected
        for (let i = 0; i < children.length; i++) {
            if (this.getLineNumber(children[i] as Element)) {
                children[i].remove();
            }

            if (children[i]?.childNodes.length > 0) {
                const cleanChildren = this.cleanLineNumbers(children[i] as Element);
                elementCopy.replaceChild(cleanChildren, children[i]);
            }
        }

        return elementCopy;
    }

    /**
     * Helper function to extract line numbers from child elements
     *
     * TODO: Cleanup
     *
     * @param element element to check for containing line numbers (usually a list)
     * @returns a list with the line numbers
     */
    private extractLineNumbers(element: Element): LineNumberObject[] {
        let foundLineNumbers = [];
        const lineNumber = this.getLineNumber(element);
        if (lineNumber) {
            foundLineNumbers.push({ lineNumber: lineNumber });
        } else if (element.nodeName === 'BR') {
            // Check if there is a new line, but it does not get a line number.
            // If so, insert a dummy line, so the line numbers stays aligned with
            // the text.
            if (!this.getLineNumber(element.nextSibling as Element)) {
                foundLineNumbers.push({ lineNumber: '' });
            }
        } else {
            const children = Array.from(element.childNodes) as Element[];
            let childrenLength = children.length;
            let childrenLineNumbers = [];
            for (let i = 0; i < children.length; i++) {
                childrenLineNumbers = childrenLineNumbers.concat(this.extractLineNumbers(children[i]));
                if (children.length < childrenLength) {
                    i -= childrenLength - children.length;
                    childrenLength = children.length;
                }
            }

            // if the found element is a list item, add some spacing
            if (childrenLineNumbers.length && (element.nodeName === 'LI' || element.parentNode.nodeName === 'LI')) {
                childrenLineNumbers[childrenLineNumbers.length - 1].marginBottom = this.P_MARGIN_BOTTOM;
            }

            foundLineNumbers = foundLineNumbers.concat(childrenLineNumbers);
        }
        return foundLineNumbers;
    }

    /**
     * Recursive helper function to determine if the element is inside a list
     *
     * @param element the current html node
     * @returns wether the element is inside a list or not
     */
    private isInsideAList(element: Element): boolean {
        let parent = element.parentNode;
        while (parent !== null) {
            if (parent.nodeName === 'UL' || parent.nodeName === 'OL') {
                return true;
            }
            parent = parent.parentNode;
        }
        return false;
    }

    /**
     * Checks if a given UL or LI list (as element) is a "fake list"
     * Fake lists in fact lists by should appear like the parent list
     * would seamlessly continue.
     * This usually happens when a user makes change recommendations in
     * lists
     *
     * @param element the list to check, can be UL or LI
     * returns wether the list is fake or not
     */
    private isFakeList(element: Element): boolean {
        if (element.firstElementChild && element.classList.contains('os-split-after')) {
            // either first child has split-before or last child has split-after
            const firstChild = element.firstElementChild;
            const lastChild = element.childNodes[element.childNodes.length - 1] as Element;
            const splitBefore = firstChild.nodeName === 'LI' && firstChild.classList.contains('os-split-before');
            const splitAfter = lastChild.nodeName === 'LI' && lastChild.classList.contains('os-split-after');
            return splitBefore || splitAfter;
        }
        return false;
    }

    /**
     * Helper function to safer extract a line number from an element
     *
     * @param element
     * @returns the line number of the element
     */
    private getLineNumber(element: Element): number {
        if (
            element &&
            element.nodeName === 'SPAN' &&
            element.getAttribute('class') &&
            element.getAttribute('class').indexOf('os-line-number') > -1
        ) {
            return parseInt(element.getAttribute('data-line-number'), 10);
        }
    }

    /**
     * Extracts the style information from the given array
     *
     * @param styles an array of inline css styles (i.e. `style="margin: 10px"`)
     * @returns an object with style pdfmake compatible style information
     */
    private computeStyle(styles: string[]): any {
        const styleObject: any = {};
        if (styles && styles.length > 0) {
            for (const style of styles) {
                const styleDefinition = style.trim().toLowerCase().split(':');
                const key = styleDefinition[0];
                const value = styleDefinition[1];

                if (styleDefinition.length === 2) {
                    switch (key) {
                        case 'padding-left': {
                            styleObject.margin = [parseInt(value, 10), 0, 0, 0];
                            break;
                        }
                        case 'font-size': {
                            styleObject.fontSize = parseInt(value, 10);
                            break;
                        }
                        case 'text-align': {
                            switch (value) {
                                case 'right':
                                case 'center':
                                case 'justify': {
                                    styleObject.alignment = value;
                                    break;
                                }
                            }
                            break;
                        }
                        case 'font-weight': {
                            switch (value) {
                                case 'bold': {
                                    styleObject.bold = true;
                                    break;
                                }
                            }
                            break;
                        }
                        case 'text-decoration': {
                            switch (value) {
                                case 'underline': {
                                    styleObject.decoration = 'underline';
                                    break;
                                }
                                case 'line-through': {
                                    styleObject.decoration = 'lineThrough';
                                    break;
                                }
                            }
                            break;
                        }
                        case 'font-style': {
                            switch (value) {
                                case 'italic': {
                                    styleObject.italics = true;
                                    break;
                                }
                            }
                            break;
                        }
                        case 'color': {
                            styleObject.color = this.parseColor(value);
                            break;
                        }
                        case 'background-color': {
                            styleObject.background = this.parseColor(value);
                            break;
                        }
                    }
                }
            }
        }
        return styleObject;
    }

    /**
     * Detect if the given element is a cr exclusive node
     * @param child
     */
    private isCrElement(element: Element): boolean {
        const nodeName = element.nodeName.toLowerCase();
        const crNodeNames = ['ins', 'del'];
        return crNodeNames.includes(nodeName);
    }

    /**
     * Returns the color in a hex format (e.g. #12ff00).
     * Also tries to convert RGB colors into hex values
     *
     * @param color color as string representation
     * @returns color as hex values for pdfmake
     */
    private parseColor(color: string): string {
        const haxRegex = new RegExp('^#([0-9a-f]{3}|[0-9a-f]{6})$');

        // e.g. `#fff` or `#ff0048`
        const rgbRegex = new RegExp('^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$');

        // e.g. rgb(0,255,34) or rgb(22, 0, 0)
        const nameRegex = new RegExp('^[a-z]+$');

        if (haxRegex.test(color)) {
            return color;
        } else if (rgbRegex.test(color)) {
            const decimalColors = rgbRegex.exec(color).slice(1);
            for (let i = 0; i < 3; i++) {
                let decimalValue = parseInt(decimalColors[i], 10);
                if (decimalValue > 255) {
                    decimalValue = 255;
                }
                let hexString = '0' + decimalValue.toString(16);
                hexString = hexString.slice(-2);
                decimalColors[i] = hexString;
            }
            return '#' + decimalColors.join('');
        } else if (nameRegex.test(color)) {
            return color;
        } else {
            console.error('Could not parse color "' + color + '"');
            return color;
        }
    }

    /**
     * Helper function to create valid doc definitions container elements for pdfmake
     *
     * @param name should be a pdfMake container element, like 'text' or 'stack'
     * @param content
     */
    private create(name: string, content?: any): any {
        const container = {};
        const docDef = content ? content : [];
        container[name] = docDef;
        return container;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Contributing to Kafka Streams Complex Event Processing
=======================================================

# Found a bug ?

If you found a bug in the source code you can help us by submitting an issue or even a Pull Request to our GitHub Repository.

# Got a new idea ?

Any new feature propositions are always appreciated. Ideas are what keep this project working. The first step is to open an issue and describe your proposal so that it can be discussed. If you changes are small you can directly proposed a Pull Request that will be reviewed before being merged.

# Coding Guidelines

 * Any code changes must include some unit tests that cover the new functionality or the bugfix.
 * Frequently rebase your works to ease the Pull Request merging.

# Commit Message Guidelines

Each commit message consists of a header, a body and a footer. The header has a special format that includes a type, a scope and a subject:

```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```

## Type

Must be one of the following:

* **build**: Changes that affect the build system or external dependencies
* **ci**: Changes to our CI configuration files and scripts
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **test**: Adding missing tests or correcting existing tests

## Scope

Must be one of the following:

* **core** : A code change that affect the server module
* **streams** : A code change that affect the streams module
* **ci** : A change to the continuous build or continuous integration
* **github-pages** : Changes to the documentation
* **checkstyle** : Changes to the checkstyle
* **examples** : Changes to the examples
* **readme** : Changes to README.md
* **changelogs** : Changes to CHANGELOG.md
* **contributing** : Changes to CONTRIBUTING.md

## Subject
The subject contains a succinct description of the change:

* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize the first letter
* no dot (.) at the end

## Body
Just as in the subject, use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior.

## Footer

Should contain the reference to the GitHub issue that this commits **Resolves**.


text:
<?php

namespace OpenOrchestra\ApiBundle\Transformer;

use OpenOrchestra\Backoffice\Security\ContributionActionInterface;
use OpenOrchestra\BaseApi\Facade\FacadeInterface;
use OpenOrchestra\BaseApi\Transformer\AbstractSecurityCheckerAwareTransformer;
use OpenOrchestra\ModelInterface\Model\NodeInterface;

/**
 * Class NodeTreeLeafTransformer
 */
class NodeTreeLeafTransformer extends AbstractSecurityCheckerAwareTransformer
{
    /**
     * @param array $node
     * @param array $params
     *
     * @return FacadeInterface
     */
    public function transform($node, array $params = array())
    {
        $facade = $this->newFacade();

        $facade->nodeId = $node['nodeId'];
        $facade->name = $node['name'];
        $facade->language = $node['language'];
        $facade->version = $node['version'];
        $facade->siteId = $node['siteId'];
        $facade->order = $node['order'];
        $facade->status = $this->getContext()->transform('status_node_tree', $node['status']);
        $facade->nodeType = $node['nodeType'];

        $facade->addRight('can_create', (
            $this->authorizationChecker->isGranted(ContributionActionInterface::CREATE, $node) &&
            NodeInterface::TYPE_DEFAULT === $node['nodeType']
        ));
        $facade->addRight('can_read', $this->authorizationChecker->isGranted(ContributionActionInterface::READ, $node));
        $facade->addRight('can_edit', $this->authorizationChecker->isGranted(ContributionActionInterface::EDIT, $node));

        return $facade;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'node_tree_leaf';
    }
}


text:
<!DOCTYPE html>

    <title>ST.event.Player | Sencha Test 1.0.3 </title>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta property="og:image" content="home-images/sencha-200.png" />
    <meta property="og:title" content="ST.event.Player | Sencha Test 1.0.3 " />
    <meta property="og:description" content="This class is rarely used directly, but is the underlying mechanism used the injectevents using the ST#play and ST.future.Element API&#39;s...." />
    <meta property="og:site_name" content="Sencha Documentation" />
    <meta property="og:url" content="http://docs.sencha.com/sencha_test/ST.event.Player.html" />
    <meta name="description" content="This class is rarely used directly, but is the underlying mechanism used the injectevents using the ST#play and ST.future.Element API's....">

    <link rel="stylesheet" type="text/css" href="css/prism.css">
        <link rel="stylesheet" type="text/css" href="css/app.css">
        <link rel='canonical' href='default.htm' /><meta name='description' content='Sencha Test API Documentation from Sencha.' />

            Docs Help

内容

                    Terms, Icons, and Labels
                    Access Levels
                    Member Types
                    Member Syntax
                    Member Flags
                    Class Icons
                    Member Icons
                    Navigation and Features
                    Class Member Quick-Nav Menu
                    Getter and Setter Methods
                    History Bar
                    Search and Filters
                    API Doc Class Metadata
                    Expanding and Collapsing Examples and Class Members
                    Desktop -vs- Mobile View
                    Viewing the Class Source

Terms, Icons, and Labels

Many classes have shortcut names used when creating (instantiating) a class with a
    configuration object.  The shortcut name is referred to as an alias (or xtype if the
    class extends Ext.Component).  The alias/xtype is listed next to the class name of
    applicable classes for quick reference.

Access Levels

Framework classes or their members may be specified as private or protected.  Else,
    the class / member is public.  Public, protected, and private are access
    descriptors used to convey how and when the class or class member should be used.

Public classes and class members are available for use by any other class or
    application code and may be relied upon as a stable and persistent within major product
    versions.  Public classes and members may safely be extended via a subclass.

Protected class members are stable public members intended to be used by the
    owning class or its subclasses.  Protected members may safely be extended via a subclass.

Private classes and class members are used internally by the framework and are not
    intended to be used by application developers.  Private classes and members may change or
    be omitted from the framework at any time without notice and should not be relied upon in
    application logic.

Member Types

Config - The configuration options for a class.

Property - Set once a class is instantiated. *See Read Only below.

Method - Actions that can be performed by a class.  Methods should be read as
    instance methods and can only be called from a instance of a given class.  Static methods
    that can be called directly from the class itself will have a static label next to the
    method name.  *See Static below.

Event - Events are specific to the framework event system allowing for classes to
    programmatically raise an event to be handled by one or more event handler methods.  DOM
    events, while handled by the framework event system, are not specifically described
    within the API documentation.  *For DOM events refer to the
    event reference page from MDN.

Theme Variable - Variables used by the visual theme engine employed by the
    framework.

Theme Mixin - Functions used by the visual theme engine employed by the framework
    and may use values set in various Theme Variables.

Member Syntax

Below is an example class member that we can disect to show the syntax of a class member
    (the lookupComponent method as viewed from the Ext.button.Button class in this case).

Ext.container.Container
view source

            lookupComponent
             ( item ) : Ext.Component

protected

Called when a raw config object is added to this container either during initialization of the items config,
        or when new items are added), or {@link #insert inserted.

This method converts the passed object into an instanced child component.

This may be overridden in subclasses when special processing needs to be applied to child creation.

Parameters

item :
                         Object

The config object being added.

Returns

                Ext.Component

The component to be added.

Let's look at each part of the member row:

Expand/Collapse - On the left-hand size of the member row is a control used to
    expand and collapse each member row to show / hide member details.

Member Name - The name of the class member (lookupComponent in this example)

Method Param - Any required or optional params used by a method (or passed to an
    event handler method) will be listed next to the method name within parenthesis
    (( item ) in this example)

Return type - The class instance or javascript object returned by the method or
    property (Ext.Component in this case).  This may be omitted for methods that do not
    return anything other than undefined or may display as multiple possible values
    separated by a forward slash / signifying that what is returned may depend on the
    results of the method call (i.e. a method may return a Component if a get method calls is
    successful or false if unsuccessful which would be displayed as
    Ext.Component/Boolean).

Flags - Any flags applicable to the member will be displayed next (PROTECTED in
    this example - see the Flags section below)

Member Origin - On the right-hand side of the member row is the class where the
    member was initially described (Ext.container.Container in this example).  The source
    class will be displayed as a blue link if the member originates from the current class
    and gray if it is inherited from an ancestor or mixed-in class.

Member Source - On the right-hand side below the member origin class is a link to
    view the member's source (view source in the example)

Params List - Each param for a class method will be listed using the same name
    found above in parenthesis, the type of class or object expected, and a description of
    the param (item : Object in the example).

Returns - If a class returns a value other than undefined a "Returns" section
    will note the type of class or object returned and a description (Ext.Component in the
    example)

Since (not shown in the example) - Some members will show which version of the
    product the member was first introduced (i.e. Available since 3.4.0 - not pictured in
    the example) just after the member description

Default (not shown in the example) - Configs often show the default config value
    to be applied to a class instance if not overridden (i.e. Defaults to: false)

Member Flags

The API documentation uses a number of flags to further commnicate the class member's
    function and intent.  The label may be represented by a text label, an abbreviation, or
    an icon.

Required - Required config when instantiating a class

Bindable - The config has a setter which allows this config to be set via ViewModel
    binding

Read Only - The property may be read, but cannot be used to configure /
    re-configure a class instance at runtime

Singleton - Singleton classes are instantiated immediately once defined and may not
    be instantiated manually

Static - A static method or property is a method or property belonging to the class
    itself, not an instance of the class

Chainable - Refers to methods that return the class instance back when called.
This enables chained method calls like: classInstance.method1().method2().etc();

Deprecated - A class or member that is scheduled for removal in a future
    framework version and is provided in the current version for backwards compatibility.
Deprecated classes and members will have a message directing you to the preferred class /
    method going forward.

Removed - A removed class or member that exists in documentation only as a
    reference for users upgrading between framework versions

Template - A method defined within a base class designed to be overridden by
    subclasses

Abstract - A class or member may be be defined as abstract.  Abstract classes and
    members establish a class structure and provide limited, if any, code.  Class-specific
    code will be furnished via overrides in subclasses.

Preventable - Events marked preventable will not fire if false is returned from
    an event handler

Class Icons

 - Indicates a framework class

 - A singleton framework class. *See the
    singleton flag for more information

 - A component-type framework class (any
    class within the Ext JS framework that extends Ext.Component)

 - Indicates that the class, member, or guide
    is new in the currently viewed version

Member Icons

 - Indicates a class member of type config

 - Indicates a class member of type property

 - Indicates a class member of type
    method

 - Indicates a class member of type event

 - Indicates a class member of type
    theme variable

 - Indicates a class member of type
    theme mixin

 - Indicates that the class, member, or guide
    is new in the currently viewed version

Navigation and Features

Class Member Quick-Nav Menu

Just below the class name on an API doc page is a row of buttons corresponding to the
    types of members owned by the current class.  Each button shows a count of members by
    type (this count is updated as filters are applied).  Clicking the button will navigate
    you to that member section.  Hovering over the member-type button will reveal a popup
    menu of all members of that type for quick navigation.

Getter and Setter Methods

Getting and setter methods that correlate to a class config option will show up in the
    methods section as well as in the configs section of both the API doc and the member-type
    menus just beneath the config they work with.  The getter and setter method documentation
    will be found in the config row for easy reference.

History Bar

Your page history is kept in localstorage and displayed (using the available real estate)
    just below the top title bar.  By default, the only search results shown are the pages
    matching the product / version you're currently viewing.  You can expand what is
    displayed by clicking on the  button on the
    right-hand side of the history bar and choosing the "All" radio option.  This will show
    all recent pages in the history bar for all products / versions.

Within the history config menu you will also see a listing of your recent page visits.
    The results are filtered by the "Current Product / Version" and "All" radio options.
    Clicking on the  button will clear the history bar as
    well as the history kept in local storage.

If "All" is selected in the history config menu the checkbox option for "Show product
    details in the history bar" will be enabled.  When checked, the product/version for each
    historic page will show alongside the page name in the history bar.  Hovering the cursor
    over the page names in the history bar will also show the product/version as a tooltip.

Search and Filters

Both API docs and guides can be searched for using the search field at the top of the
    page.

On API doc pages there is also a filter input field that filters the member rows
    using the filter string.  In addition to filtering by string you can filter the class
    members by access level and inheritance.  This is done using the checkboxes at the top of
    the page.  Note that filtering out private members also filters the API class
    navigation tree.

Clicking on an empty search field will show your last 10 searches for quick navigation.

API Doc Class Metadata

Each API doc page (with the exception of Javascript primitives pages) has a menu view of
    metadata relating to that class.  This metadata view will have one or more of the
    following:

Alternate Name - One or more additional class name synonymns (in Ext JS 6.0.0 the
    Ext.button.Button class has an alternate class name of Ext.Button).  Alternate class
    names are commonly maintained for backward compatibility.

Hierarchy - The hierararchy view lists the inheritance chain of the current class
    up through its ancestor classes up to the root base class.

Mixins - A list of classes that are mixed into the current class

Inherited Mixins - A list of classes that are mixed into an ancestor of the current
    class

Requires - All classes required to be defined for the class to be instantiated

Uses - A list of classes potentially used by the class at some point in its
    lifecycle, but not necessarily requried for the class to initially be instantiated

Subclasses - Classes that extend the current class

Expanding and Collapsing Examples and Class Members

Runnable examples (Fiddles) are expanded on a page by default.  You can collapse and
    expand example code blocks individually using the arrow on the top-left of the code
    block.  You can also toggle the collapse state of all examples using the toggle button on
    the top-right of the page.  The toggle-all state will be remembered between page loads.

Class members are collapsed on a page by default.  You can expand and collapse members
    using the arrow icon on the left of the member row or globally using the expand /
    collapse all toggle button top-right.

Desktop -vs- Mobile View

Viewing the docs on narrower screens or browsers will result in a view optimized for a
    smaller form factor.  The primary differences between the desktop and "mobile" view are:

Global navigation will be located in a menu on the left-hand side accessible via the
    hamburger menu icon.  The menu houses the following (on most pages):

The name of the current product (as a link to the product landing page)

The Sencha icon used to navigate back to the documentation home page

The product menu drop-down button

Tabs of navigation trees for the API docs and guides

Current context navigation and tools is located on the right-hand side accessible via
    the gear icon.  The context menu houses teh following:

The global search input field

(API doc) A "Filters" tab with the member filter, expand / collapse all examples
    button, expand / collapse all member rows button, the access level filter checkboxes,
    and the counts of each member

(API doc) A "Related Classes" tab containing the menu of metadata related to the
    current class

(Guides) The table of contents for the guide

Viewing the Class Source

The class source can be viewed by clicking on the class name at the top of an API doc
    page.  The source for class members can be viewed by clicking on the "view source" link
    on the right-hand side of the member row.

            ST.event.Player

                Sencha Test 1.0.3

                    Guides

                    API

        ▸

            ST

                        ▸

                            event

                                        ▸

                                            Driver

                                        ▸

                                            Event

                                        ▸

                                            GestureQueue

                                        ▸

                                            Injector

                                        ▸

                                            Playable

                                        ▸

                                            Player

                                        ▸

                                            Recorder

                        ▸

                            future

                                        ▸

                                            Button

                                        ▸

                                            Cell

                                        ▸

                                            CheckBox

                                        ▸

                                            ComboBox

                                        ▸

                                            Component

                                        ▸

                                            DataView

                                        ▸

                                            Element

                                        ▸

                                            Field

                                        ▸

                                            Grid

                                        ▸

                                            Item

                                        ▸

                                            Panel

                                        ▸

                                            Picker

                                        ▸

                                            Row

                                        ▸

                                            Select

                                        ▸

                                            Selection

                                        ▸

                                            SelectionModel

                                        ▸

                                            TextField

                        ▸

                            locator

                                        ▸

                                            Strategy

                        ▸

                            Alert

                        ▸

                            Block

                        ▸

                            Browser

                        ▸

                            browser

                        ▸

                            Element

                        ▸

                            Gate

                        ▸

                            jasmine

                        ▸

                            Locator

                        ▸

                            options

                        ▸

                            os

                        ▸

                            OS

                        ▸

                            Spec

                        ▸

                            status

                        ▸

                            Suite

                        ▸

                            supports

                        ▸

                            system

                        ▸

                            Test

                        ▸

                            Tests

                        ▸

                            Version

                        ▸

                            WatchDog

        ▸

            Array

        ▸

            Boolean

        ▸

            Date

        ▸

            Function

        ▸

            Number

        ▸

            Object

        ▸

            RegExp

        ▸

            String

        ▸

            Sencha Test 概述

        ▸

            安装和配置

        ▸

            入门

        ▸

            测试已有应用程序

        ▸

            测试新建应用程序

        ▸

            命令行工具CLI和归档服务器

        ▸

            项目, 场景(Scenarios)和套件(Suites)

        ▸

            使用Test Runner

        ▸

            单元测试 vs 功能测试

        ▸

            发布说明

        top

ST.event.Player

        <form autocomplete="off">
            <input type="text" type="search" placeholder="search" id="searchtext">

        </form>

            Filters

            Related Classes

                <input placeholder="Filter members..." type="search" id="member-filter-field" name="member-filter-field">

<input id="publicCheckbox" type="checkbox" value="member-public" checked=true/>Public

<input id="protectedCheckbox" type="checkbox" value="member-protected" checked=true/>Protected

<input id="privateCheckbox" type="checkbox" value="member-private" checked=true/>Private

<input id="inheritedCheckbox" type="checkbox" value="member-inherited" checked=true/>Inherited

                        configs

                        properties

                        methods

                        events

Hierarchy

ST.event.Driver
ST.event.Player

Summary

This class is rarely used directly, but is the underlying mechanism used the inject
events using the ST#play and ST.future.Element API's.

No members found using the current filters

configs

ST.event.Player
view source

            events

                : Array

The event queue to playback. This must be provided before
the start method is called.

ST.event.Player
view source

            pauseForAnimations

                : Boolean

True to pause event playback during animations, false
to ignore animations. Default is true.

Defaults to: true

ST.event.Player
view source

            timeout

                : Number

The event player will wait for certain conditions to be met before playing each
event in the queue.  These conditions include:

target element present and visible in DOM

Ext JS framework animations complete

If the time waited for these conditions to be met exceeds this timeout value,
playback will be aborted.

If specified, this will be the default timeout
for all events. Otherwise, the timeout will be
used.

ST.event.Player
view source

            translate

                : Boolean

false to disable event translation.  If false events that are not supported by
the browser's event APIs will simply be skipped.

Defaults to: true

ST.event.Player
view source

            visualFeedback

                : Boolean

false to disable visual feedback during event playback (mouse cursor, and "gesture"
indicator)

Defaults to: true

ST.event.Player
view source

            waitInterval

                : Number

Amount of time (in milliseconds) to wait before trying again if event cannot be
played due to target element not being available, animations in progress, etc.

Defaults to: ST.isIE9m ? 50 : 10

properties

ST.event.Player
view source

            pendingEvent

This property holds the event last pulled from the queue but yet to be played.

Defaults to: null

methods

ST.event.Player
view source

            add
             (

                        [index]
                        ,
                        events

                )

                :
                    ST.event.Playable[]

                    private
                    pri

Adds new ST.event.Playable to the play queue.

This method is not normally called by user code. Use ST#play insteaad.

Parameters

index :
                             Object
                        (optional)

events :
                             ST.event.Playable[]

The events to add or config objects for
them.

Returns

                :ST.event.Playable[]

The events array with each element now promoted
from config object to ST.event.Playable instance.

ST.event.Driver
view source

            getTimestamp

Returns the number of milliseconds since start was called.

ST.event.Player
view source

            setupGesturePublisher

                    private
                    pri

Applies override to gesture publisher if applicable

ST.event.Driver
view source

            start

Starts this object. If this object is already started, nothing happens.

ST.event.Driver
view source

            stop

Stops this object. If this object is not started, nothing happens.

events

ST.event.Driver
view source

            start
             (

                        this
                            , eOpts

                )

Fires when this object is started.

Parameters

this :
                             Ext.ux.event.Driver

eOpts : Object

The options object passed to Ext.util.Observable.addListener.

ST.event.Driver
view source

            stop
             (

                        this
                            , eOpts

                )

Fires when this object is stopped.

Parameters

this :
                             Ext.ux.event.Driver

eOpts : Object

The options object passed to Ext.util.Observable.addListener.

ST.event.Player
view source

            timeout
             (

                        this
                        ,
                        message
                            , eOpts

                )

Fires when the player times out while waiting for conditions to be met in order
for playback to proceed, for example, target element unavailable or animations
never finished.

Parameters

this :
                             ST.event.Player

message :
                             String

A message containing the reason for timeout

eOpts : Object

The options object passed to Ext.util.Observable.addListener.

            Sencha Test 1.0.3  | Terms of Use

Sencha Test 1.0.3

            <input type="text" id="mobile-input" />

Ext JS

Sencha Test

Cmd

GXT

IDE Plugins

Sencha Inspector

Architect

Touch

Web Application Manager

Ext JS

6.x

6.2.0 EA
                                                (classic)
                                                (modern)

6.0.2
                                                (classic)
                                                (modern)

6.0.1
                                                (classic)
                                                (modern)

6.0.0
                                                (classic)
                                                (modern)

5.x

                                        5.1.3
                                        5.1.2
                                        5.1.1
                                        5.1.0
                                        5.0.1
                                        5.0.0

4.x

                                        4.2.5
                                        4.1.3
                                        4.0.7

3.x

                                        3.4.0

Sencha Test

                        Sencha Test

Cmd

                        Cmd

GXT

                                4.x
                                3.x

IDE Plugins

                        IDE Plugins

Sencha Inspector

                        Sencha Inspector

Architect

                                Architect 3
                                Architect 4 EA

Touch

2.x

                                        Touch 2.4
                                        Touch 2.3
                                        Touch 2.2
                                        Touch 2.0

Web Application Manager

                        Web Application Manager

            <input id="historyTypeCurrent" type="radio" name="historyType" value="current" checked="true" />
            Current Product / Version

            <input id="historyTypeAll" type="radio" name="historyType" value="all" />
            All

                <input id="history-all-labels" type="checkbox" checked="true" />
                Show product details in the history bar


text:
module.exports = function sentenceCase (text) {
  return text
    .split(/\.[ \-_]/)
    .map(function (sentence) {
      return sentence.charAt(0).toUpperCase() + sentence.substr(1).toLowerCase()
    })
    .join('.-')
    .split(/[ \-_]/)
    .join(' ')
}


text:
<?php namespace Cmsable\PageType;

interface ConfigInterface{

    public function getPageTypeId();

    public function setPageTypeId($pageTypeId);

    public function get($name);

    public function set($name, $value);

    public function setFromModel($name, $value);

    public function hasChanged($name);

}


text:
"""
This shiw provides a QWebView either from QtWebKit or from QtWebEngine.
"""
import os
from pyqode.qt import QT_API
from pyqode.qt import PYQT5_API
from pyqode.qt import PYQT4_API
from pyqode.qt import PYSIDE_API

if os.environ[QT_API] in PYQT5_API:
    try:
        from PyQt5.QtWebKitWidgets import QWebView
        from PyQt5.QtWebKitWidgets import QWebPage
    except ImportError:
        try:
            from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView
            from PyQt5.QtWebEngineWidgets import QWebEnginePage as QWebPage
        except ImportError:
            # neither QtWebKit nor QtWebEngine installed
            QWebPage = None
            QWebView = None
elif os.environ[QT_API] in PYQT4_API:
    from PyQt4.QtWebKit import QWebView, QWebPage
elif os.environ[QT_API] in PYSIDE_API:
    from PySide.QtWebKit import QWebView, QWebPage
else:
    QWebPage = None
    QWebView = None


text:
require 'json'

module Hckr
  class JsonBuilder
    def initialize type
      @type = type
    end

    def build!
      links = Hckr::Scraper.new(@type).scrape!
      links.map { |o| Hash[o.each_pair.to_a] }.to_json
    end
  end
end


text:
test:
	make unit-test
	make flake8

unit-test:
	python -m unittest discover -s ./tests/  -p "test_*.py"

flake8:
	# I want to specify all files at once but I couldn't resolve it
	flake8  app/*/*.py *.py tests/*/*.py


text:
#include "cTimeManager.hpp"

#include <boost/date_time/posix_time/posix_time.hpp>

namespace elevatorSim {

/* TODO: use boost to avoid ambiguity */
const double cTimeManager::redrawInterval = 0.001;

cTimeManager::cTimeManager() {
   init();
}

void cTimeManager::init() {
   m_dwCurrTime = boost::posix_time::second_clock::local_time();
   m_dwLimitTime = m_dwCurrTime + boost::posix_time::seconds(1);
   totalFrames = 0;
   secondFrames = 0;
   FPS = 0;
}

void cTimeManager::update() {
   m_dwPrevTime = m_dwCurrTime;
   m_dwCurrTime = boost::posix_time::second_clock::local_time();
   m_dwLastFrameTime = m_dwCurrTime - m_dwPrevTime;
   m_dwWorldTime += m_dwLastFrameTime;

   ++totalFrames;
   ++secondFrames;

   if( m_dwCurrTime >= m_dwLimitTime ) {
      FPS = secondFrames;
      secondFrames = 0;
      m_dwLimitTime = m_dwCurrTime + boost::posix_time::seconds(1);
   }
}

} /* namespace elevatorSim */


text:
package com.zaradai.kunzite.trader.instruments;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;

public class TickCalculatorTest {
    private TickCalculator uut;

    @Before
    public void setUp() throws Exception {
        // will follow HKEX for stocks rules
        uut = new TickCalculator();
        uut.addDefinition(new TickDefinition(0.01, 0.25, 0.001));
        uut.addDefinition(new TickDefinition(0.25, 0.50, 0.005));
        uut.addDefinition(new TickDefinition(0.505, 10.00, 0.01));
        uut.addDefinition(new TickDefinition(10.01, 20.00, 0.02));
        uut.addDefinition(new TickDefinition(20.01, 100.00, 0.05));
        uut.addDefinition(new TickDefinition(100.01, 200.00, 0.10));
        uut.addDefinition(new TickDefinition(200.01, 500.00, 0.20));
        uut.addDefinition(new TickDefinition(500.01, 1000.00, 0.50));
        uut.addDefinition(new TickDefinition(1000.01, 2000.00, 1.00));
        uut.addDefinition(new TickDefinition(2000.01, 5000.00, 2.00));
        uut.addDefinition(new TickDefinition(5000.01, 9995.00, 5.00));
    }

    @Test
    public void shouldFindDefinition() throws Exception {
        assertThat(uut.getTickDefinitionFor(200.0).getValue(), is(0.10));
        assertThat(uut.getTickDefinitionFor(200.01).getValue(), is(0.20));
        assertThat(uut.getTickDefinitionFor(0.249).getValue(), is(0.001));
        assertThat(uut.getTickDefinitionFor(0.25).getValue(), is(0.005));
        assertThat(uut.getTickDefinitionFor(10000.0), is(nullValue()));
    }

    @Test
    public void shouldIndicateTickValidity() {
        assertThat(uut.isValidTick(0.251), is(false));
        assertThat(uut.isValidTick(0.255), is(true));
        assertThat(uut.isValidTick(10000.0), is(false));
    }

    @Test
    public void shouldWorkWithOneDefinition() {
        uut = new TickCalculator();
        uut.addDefinition(new TickDefinition(0.01, 10.00, 0.01));

        assertThat(uut.isValidTick(5.25), is(true));
        assertThat(uut.isValidTick(5.251), is(false));
    }

    @Test
    public void shouldHandleReset() throws Exception {
        uut.reset();

        assertThat(uut.getTickDefinitionFor(1), is(nullValue()));
    }
}