text:
require('chai').should();

describe('Bars generator', function() {
    function createBarElement() {
        var container = document.createElement('div');
        var svg = document.createElement('svg');
        container.appendChild(svg);
        var seriesCont = document.createElement('g');
        svg.appendChild(seriesCont);
        var el = document.createElement('g');
        seriesCont.appendChild(el);

        return el;
    }

    var Bars = require('../../../src/lib/generators/bars');
    var d3 = require('d3');

    describe('initialisation', function() {
        beforeEach(function () {
            // create a new svg element
            var el = createBarElement();
            this.bars = new Bars(el, {});
            this.bars.xScale = d3.scale.ordinal();
            this.bars.yScale = d3.scale.linear();
        });

        afterEach(function() {
            delete this.bars;
        });

        it('should create a bars object', function() {
            this.bars.should.exist;
        });

        it('should have an element to operate on', function() {
            this.bars.el.should.exist;
            this.bars.el.should.be.an.instanceof(HTMLElement);
        });

        it('should have a draw function', function() {
            this.bars.should.have.property('draw');
            this.bars.draw.should.be.a.function;
        });

    });

    describe('setting scales', function() {
        it('should set scales and accessor functions', function() {
            this.el = createBarElement();
            this.bars = new Bars(this.el, {});
            var xScale = d3.scale.ordinal();
            var yScale = d3.scale.linear();
            this.bars.setScales(xScale, yScale);
        });
    });

    describe('simple drawing', function() {
        beforeEach(function() {
            this.el = createBarElement();
            this.bars = new Bars(this.el, {
                duration: 0,
                category: 'category',
                value: 'value'
            });
            var xScale = d3.scale.ordinal();
            var yScale = d3.scale.linear();
            this.bars.setScales(xScale, yScale);
        });

        afterEach(function() {
            delete this.bars;
        });

        it('should draw rects correctly', function() {
            var self = this;
            var data = [
                { category: 'a', value: -1 },
                { category: 'b', value: 0 },
                { category: 'c', value: 1 }
            ];
            this.bars.category_scale.domain(['a', 'b', 'c']).rangeBands([0, 800]);
            this.bars.value_scale.domain([-1, 1]).range([200, 0]);
            return this.bars.draw(data)
                .then(function() {
                    var rects = self.bars.el.querySelectorAll('rect.bar');
                    rects.should.be.truthy;
                    rects.length.should.equal(3);
                    parseInt(rects[0].getAttribute('height'), 10).should.be.approximately(100, 2);
                    parseInt(rects[1].getAttribute('height'), 10).should.equal(0, 2);
                    parseInt(rects[2].getAttribute('height'), 10).should.equal(100, 2);
                });

        });

    });

});


text:
using CharacterGen.CharacterClasses;
using NUnit.Framework;

namespace CharacterGen.Tests.Unit.Generators.Classes
{
    [TestFixture]
    public class CharacterClassConstantsTests
    {
        [TestCase(CharacterClassConstants.Barbarian, "Barbarian")]
        [TestCase(CharacterClassConstants.Bard, "Bard")]
        [TestCase(CharacterClassConstants.Cleric, "Cleric")]
        [TestCase(CharacterClassConstants.Druid, "Druid")]
        [TestCase(CharacterClassConstants.Fighter, "Fighter")]
        [TestCase(CharacterClassConstants.Monk, "Monk")]
        [TestCase(CharacterClassConstants.Paladin, "Paladin")]
        [TestCase(CharacterClassConstants.Ranger, "Ranger")]
        [TestCase(CharacterClassConstants.Rogue, "Rogue")]
        [TestCase(CharacterClassConstants.Sorcerer, "Sorcerer")]
        [TestCase(CharacterClassConstants.Wizard, "Wizard")]
        [TestCase(CharacterClassConstants.Warrior, "Warrior")]
        [TestCase(CharacterClassConstants.Commoner, "Commoner")]
        [TestCase(CharacterClassConstants.Expert, "Expert")]
        [TestCase(CharacterClassConstants.Adept, "Adept")]
        [TestCase(CharacterClassConstants.Aristocrat, "Aristocrat")]
        [TestCase(CharacterClassConstants.Domains.Air, "Air")]
        [TestCase(CharacterClassConstants.Domains.Animal, "Animal")]
        [TestCase(CharacterClassConstants.Domains.Chaos, "Chaos")]
        [TestCase(CharacterClassConstants.Domains.Death, "Death")]
        [TestCase(CharacterClassConstants.Domains.Destruction, "Destruction")]
        [TestCase(CharacterClassConstants.Domains.Earth, "Earth")]
        [TestCase(CharacterClassConstants.Domains.Evil, "Evil")]
        [TestCase(CharacterClassConstants.Domains.Fire, "Fire")]
        [TestCase(CharacterClassConstants.Domains.Good, "Good")]
        [TestCase(CharacterClassConstants.Domains.Healing, "Healing")]
        [TestCase(CharacterClassConstants.Domains.Knowledge, "Knowledge")]
        [TestCase(CharacterClassConstants.Domains.Law, "Law")]
        [TestCase(CharacterClassConstants.Domains.Luck, "Luck")]
        [TestCase(CharacterClassConstants.Domains.Magic, "Magic")]
        [TestCase(CharacterClassConstants.Domains.Plant, "Plant")]
        [TestCase(CharacterClassConstants.Domains.Protection, "Protection")]
        [TestCase(CharacterClassConstants.Domains.Strength, "Strength")]
        [TestCase(CharacterClassConstants.Domains.Sun, "Sun")]
        [TestCase(CharacterClassConstants.Domains.Travel, "Travel")]
        [TestCase(CharacterClassConstants.Domains.Trickery, "Trickery")]
        [TestCase(CharacterClassConstants.Domains.War, "War")]
        [TestCase(CharacterClassConstants.Domains.Water, "Water")]
        [TestCase(CharacterClassConstants.Schools.Abjuration, "Abjuration")]
        [TestCase(CharacterClassConstants.Schools.Conjuration, "Conjuration")]
        [TestCase(CharacterClassConstants.Schools.Divination, "Divination")]
        [TestCase(CharacterClassConstants.Schools.Enchantment, "Enchantment")]
        [TestCase(CharacterClassConstants.Schools.Evocation, "Evocation")]
        [TestCase(CharacterClassConstants.Schools.Illusion, "Illusion")]
        [TestCase(CharacterClassConstants.Schools.Necromancy, "Necromancy")]
        [TestCase(CharacterClassConstants.Schools.Transmutation, "Transmutation")]
        [TestCase(CharacterClassConstants.TrainingTypes.Intuitive, "Intuitive")]
        [TestCase(CharacterClassConstants.TrainingTypes.SelfTaught, "Self-Taught")]
        [TestCase(CharacterClassConstants.TrainingTypes.Trained, "Trained")]
        public void Constant(string constant, string value)
        {
            Assert.That(constant, Is.EqualTo(value));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package axiom.saml.idp;

import org.apache.log4j.Logger;
import org.opensaml.common.SignableSAMLObject;

/**
 * Abstract factory used for building all versions and types of SAML Responses.
 * Contains a nested Assertion factory.
 *
 * @author rbrainard
 */
public abstract class AbstractResponseFactory extends AbstractXMLObjectFactory {

    @SuppressWarnings("unused")
    private static Logger logger = Logger.getLogger(AbstractResponseFactory.class);

    private String recipient;
    private AbstractAssertionFactory assertionFactory;

    /**
     * No-arg constructor. Should only be created from IdpConfiguration or subclasses.
     */
    protected AbstractResponseFactory() {
    }

    public abstract SignableSAMLObject buildResponse();

    public String getRecipient() {
        return recipient;
    }

    public void setRecipient(String recipient) {
        this.recipient = recipient;
    }

    public AbstractAssertionFactory getAssertionFactory() {
        return assertionFactory;
    }

    public void setAssertionFactory(AbstractAssertionFactory assertionFactory) {
        this.assertionFactory = assertionFactory;
    }

}


text:
package com.zkzong.mybatis.mapper;

import org.apache.ibatis.annotations.Param;

/**
 * Created by Zong on 2017/5/31.
 */
public interface PersonMapper {

    int insertPerson(@Param("name") String name, @Param("age") int age);

}


text:
import * as React from 'react';
import { ColumnProps } from '../column';
import { PaginatorTemplate } from '../paginator';

type DataTablePaginatorPositionType = 'top' | 'bottom' | 'both';

type DataTableSortModeType = 'single' | 'multiple';

type DataTableSortOrderType = 1 | 0 | -1 | undefined | null;

type DataTableEmptyMessageType = React.ReactNode | ((frozen: boolean) => React.ReactNode);

type DataTableSelectionModeType = 'single' | 'multiple' | 'checkbox' | 'radiobutton';

type DataTableColumnResizeModeType = 'fit' | 'expand';

type DataTableFilterMatchModeType = 'startsWith' | 'contains' | 'endsWith' | 'equals' | 'notEquals' | 'in' | 'lt' | 'lte' | 'gt' | 'gte' | 'custom';

type DataTableGlobalFilterType = string | undefined | null;

type DataTableMultiSortMetaType = DataTableSortMeta[] | undefined | null;

type DataTableCompareSelectionByType = 'deepEquals' | 'equals';

type DataTableStateStorageType = 'session' | 'local' | 'custom';

type DataTableAppendToType = 'self' | HTMLElement | undefined | null;

type DataTableSelectType = 'row' | 'cell' | 'checkbox' | 'radio' | 'all';

interface DataTableSortMeta {
    field: string;
    order: DataTableSortOrderType;
}

interface DataTableFilterMetaData {
    value: any;
    matchMode: DataTableFilterMatchModeType;
}

interface DataTableFilterMeta {
    [key: string]: DataTableFilterMetaData;
}

interface DataTableExpandedRows {
    [key: string]: boolean;
}

interface DataTableEditingRows {
    [key: string]: boolean;
}

interface DataTablePageParams {
    first: number;
    rows: number;
    page: number;
    pageCount: number;
}

interface DataTableVirtualScrollParams {
    first: number;
    rows: number;
}

interface DataTableRowToggleParams {
    data: any[];
}

interface DataTableColumnResizeEndParams {
    element: HTMLElement;
    column: ColumnProps;
    delta: number;
}

interface DataTableColumnResizerClickParams {
    originalEvent: React.MouseEvent<HTMLElement>;
    element: HTMLElement;
    column: ColumnProps;
}

interface DataTableSortParams {
    sortField: string;
    sortOrder: DataTableSortOrderType;
    multiSortMeta: DataTableMultiSortMetaType;
}

interface DataTableFilterParams {
    filters: DataTableFilterMeta;
}

interface DataTableSelectionChangeParams {
    originalEvent: React.SyntheticEvent;
    value: any;
    [key: string]: any;
}

interface DataTableRowEventParams {
    originalEvent: React.SyntheticEvent;
    data: any;
}

interface DataTableRowClickEventParams extends Omit<DataTableRowEventParams, 'originalEvent'> {
    originalEvent: React.MouseEvent<HTMLElement>;
    index: number;
}

interface DataTableCellClickEventParams {
    originalEvent: React.MouseEvent<HTMLElement>;
    value: any;
    field: string;
    rowData: any;
    rowIndex: number;
    cellIndex: number;
    selected: boolean;
}

interface DataTableRowEditParams extends DataTableRowEventParams {
    index: number;
}

interface DataTableRowEditSaveParams extends DataTableRowEditParams {
    valid: boolean;
}

interface DataTableSelectParams {
    originalEvent: React.SyntheticEvent;
    data: any;
    type: DataTableSelectType;
}

interface DataTableUnselectParams extends DataTableSelectParams { }

interface DataTableExportFunctionParams {
    data: any;
    field: string;
}

interface DataTableColReorderParams {
    originalEvent: React.DragEvent<HTMLElement>;
    dragIndex: number;
    dropIndex: number;
    columns: React.ReactElement;
}

interface DataTableRowReorderParams {
    originalEvent: React.DragEvent<HTMLElement>;
    value: any;
    dragIndex: number;
    dropIndex: number;
}

export interface DataTableProps {
    id?: string;
    value?: any[];
    header?: React.ReactNode;
    footer?: React.ReactNode;
    style?: object;
    className?: string;
    tableStyle?: object;
    tableClassName?: string;
    paginator?: boolean;
    paginatorPosition?: DataTablePaginatorPositionType;
    alwaysShowPaginator?: boolean;
    paginatorClassName?: string;
    paginatorTemplate?: PaginatorTemplate;
    paginatorLeft?: React.ReactNode;
    paginatorRight?: React.ReactNode;
    paginatorDropdownAppendTo?: DataTableAppendToType;
    pageLinkSize?: number;
    rowsPerPageOptions?: number[];
    currentPageReportTemplate?: string;
    first?: number;
    rows?: number;
    totalRecords?: number;
    lazy?: boolean;
    sortField?: string;
    sortOrder?: DataTableSortOrderType;
    multiSortMeta?: DataTableMultiSortMetaType;
    sortMode?: DataTableSortModeType;
    defaultSortOrder?: DataTableSortOrderType;
    removableSort?: boolean;
    emptyMessage?: DataTableEmptyMessageType;
    selectionMode?: DataTableSelectionModeType;
    dragSelection?: boolean;
    cellSelection?: boolean;
    selection?: any | any[];
    contextMenuSelection?: object;
    compareSelectionBy?: DataTableCompareSelectionByType;
    dataKey?: string;
    metaKeySelection?: boolean;
    selectOnEdit?: boolean;
    headerColumnGroup?: React.ReactNode;
    footerColumnGroup?: React.ReactNode;
    frozenHeaderColumnGroup?: React.ReactNode;
    frozenFooterColumnGroup?: React.ReactNode;
    expandedRows?: any[] | DataTableExpandedRows;
    resizableColumns?: boolean;
    columnResizeMode?: DataTableColumnResizeModeType;
    reorderableColumns?: boolean;
    filters?: DataTableFilterMeta;
    globalFilter?: DataTableGlobalFilterType;
    filterDelay?: number;
    filterLocale?: string;
    scrollable?: boolean;
    scrollHeight?: string;
    virtualScroll?: boolean;
    virtualScrollDelay?: number;
    virtualRowHeight?: number;
    frozenWidth?: string;
    frozenValue?: any[];
    csvSeparator?: string;
    exportFilename?: string;
    rowGroupMode?: string;
    autoLayout?: boolean;
    loading?: boolean;
    loadingIcon?: string;
    tabIndex?: number;
    stateKey?: string;
    stateStorage?: DataTableStateStorageType;
    groupField?: string;
    editMode?: string;
    editingRows?: any[] | DataTableEditingRows;
    expandableRowGroups?: boolean;
    rowHover?: boolean;
    showGridlines?: boolean;
    stripedRows?: boolean;
    showSelectionElement?(data: any): boolean | undefined | null;
    showRowReorderElement?(data: any): boolean | undefined | null;
    onSelectionChange?(e: DataTableSelectionChangeParams): void;
    onContextMenuSelectionChange?(e: DataTableSelectionChangeParams): void;
    rowExpansionTemplate?(data: any): React.ReactNode;
    onRowToggle?(e: DataTableRowToggleParams): void;
    rowClassName?(data: any): object;
    rowGroupHeaderTemplate?(data: any, index: number): React.ReactNode;
    rowGroupFooterTemplate?(data: any, index: number): React.ReactNode;
    onColumnResizeEnd?(e: DataTableColumnResizeEndParams): void;
    onColumnResizerClick?(e: DataTableColumnResizerClickParams): void;
    onColumnResizerDoubleClick?(e: DataTableColumnResizerClickParams): void;
    onSort?(e: DataTableSortParams): void;
    onPage?(e: DataTablePageParams): void;
    onFilter?(e: DataTableFilterParams): void;
    onVirtualScroll?(e: DataTableVirtualScrollParams): void;
    onAllRowsSelect?(e: DataTableSelectParams): void;
    onAllRowsUnselect?(e: DataTableUnselectParams): void;
    onRowClick?(e: DataTableRowClickEventParams): void;
    onRowDoubleClick?(e: DataTableRowClickEventParams): void;
    onRowSelect?(e: DataTableSelectParams): void;
    onRowUnselect?(e: DataTableUnselectParams): void;
    onRowExpand?(e: DataTableRowEventParams): void;
    onRowCollapse?(e: DataTableRowEventParams): void;
    onCellClick?(e: DataTableCellClickEventParams): void;
    onCellSelect?(e: DataTableSelectParams): void;
    onCellUnselect?(e: DataTableUnselectParams): void;
    onContextMenu?(e: DataTableRowEventParams): void;
    onColReorder?(e: DataTableColReorderParams): void;
    onRowReorder?(e: DataTableRowReorderParams): void;
    onValueChange?(value: any[]): void;
    rowEditorValidator?(data: any): boolean;
    onRowEditInit?(e: DataTableRowEditParams): void;
    onRowEditSave?(e: DataTableRowEditSaveParams): void;
    onRowEditCancel?(e: DataTableRowEditParams): void;
    onRowEditChange?(e: DataTableRowEditParams): void;
    exportFunction?(e: DataTableExportFunctionParams): any;
    customSaveState?(state: object): void;
    customRestoreState?(): object;
    onStateSave?(state: object): void;
    onStateRestore?(state: object): void;
}

export declare class DataTable extends React.Component<DataTableProps, any> {
    public reset(): void;
    public exportCSV(options: { selectionOnly: boolean }): void;
    public filter<T>(value: T, field: string, mode: DataTableFilterMatchModeType): void;
    public resetColumnOrder(): void;
    public closeEditingCell(): void;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.jasonmfehr.watson.texttospeech.ninja</groupId>
    <artifactId>watson-texttospeech-ninja</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <java-version>1.7</java-version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>${project.build.sourceEncoding}</project.reporting.outputEncoding>

        <ninja.version>5.1.2</ninja.version>
        <jetty.version>9.2.10.v20150310</jetty.version>
    </properties>

    <scm>
        <connection>scm:git:git@github.com:jasonmfehr/text-to-speech-java.git</connection>
        <developerConnection>scm:git:git@github.com:jasonmfehr/text-to-speech-java.git</developerConnection>
        <url>https://github.com/jasonmfehr/text-to-speech-java</url>
        <tag>HEAD</tag>
    </scm>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warName>${project.artifactId}</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.3.1</version>
                <executions>
                    <execution>
                        <id>enforce-banned-dependencies</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <bannedDependencies>
                                    <excludes>
                                        <exclude>commons-logging</exclude>
                                    </excludes>
                                </bannedDependencies>
                            </rules>
                            <fail>true</fail>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.version}</version>
                <configuration>
                    <contextPath>/</contextPath>
                    <stopKey>stop</stopKey>
                    <stopPort>8889</stopPort>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <reload>automatic</reload>
                    <scanTargetPatterns>
                        <scanTargetPattern>
                            <directory>target/classes</directory>
                            <includes>
                                <include>**/*</include>
                            </includes>
                            <excludes>
                                <exclude>**/*.ftl.html</exclude>
                                <exclude>assets/**</exclude>
                            </excludes>
                        </scanTargetPattern>
                    </scanTargetPatterns>
                    <systemProperties>
                        <systemProperty>
                            <name>ninja.mode</name>
                            <value>dev</value>
                        </systemProperty>
                    </systemProperties>
                </configuration>
            </plugin>
            <!-- Allows you to run Ninja via the SuperDevMode. -->
            <!-- run "mvn ninja:run" on the command line for the best -->
            <!-- development experience. -->
            <plugin>
                <groupId>org.ninjaframework</groupId>
                <artifactId>ninja-maven-plugin</artifactId>
                <version>${ninja.version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.ninjaframework</groupId>
            <artifactId>ninja-servlet</artifactId>
            <version>${ninja.version}</version>
        </dependency>
        <dependency>
            <groupId>org.ninjaframework</groupId>
            <artifactId>ninja-test-utilities</artifactId>
            <version>${ninja.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
            <version>4.3.4</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.4</version>
        </dependency>

        <!-- logging dependencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.3</version>
        </dependency>
    </dependencies>
</project>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.CL_PLATFORM_HOST_TIMER_RESOLUTION.html">

Redirecting to constant.CL_PLATFORM_HOST_TIMER_RESOLUTION.html...


text:
from dateutil import parser

from ._common_conversion import _to_str

try:
    from xml.etree import cElementTree as ETree
except ImportError:
    from xml.etree import ElementTree as ETree

from .models import (
    ServiceProperties,
    Logging,
    Metrics,
    CorsRule,
    AccessPolicy,
    _dict,
    GeoReplication,
    ServiceStats,
    DeleteRetentionPolicy,
    StaticWebsite,
)

def _to_int(value):
    return value if value is None else int(value)

def _bool(value):
    return value.lower() == 'true'

def _to_upper_str(value):
    return _to_str(value).upper() if value is not None else None

def _get_download_size(start_range, end_range, resource_size):
    if start_range is not None:
        end_range = end_range if end_range else (resource_size if resource_size else None)
        if end_range is not None:
            return end_range - start_range
        else:
            return None
    else:
        return resource_size

GET_PROPERTIES_ATTRIBUTE_MAP = {
    'last-modified': (None, 'last_modified', parser.parse),
    'etag': (None, 'etag', _to_str),
    'x-ms-blob-type': (None, 'blob_type', _to_str),
    'content-length': (None, 'content_length', _to_int),
    'content-range': (None, 'content_range', _to_str),
    'x-ms-blob-sequence-number': (None, 'page_blob_sequence_number', _to_int),
    'x-ms-blob-committed-block-count': (None, 'append_blob_committed_block_count', _to_int),
    'x-ms-blob-public-access': (None, 'public_access', _to_str),
    'x-ms-access-tier': (None, 'blob_tier', _to_str),
    'x-ms-access-tier-change-time': (None, 'blob_tier_change_time', parser.parse),
    'x-ms-access-tier-inferred': (None, 'blob_tier_inferred', _bool),
    'x-ms-archive-status': (None, 'rehydration_status', _to_str),
    'x-ms-share-quota': (None, 'quota', _to_int),
    'x-ms-server-encrypted': (None, 'server_encrypted', _bool),
    'x-ms-encryption-key-sha256': (None, 'encryption_key_sha256', _to_str),
    'x-ms-creation-time': (None, 'creation_time', parser.parse),
    'content-type': ('content_settings', 'content_type', _to_str),
    'cache-control': ('content_settings', 'cache_control', _to_str),
    'content-encoding': ('content_settings', 'content_encoding', _to_str),
    'content-disposition': ('content_settings', 'content_disposition', _to_str),
    'content-language': ('content_settings', 'content_language', _to_str),
    'content-md5': ('content_settings', 'content_md5', _to_str),
    'x-ms-lease-status': ('lease', 'status', _to_str),
    'x-ms-lease-state': ('lease', 'state', _to_str),
    'x-ms-lease-duration': ('lease', 'duration', _to_str),
    'x-ms-copy-id': ('copy', 'id', _to_str),
    'x-ms-copy-source': ('copy', 'source', _to_str),
    'x-ms-copy-status': ('copy', 'status', _to_str),
    'x-ms-copy-progress': ('copy', 'progress', _to_str),
    'x-ms-copy-completion-time': ('copy', 'completion_time', parser.parse),
    'x-ms-copy-destination-snapshot': ('copy', 'destination_snapshot_time', _to_str),
    'x-ms-copy-status-description': ('copy', 'status_description', _to_str),
    'x-ms-has-immutability-policy': (None, 'has_immutability_policy', _bool),
    'x-ms-has-legal-hold': (None, 'has_legal_hold', _bool),
    'x-ms-file-attributes': ('smb_properties', 'ntfs_attributes', _to_str),
    'x-ms-file-creation-time': ('smb_properties', 'creation_time', parser.parse, True),
    'x-ms-file-last-write-time': ('smb_properties', 'last_write_time', parser.parse, True),
    'x-ms-file-change-time': ('smb_properties', 'change_time', parser.parse, True),
    'x-ms-file-permission-key': ('smb_properties', 'permission_key', _to_str),
    'x-ms-file-id': ('smb_properties', 'file_id', _to_str),
    'x-ms-file-parent-id': ('smb_properties', 'parent_id', _to_str),
}

def _parse_metadata(response):
    '''
    Extracts out resource metadata information.
    '''

    if response is None or response.headers is None:
        return None

    metadata = _dict()
    for key, value in response.headers.items():
        if key.lower().startswith('x-ms-meta-'):
            metadata[key[10:]] = _to_str(value)

    return metadata

def _parse_properties(response, result_class):
    '''
    Extracts out resource properties and metadata information.
    Ignores the standard http headers.
    '''

    if response is None or response.headers is None:
        return None

    props = result_class()
    for key, value in response.headers.items():
        info = GET_PROPERTIES_ATTRIBUTE_MAP.get(key)
        if info:
            if info[0] is None:
                setattr(props, info[1], info[2](value))
            else:
                attr = getattr(props, info[0])
                # if info[3] is True, time zones in parsed strings are ignored and a naive :class:`datetime` object
                # will be returned.
                ignoretz = info[3] if len(info) > 3 else False
                header_value = info[2](value, ignoretz=ignoretz) if info[2] is parser.parse else info[2](value)
                setattr(attr, info[1], header_value)

    if hasattr(props, 'blob_type') and props.blob_type == 'PageBlob' and hasattr(props, 'blob_tier') and props.blob_tier is not None:
        props.blob_tier = _to_upper_str(props.blob_tier)
    return props

def _parse_length_from_content_range(content_range):
    '''
    Parses the blob length from the content range header: bytes 1-3/65537
    '''
    if content_range is None:
        return None

    # First, split in space and take the second half: '1-3/65537'
    # Next, split on slash and take the second half: '65537'
    # Finally, convert to an int: 65537
    return int(content_range.split(' ', 1)[1].split('/', 1)[1])

def _convert_xml_to_signed_identifiers(response):
    '''
    <?xml version="1.0" encoding="utf-8"?>
    <SignedIdentifiers>
      <SignedIdentifier>
        <Id>unique-value</Id>
        <AccessPolicy>
          <Start>start-time</Start>
          <Expiry>expiry-time</Expiry>
          <Permission>abbreviated-permission-list</Permission>
        </AccessPolicy>
      </SignedIdentifier>
    </SignedIdentifiers>
    '''
    if response is None or response.body is None:
        return None

    list_element = ETree.fromstring(response.body)
    signed_identifiers = _dict()

    for signed_identifier_element in list_element.findall('SignedIdentifier'):
        # Id element
        id = signed_identifier_element.find('Id').text

        # Access policy element
        access_policy = AccessPolicy()
        access_policy_element = signed_identifier_element.find('AccessPolicy')
        if access_policy_element is not None:
            start_element = access_policy_element.find('Start')
            if start_element is not None:
                access_policy.start = parser.parse(start_element.text)

            expiry_element = access_policy_element.find('Expiry')
            if expiry_element is not None:
                access_policy.expiry = parser.parse(expiry_element.text)

            access_policy.permission = access_policy_element.findtext('Permission')

        signed_identifiers[id] = access_policy

    return signed_identifiers

def _convert_xml_to_service_stats(response):
    '''
    <?xml version="1.0" encoding="utf-8"?>
    <StorageServiceStats>
      <GeoReplication>
          <Status>live|bootstrap|unavailable</Status>
          <LastSyncTime>sync-time|<empty></LastSyncTime>
      </GeoReplication>
    </StorageServiceStats>
    '''
    if response is None or response.body is None:
        return None

    service_stats_element = ETree.fromstring(response.body)

    geo_replication_element = service_stats_element.find('GeoReplication')

    geo_replication = GeoReplication()
    geo_replication.status = geo_replication_element.find('Status').text
    last_sync_time = geo_replication_element.find('LastSyncTime').text
    geo_replication.last_sync_time = parser.parse(last_sync_time) if last_sync_time else None

    service_stats = ServiceStats()
    service_stats.geo_replication = geo_replication
    return service_stats

def _convert_xml_to_service_properties(response):
    '''
    <?xml version="1.0" encoding="utf-8"?>
    <StorageServiceProperties>
        <Logging>
            <Version>version-number</Version>
            <Delete>true|false</Delete>
            <Read>true|false</Read>
            <Write>true|false</Write>
            <RetentionPolicy>
                <Enabled>true|false</Enabled>
                <Days>number-of-days</Days>
            </RetentionPolicy>
        </Logging>
        <HourMetrics>
            <Version>version-number</Version>
            <Enabled>true|false</Enabled>
            <IncludeAPIs>true|false</IncludeAPIs>
            <RetentionPolicy>
                <Enabled>true|false</Enabled>
                <Days>number-of-days</Days>
            </RetentionPolicy>
        </HourMetrics>
        <MinuteMetrics>
            <Version>version-number</Version>
            <Enabled>true|false</Enabled>
            <IncludeAPIs>true|false</IncludeAPIs>
            <RetentionPolicy>
                <Enabled>true|false</Enabled>
                <Days>number-of-days</Days>
            </RetentionPolicy>
        </MinuteMetrics>
        <Cors>
            <CorsRule>
                <AllowedOrigins>comma-separated-list-of-allowed-origins</AllowedOrigins>
                <AllowedMethods>comma-separated-list-of-HTTP-verb</AllowedMethods>
                <MaxAgeInSeconds>max-caching-age-in-seconds</MaxAgeInSeconds>
                <ExposedHeaders>comma-seperated-list-of-response-headers</ExposedHeaders>
                <AllowedHeaders>comma-seperated-list-of-request-headers</AllowedHeaders>
            </CorsRule>
        </Cors>
        <DeleteRetentionPolicy>
             <Enabled>true|false</Enabled>
             <Days>number-of-days</Days>
        </DeleteRetentionPolicy>
        <StaticWebsite>
            <Enabled>true|false</Enabled>
            <IndexDocument></IndexDocument>
            <ErrorDocument404Path></ErrorDocument404Path>
        </StaticWebsite>
    </StorageServiceProperties>
    '''
    if response is None or response.body is None:
        return None

    service_properties_element = ETree.fromstring(response.body)
    service_properties = ServiceProperties()

    # Logging
    logging = service_properties_element.find('Logging')
    if logging is not None:
        service_properties.logging = Logging()
        service_properties.logging.version = logging.find('Version').text
        service_properties.logging.delete = _bool(logging.find('Delete').text)
        service_properties.logging.read = _bool(logging.find('Read').text)
        service_properties.logging.write = _bool(logging.find('Write').text)

        _convert_xml_to_retention_policy(logging.find('RetentionPolicy'),
                                         service_properties.logging.retention_policy)
    # HourMetrics
    hour_metrics_element = service_properties_element.find('HourMetrics')
    if hour_metrics_element is not None:
        service_properties.hour_metrics = Metrics()
        _convert_xml_to_metrics(hour_metrics_element, service_properties.hour_metrics)

    # MinuteMetrics
    minute_metrics_element = service_properties_element.find('MinuteMetrics')
    if minute_metrics_element is not None:
        service_properties.minute_metrics = Metrics()
        _convert_xml_to_metrics(minute_metrics_element, service_properties.minute_metrics)

    # CORS
    cors = service_properties_element.find('Cors')
    if cors is not None:
        service_properties.cors = list()
        for rule in cors.findall('CorsRule'):
            allowed_origins = rule.find('AllowedOrigins').text.split(',')

            allowed_methods = rule.find('AllowedMethods').text.split(',')

            max_age_in_seconds = int(rule.find('MaxAgeInSeconds').text)

            cors_rule = CorsRule(allowed_origins, allowed_methods, max_age_in_seconds)

            exposed_headers = rule.find('ExposedHeaders').text
            if exposed_headers is not None:
                cors_rule.exposed_headers = exposed_headers.split(',')

            allowed_headers = rule.find('AllowedHeaders').text
            if allowed_headers is not None:
                cors_rule.allowed_headers = allowed_headers.split(',')

            service_properties.cors.append(cors_rule)

    # Target version
    target_version = service_properties_element.find('DefaultServiceVersion')
    if target_version is not None:
        service_properties.target_version = target_version.text

    # DeleteRetentionPolicy
    delete_retention_policy_element = service_properties_element.find('DeleteRetentionPolicy')
    if delete_retention_policy_element is not None:
        service_properties.delete_retention_policy = DeleteRetentionPolicy()
        policy_enabled = _bool(delete_retention_policy_element.find('Enabled').text)
        service_properties.delete_retention_policy.enabled = policy_enabled

        if policy_enabled:
            service_properties.delete_retention_policy.days = int(delete_retention_policy_element.find('Days').text)

    # StaticWebsite
    static_website_element = service_properties_element.find('StaticWebsite')
    if static_website_element is not None:
        service_properties.static_website = StaticWebsite()
        service_properties.static_website.enabled = _bool(static_website_element.find('Enabled').text)

        index_document_element = static_website_element.find('IndexDocument')
        if index_document_element is not None:
            service_properties.static_website.index_document = index_document_element.text

        error_document_element = static_website_element.find('ErrorDocument404Path')
        if error_document_element is not None:
            service_properties.static_website.error_document_404_path = error_document_element.text

    return service_properties

def _convert_xml_to_metrics(xml, metrics):
    '''
    <Version>version-number</Version>
    <Enabled>true|false</Enabled>
    <IncludeAPIs>true|false</IncludeAPIs>
    <RetentionPolicy>
        <Enabled>true|false</Enabled>
        <Days>number-of-days</Days>
    </RetentionPolicy>
    '''
    # Version
    metrics.version = xml.find('Version').text

    # Enabled
    metrics.enabled = _bool(xml.find('Enabled').text)

    # IncludeAPIs
    include_apis_element = xml.find('IncludeAPIs')
    if include_apis_element is not None:
        metrics.include_apis = _bool(include_apis_element.text)

    # RetentionPolicy
    _convert_xml_to_retention_policy(xml.find('RetentionPolicy'), metrics.retention_policy)

def _convert_xml_to_retention_policy(xml, retention_policy):
    '''
    <Enabled>true|false</Enabled>
    <Days>number-of-days</Days>
    '''
    # Enabled
    retention_policy.enabled = _bool(xml.find('Enabled').text)

    # Days
    days_element = xml.find('Days')
    if days_element is not None:
        retention_policy.days = int(days_element.text)


text:
package org.keycloak.protocol.saml;

import org.keycloak.common.VerificationException;
import org.keycloak.common.util.PemUtils;
import org.keycloak.models.ClientModel;
import org.keycloak.saml.SignatureAlgorithm;
import org.keycloak.saml.common.constants.GeneralConstants;
import org.keycloak.saml.common.exceptions.ProcessingException;
import org.keycloak.saml.processing.api.saml.v2.sig.SAML2Signature;
import org.keycloak.saml.processing.web.util.RedirectBindingUtil;
import org.w3c.dom.Document;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class SamlProtocolUtils {

    public static void verifyDocumentSignature(ClientModel client, Document document) throws VerificationException {
        SamlClient samlClient = new SamlClient(client);
        if (!samlClient.requiresClientSignature()) {
            return;
        }
        PublicKey publicKey = getSignatureValidationKey(client);
        verifyDocumentSignature(document, publicKey);
    }

    public static void verifyDocumentSignature(Document document, PublicKey publicKey) throws VerificationException {
        SAML2Signature saml2Signature = new SAML2Signature();
        try {
            if (!saml2Signature.validate(document, publicKey)) {
                throw new VerificationException("Invalid signature on document");
            }
        } catch (ProcessingException e) {
            throw new VerificationException("Error validating signature", e);
        }
    }

    public static PublicKey getSignatureValidationKey(ClientModel client) throws VerificationException {
        return getPublicKey(new SamlClient(client).getClientSigningCertificate());
    }

    public static PublicKey getEncryptionValidationKey(ClientModel client) throws VerificationException {
        return getPublicKey(client, SamlConfigAttributes.SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE);
    }

    public static PublicKey getPublicKey(ClientModel client, String attribute) throws VerificationException {
        String certPem = client.getAttribute(attribute);
        return getPublicKey(certPem);
    }

    private static PublicKey getPublicKey(String certPem) throws VerificationException {
        if (certPem == null) throw new VerificationException("Client does not have a public key.");
        Certificate cert = null;
        try {
            cert = PemUtils.decodeCertificate(certPem);
        } catch (Exception e) {
            throw new VerificationException("Could not decode cert", e);
        }
        return cert.getPublicKey();
    }

    public static void verifyRedirectSignature(PublicKey publicKey, UriInfo uriInformation, String paramKey) throws VerificationException {
        MultivaluedMap<String, String> encodedParams = uriInformation.getQueryParameters(false);
        String request = encodedParams.getFirst(paramKey);
        String algorithm = encodedParams.getFirst(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);
        String signature = encodedParams.getFirst(GeneralConstants.SAML_SIGNATURE_REQUEST_KEY);
        String decodedAlgorithm = uriInformation.getQueryParameters(true).getFirst(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY);

        if (request == null) throw new VerificationException("SAM was null");
        if (algorithm == null) throw new VerificationException("SigAlg was null");
        if (signature == null) throw new VerificationException("Signature was null");

        // Shibboleth doesn't sign the document for redirect binding.
        // todo maybe a flag?

        UriBuilder builder = UriBuilder.fromPath("/")
                .queryParam(paramKey, request);
        if (encodedParams.containsKey(GeneralConstants.RELAY_STATE)) {
            builder.queryParam(GeneralConstants.RELAY_STATE, encodedParams.getFirst(GeneralConstants.RELAY_STATE));
        }
        builder.queryParam(GeneralConstants.SAML_SIG_ALG_REQUEST_KEY, algorithm);
        String rawQuery = builder.build().getRawQuery();

        try {
            byte[] decodedSignature = RedirectBindingUtil.urlBase64Decode(signature);

            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.getFromXmlMethod(decodedAlgorithm);
            Signature validator = signatureAlgorithm.createSignature(); // todo plugin signature alg
            validator.initVerify(publicKey);
            validator.update(rawQuery.getBytes("UTF-8"));
            if (!validator.verify(decodedSignature)) {
                throw new VerificationException("Invalid query param signature");
            }
        } catch (Exception e) {
            throw new VerificationException(e);
        }
    }

}


text:
from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING

import sys

import difflib
import errno
import filecmp
import functools
import io
import json
import logging
import os
import shlex
import shutil

import click
from watch_hook import WatchHook

# Use this instead of click.option
click_option = functools.partial(click.option, show_default=True)
click_option_no_default = functools.partial(click.option, show_default=False)

from ambassador import Config, IR, Diagnostics, EnvoyConfig
from ambassador.fetch import ResourceFetcher
from ambassador.utils import parse_yaml, SecretHandler, SecretInfo, dump_json, parse_bool
from kat.utils import ShellCommand

if TYPE_CHECKING:
    from ambassador.ir import IRResource

KubeResource = Dict[str, Any]
KubeList = List[KubeResource]
WattDict = Dict[str, KubeList]

class LabelSpec:
    def __init__(self, serialization: str) -> None:
        if '=' not in serialization:
            raise Exception(f"label serialization must be key=value, not {serialization}")

        (key, value) = serialization.split('=', 1)

        self.key = key
        self.value = value

    def __str__(self) -> str:
        return f"{self.key}={self.value}"

    def match(self, labels: Dict[str, str]) -> bool:
        return bool(labels.get(self.key, None) == self.value)

class FieldSpec:
    def __init__(self, serialization: str) -> None:
        if '=' not in serialization:
            raise Exception(f"field serialization must be key=value, not {serialization}")

        (key, value) = serialization.split('=', 1)

        self.elements = key.split('.')
        self.value = value

    def __str__(self) -> str:
        return f"{'.'.join(self.elements)}={self.value}"

    def match(self, resource: Dict[str, Any]) -> bool:
        node = resource

        for el in self.elements[:-1]:
            node = node.get(el, None)

            if node is None:
                return False

        return bool(node.get(self.elements[-1], None) == self.value)

class WatchResult:
    def __init__(self, kind: str, watch_id: str) -> None:
        self.kind = kind
        self.watch_id = watch_id

class WatchSpec:
    def __init__(self, logger: logging.Logger, kind: str, namespace: Optional[str],
                 labels: Optional[str], fields: Optional[str]=None,
                 bootstrap: Optional[bool]=False):
        self.logger = logger
        self.kind = kind
        self.match_kinds = { self.kind.lower(): True }
        self.namespace = namespace
        self.labels: Optional[List[LabelSpec]] = None
        self.fields: Optional[List[FieldSpec]] = None
        self.bootstrap = bootstrap

        if self.kind == 'ingresses':
            self.match_kinds['ingress'] = True

        if labels:
            self.labels = [ LabelSpec(l) for l in labels.split(',') ]

        if fields:
            self.fields = [ FieldSpec(f) for f in fields.split(',') ]

    def _labelstr(self) -> str:
        return ",".join([ str(x) for x in self.labels or [] ])

    def _fieldstr(self) -> str:
        return ",".join([ str(x) for x in self.fields or [] ])

    @staticmethod
    def _star(s: Optional[str]) -> str:
        return s if s else "*"

    def __repr__(self) -> str:
        s = f"{self.kind}|{self._star(self.namespace)}|{self._star(self._fieldstr())}|{self._star(self._labelstr())}"

        if self.bootstrap:
            s += ' (bootstrap)'

        return f"<{s}>"

    def __str__(self) -> str:
        if self.bootstrap:
            return f"{self.kind}|bootstrap"
        else:
            return f"{self.kind}|{self._star(self.namespace)}|{self._star(self._fieldstr())}|{self._star(self._labelstr())}"

    def match(self, obj: KubeResource) -> Optional[WatchResult]:
        kind: Optional[str] = obj.get('kind') or None
        metadata: Dict[str, Any] = obj.get('metadata') or {}
        name: Optional[str] = metadata.get('name') or None
        namespace: str = metadata.get('namespace') or 'default'
        labels: Dict[str, str] = metadata.get('labels') or {}

        if not kind or not name:
            self.logger.error(f"K8s object requires kind and name: {obj}")
            return None

        # self.logger.debug(f"match {self}: check {obj}")
        match_kind_str = ','.join(sorted(self.match_kinds.keys()))

        # OK. Does the kind match up?
        if kind.lower() not in self.match_kinds:
            # self.logger.debug(f"match {self}: mismatch for kind {kind}, match_kinds {match_kind_str}")
            return None

        # How about namespace (if present)?
        if self.namespace:
            if namespace != self.namespace:
                # self.logger.debug(f"match {self}: mismatch for namespace {namespace}")
                return None

        # OK, check labels...
        if self.labels:
            for l in self.labels:
                if not l.match(labels):
                    # self.logger.debug(f"match {self}: mismatch for label {l}")
                    return None

        # ...and fields.
        if self.fields:
            for f in self.fields:
                if not f.match(obj):
                    # self.logger.debug(f"match {self}: mismatch for field {f}")
                    return None

        # Woo, it worked!
        self.logger.debug(f"match {self} - {match_kind_str}: good!")
        # self.logger.debug(f"{obj}")

        return WatchResult(kind=self.kind, watch_id=str(self))

class Mockery:
    def __init__(self, logger: logging.Logger, debug: bool, sources: List[str],
                 labels: Optional[str], namespace: Optional[str], watch: str) -> None:
        self.logger = logger
        self.debug = debug
        self.sources = sources
        self.namespace = namespace
        self.watch = watch

        self.watch_specs: Dict[str, WatchSpec] = {}

        # Set up bootstrap sources.
        for source in sources:
            bootstrap_watch = WatchSpec(
                logger=self.logger,
                kind=source,
                namespace=self.namespace,
                labels=labels,
                bootstrap=True
            )

            if not self.maybe_add(bootstrap_watch):
                self.logger.error(f"how is a bootstrap watch not new? {bootstrap_watch}")
                sys.exit(1)

    def maybe_add(self, w: WatchSpec) -> bool:
        key = str(w)

        if key in self.watch_specs:
            return False
        else:
            self.watch_specs[key] = w

        return True

    def load(self, manifest: KubeList) -> WattDict:
        collected: Dict[str, Dict[str, KubeResource]] = {}
        watt_k8s: WattDict = {}

        self.logger.info("LOADING:")

        for spec in self.watch_specs.values():
            self.logger.debug(f"{repr(spec)}")

        for obj in manifest:
            metadata = obj.get('metadata') or {}
            name = metadata.get('name')

            if not name:
                self.logger.debug(f"skipping unnamed object {obj}")
                continue

            # self.logger.debug(f"consider {obj}")

            for w in self.watch_specs.values():
                m = w.match(obj)

                if m:
                    by_type = collected.setdefault(m.kind, {})

                    # If we already have this object's name in the collection,
                    # this is a duplicate find.
                    if name not in by_type:
                        by_type[name] = obj

        # Once that's all done, flatten everything.
        for kind in collected.keys():
            watt_k8s[kind] = list(collected[kind].values())

        self.snapshot = dump_json({ 'Consul': {}, 'Kubernetes': watt_k8s }, pretty=True)

        return watt_k8s

    def run_hook(self) -> Tuple[bool, bool]:
        self.logger.info("RUNNING HOOK")

        yaml_stream = io.StringIO(self.snapshot)

        wh = WatchHook(self.logger, yaml_stream)

        any_changes = False

        if wh.watchset:
            for w in wh.watchset.get("kubernetes-watches") or []:
                potential = WatchSpec(
                    logger=self.logger,
                    kind=w['kind'],
                    namespace=w.get('namespace'),
                    labels=w.get('label-selector'),
                    fields=w.get('field-selector'),
                    bootstrap=False
                )

                if self.maybe_add(potential):
                    any_changes = True

        return True, any_changes

class MockSecretHandler(SecretHandler):
    def load_secret(self, resource: 'IRResource', secret_name: str, namespace: str) -> Optional[SecretInfo]:
        # Allow an environment variable to state whether we're in Edge Stack. But keep the
        # existing condition as sufficient, so that there is less of a chance of breaking
        # things running in a container with this file present.
        if parse_bool(os.environ.get('EDGE_STACK', 'false')) or os.path.exists('/ambassador/.edge_stack'):
            if ((secret_name == "fallback-self-signed-cert") and
                (namespace == Config.ambassador_namespace)):
                # This is Edge Stack. Force the fake TLS secret.

                self.logger.info(f"MockSecretHandler: mocking fallback secret {secret_name}.{namespace}")
                return SecretInfo(secret_name, namespace, "mocked-fallback-secret",
                                  "-fallback-cert-", "-fallback-key-", decode_b64=False)

        self.logger.debug(f"MockSecretHandler: cannot load {secret_name}.{namespace}")
        return None

@click.command(help="Mock the watt/watch_hook/diagd cycle to generate an IR from a Kubernetes YAML manifest.")
@click_option('--debug/--no-debug', default=True,
              help="enable debugging")
@click_option('-n', '--namespace', type=click.STRING,
              help="namespace to watch [default: all namespaces])")
@click_option('-s', '--source', type=click.STRING, multiple=True,
              help="define initial source types [default: all Ambassador resources]")
@click_option('--labels', type=click.STRING, multiple=True,
              help="define initial label selector")
@click_option('--force-pod-labels/--no-force-pod-labels', default=True,
              help="copy initial label selector to /tmp/ambassador-pod-info/labels")
@click_option('--kat-name', '--kat', type=click.STRING,
              help="emulate a running KAT test with this name")
@click_option('-w', '--watch', type=click.STRING, default="python /ambassador/watch_hook.py",
              help="define a watch hook")
@click_option('--diff-path', '--diff', type=click.STRING,
              help="directory to diff against")
@click_option('--include-ir/--no-include-ir', '--ir/--no-ir', default=False,
              help="include IR in diff when using --diff-path")
@click_option('--include-aconf/--no-include-aconf', '--aconf/--no-aconf', default=False,
              help="include AConf in diff when using --diff-path")
@click_option('--update/--no-update', default=False,
              help="update the diff path when finished")
@click.argument('k8s-yaml-paths', nargs=-1)
def main(k8s_yaml_paths: List[str], debug: bool, force_pod_labels: bool, update: bool,
         source: List[str], labels: List[str], namespace: Optional[str], watch: str,
         include_ir: bool, include_aconf: bool,
         diff_path: Optional[str]=None, kat_name: Optional[str]=None) -> None:
    loglevel = logging.DEBUG if debug else logging.INFO

    logging.basicConfig(
        level=loglevel,
        format="%(asctime)s mockery %(levelname)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )

    logger = logging.getLogger('mockery')

    logger.debug(f"reading from {k8s_yaml_paths}")

    if not source:
        source = [
            "Host", "service", "ingresses",
            "AuthService", "LogService", "Mapping", "Module", "RateLimitService",
            "TCPMapping", "TLSContext", "TracingService",
            "ConsulResolver", "KubernetesEndpointResolver", "KubernetesServiceResolver"
        ]

    if namespace:
        os.environ['AMBASSADOR_NAMESPACE'] = namespace

    # Make labels a list, instead of a tuple.
    labels = list(labels)
    labels_to_force = { l: True for l in labels or [] }

    if kat_name:
        logger.debug(f"KAT name {kat_name}")

        # First set up some labels to force.

        labels_to_force["scope=AmbassadorTest"] = True
        labels_to_force[f"service={kat_name}"] = True

        kat_amb_id_label = f"kat-ambassador-id={kat_name}"

        if kat_amb_id_label not in labels_to_force:
            labels_to_force[kat_amb_id_label] = True
            labels.append(kat_amb_id_label)

        os.environ['AMBASSADOR_ID'] = kat_name

        # Forcibly override the cached ambassador_id.
        Config.ambassador_id = kat_name

    logger.debug(f"namespace {namespace or '*'}")
    logger.debug(f"labels to watch {', '.join(labels)}")
    logger.debug(f"labels to force {', '.join(sorted(labels_to_force.keys()))}")
    logger.debug(f"watch hook {watch}")
    logger.debug(f"sources {', '.join(source)}")

    for key in sorted(os.environ.keys()):
        if key.startswith('AMBASSADOR'):
            logger.debug(f"${key}={os.environ[key]}")

    if force_pod_labels:
        try:
            os.makedirs("/tmp/ambassador-pod-info")
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        with open("/tmp/ambassador-pod-info/labels", "w", encoding="utf-8") as outfile:
            for l in labels_to_force:
                outfile.write(l)
                outfile.write("\n")

    # Pull in the YAML.
    input_yaml = ''.join([ open(x, "r").read() for x in k8s_yaml_paths ])
    manifest = parse_yaml(input_yaml)

    w = Mockery(logger, debug, source, ",".join(labels), namespace, watch)

    iteration = 0

    while True:
        iteration += 1

        if iteration > 10:
            print(f"!!!! Not stable after 10 iterations, failing")
            logger.error("Not stable after 10 iterations, failing")
            sys.exit(1)

        logger.info(f"======== START ITERATION {iteration}")

        w.load(manifest)

        logger.info(f"WATT_K8S: {w.snapshot}")

        hook_ok, any_changes = w.run_hook()

        if not hook_ok:
            raise Exception("hook failed")

        if any_changes:
            logger.info(f"======== END ITERATION {iteration}: watches changed!")
        else:
            logger.info(f"======== END ITERATION {iteration}: stable!")
            break

    # Once here, we should be good to go.
    try:
        os.makedirs("/tmp/ambassador/snapshots")
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise

    scc = MockSecretHandler(logger, "mockery", "/tmp/ambassador/snapshots", f"v{iteration}")

    aconf = Config()

    logger.debug(f"Config.ambassador_id {Config.ambassador_id}")
    logger.debug(f"Config.ambassador_namespace {Config.ambassador_namespace}")

    logger.info(f"STABLE WATT_K8S: {w.snapshot}")

    fetcher = ResourceFetcher(logger, aconf)
    fetcher.parse_watt(w.snapshot)
    aconf.load_all(fetcher.sorted())

    open("/tmp/ambassador/snapshots/aconf.json", "w", encoding="utf-8").write(aconf.as_json())

    ir = IR(aconf, secret_handler=scc)

    open("/tmp/ambassador/snapshots/ir.json", "w", encoding="utf-8").write(ir.as_json())

    econf = EnvoyConfig.generate(ir, "V2")
    bootstrap_config, ads_config, clustermap = econf.split_config()

    ads_config.pop('@type', None)
    with open("/tmp/ambassador/snapshots/econf.json", "w", encoding="utf-8") as outfile:
        outfile.write(dump_json(ads_config, pretty=True))

    with open("/tmp/ambassador/snapshots/bootstrap.json", "w", encoding="utf-8") as outfile:
        outfile.write(dump_json(bootstrap_config, pretty=True))

    diag = Diagnostics(ir, econf)

    with open("/tmp/ambassador/snapshots/diag.json", "w", encoding="utf-8") as outfile:
        outfile.write(dump_json(diag.as_dict(), pretty=True))

    if diff_path:
        diffs = False

        pairs_to_check = [
            (os.path.join(diff_path, 'snapshots', 'econf.json'), '/tmp/ambassador/snapshots/econf.json'),
            (os.path.join(diff_path, 'bootstrap-ads.json'), '/tmp/ambassador/snapshots/bootstrap.json')
        ]

        if include_ir:
            pairs_to_check.append(
                ( os.path.join(diff_path, 'snapshots', 'ir.json'), '/tmp/ambassador/snapshots/ir.json' )
            )

        if include_aconf:
            pairs_to_check.append(
                ( os.path.join(diff_path, 'snapshots', 'aconf.json'), '/tmp/ambassador/snapshots/aconf.json' )
            )

        for gold_path, check_path in pairs_to_check:
            if update:
                logger.info(f"mv {check_path} {gold_path}")
                shutil.move(check_path, gold_path)
            elif not filecmp.cmp(gold_path, check_path):
                diffs = True

                gold_lines = open(gold_path, "r", encoding="utf-8").readlines()
                check_lines = open(check_path, "r", encoding="utf-8").readlines()

                for line in difflib.unified_diff(gold_lines, check_lines, fromfile=gold_path, tofile=check_path):
                    sys.stdout.write(line)

        if diffs:
            sys.exit(1)

if __name__ == '__main__':
    main()


text:
import * as p from "core/properties"
import {input, textarea, select, option, Keys} from "core/dom"
import {extend} from "core/util/object"

import {DOMView} from "core/dom_view"
import {Model} from "../../../model"
import {DTINDEX_NAME, Item} from "./data_table"

export abstract class CellEditorView extends DOMView {
  model: CellEditor

  defaultValue: any

  get emptyValue(): any {
    return null
  }

  inputEl: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement

  protected args: any

  protected abstract _createInput(): HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement

  constructor(options: any) {
    super(extend({model: options.column.model}, options))
  }

  initialize(options: any): void {
    super.initialize(options)
    this.inputEl = this._createInput()
    this.defaultValue = null
    this.args = options
    this.render()
  }

  css_classes(): string[] {
    return super.css_classes().concat("bk-cell-editor")
  }

  render(): void {
    super.render()
    this.args.container.appendChild(this.el)
    this.el.appendChild(this.inputEl)
    this.renderEditor()
    this.disableNavigation()
  }

  renderEditor(): void {}

  disableNavigation(): void {
    this.inputEl.addEventListener("keydown", (event: KeyboardEvent) => {
      switch (event.keyCode) {
        case Keys.Left:
        case Keys.Right:
        case Keys.Up:
        case Keys.Down:
        case Keys.PageUp:
        case Keys.PageDown:
          event.stopImmediatePropagation()
      }
    })
  }

  destroy(): void {
    this.remove()
  }

  focus(): void {
    this.inputEl.focus()
  }

  show(): void {}

  hide(): void {}

  position(): any {}

  getValue(): any {
    return this.inputEl.value
  }

  setValue(val: any): void {
    this.inputEl.value = val
  }

  serializeValue(): any {
    return this.getValue()
  }

  isValueChanged(): boolean {
    return !(this.getValue() == "" && this.defaultValue == null) && this.getValue() !== this.defaultValue
  }

  applyValue(item: Item, state: any): void {
    this.args.grid.getData().setField(item[DTINDEX_NAME], this.args.column.field, state)
  }

  loadValue(item: Item): void {
    const value = item[this.args.column.field]
    this.defaultValue = value != null ? value : this.emptyValue
    this.setValue(this.defaultValue)
  }

  validateValue(value: any): any {
    if (this.args.column.validator) {
      const result = this.args.column.validator(value)
      if (!result.valid) {
        return result
      }
    }

    return { valid: true, msg: null }
  }

  validate(): any {
    return this.validateValue(this.getValue())
  }
}

export abstract class CellEditor extends Model {
  static initClass(): void {
    this.prototype.type = "CellEditor"
  }
}
CellEditor.initClass()

export class StringEditorView extends CellEditorView {
  model: StringEditor

  inputEl: HTMLInputElement

  get emptyValue(): string {
    return ""
  }

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }

  renderEditor(): void {
    //completions = @model.completions
    //if completions.length != 0
    //  @inputEl.classList.add("bk-cell-editor-completion")
    //  $(@inputEl).autocomplete({source: completions})
    //  $(@inputEl).autocomplete("widget")
    this.inputEl.focus()
    this.inputEl.select()
  }

  loadValue(item: Item): void {
    super.loadValue(item)
    this.inputEl.defaultValue = this.defaultValue
    this.inputEl.select()
  }
}

export class StringEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'StringEditor'
    this.prototype.default_view = StringEditorView
    this.define({
      completions: [ p.Array, [] ],
    })
  }
}
StringEditor.initClass()

export class TextEditorView extends CellEditorView {
  model: TextEditor

  inputEl: HTMLTextAreaElement

  protected _createInput(): HTMLTextAreaElement {
    return textarea()
  }
}

export class TextEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'TextEditor'
    this.prototype.default_view = TextEditorView
  }
}
TextEditor.initClass()

export class SelectEditorView extends CellEditorView {
  model: SelectEditor

  inputEl: HTMLSelectElement

  protected _createInput(): HTMLSelectElement {
    return select()
  }

  renderEditor(): void {
    for (const opt of this.model.options) {
      this.inputEl.appendChild(option({value: opt}, opt))
    }
    this.focus()
  }
}

export class SelectEditor extends CellEditor {
  options: string[]

  static initClass(): void {
    this.prototype.type = 'SelectEditor'
    this.prototype.default_view = SelectEditorView
    this.define({
      options: [ p.Array, [] ],
    })
  }
}
SelectEditor.initClass()

export class PercentEditorView extends CellEditorView {
  model: PercentEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }
}

export class PercentEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'PercentEditor'
    this.prototype.default_view = PercentEditorView
  }
}
PercentEditor.initClass()

export class CheckboxEditorView extends CellEditorView {
  model: CheckboxEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "checkbox", value: "true"})
  }

  renderEditor(): void {
    this.focus()
  }

  loadValue(item: Item): void {
    this.defaultValue = !!item[this.args.column.field]
    this.inputEl.checked = this.defaultValue
  }

  serializeValue(): any {
    return this.inputEl.checked
  }
}

export class CheckboxEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'CheckboxEditor'
    this.prototype.default_view = CheckboxEditorView
  }
}
CheckboxEditor.initClass()

export class IntEditorView extends CellEditorView {
  model: IntEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }

  renderEditor(): void {
    //$(@inputEl).spinner({step: @model.step})
    this.inputEl.focus()
    this.inputEl.select()
  }

  remove(): void {
    //$(@inputEl).spinner("destroy")
    super.remove()
  }

  serializeValue(): any {
    return parseInt(this.getValue(), 10) || 0
  }

  loadValue(item: Item): void {
    super.loadValue(item)
    this.inputEl.defaultValue = this.defaultValue
    this.inputEl.select()
  }

  validateValue(value: any): any {
    if (isNaN(value))
      return { valid: false, msg: "Please enter a valid integer" }
    else
      return super.validateValue(value)
  }
}

export class IntEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'IntEditor'
    this.prototype.default_view = IntEditorView
    this.define({
      step: [ p.Number, 1 ],
    })
  }
}
IntEditor.initClass()

export class NumberEditorView extends CellEditorView {
  model: NumberEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }

  renderEditor(): void {
    //$(@inputEl).spinner({step: @model.step})
    this.inputEl.focus()
    this.inputEl.select()
  }

  remove(): void {
    //$(@inputEl).spinner("destroy")
    super.remove()
  }

  serializeValue(): any {
    return parseFloat(this.getValue()) || 0.0
  }

  loadValue(item: Item): void {
    super.loadValue(item)
    this.inputEl.defaultValue = this.defaultValue
    this.inputEl.select()
  }

  validateValue(value: any): any {
    if (isNaN(value))
      return { valid: false, msg: "Please enter a valid number" }
    else
      return super.validateValue(value)
  }
}

export class NumberEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'NumberEditor'
    this.prototype.default_view = NumberEditorView
    this.define({
      step: [ p.Number, 0.01 ],
    })
  }
}
NumberEditor.initClass()

export class TimeEditorView extends CellEditorView {
  model: TimeEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }
}

export class TimeEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'TimeEditor'
    this.prototype.default_view = TimeEditorView
  }
}
TimeEditor.initClass()

export class DateEditorView extends CellEditorView {
  model: DateEditor

  inputEl: HTMLInputElement

  protected _createInput(): HTMLInputElement {
    return input({type: "text"})
  }

  get emptyValue(): Date {
    return new Date()
  }

  renderEditor(): void {
    //this.calendarOpen = false

    //@$datepicker = $(@inputEl).datepicker({
    //  showOn: "button"
    //  buttonImageOnly: true
    //  beforeShow: () => @calendarOpen = true
    //  onClose: () => @calendarOpen = false
    //})
    //@$datepicker.siblings(".ui-datepicker-trigger").css("vertical-align": "middle")
    //@$datepicker.width(@$datepicker.width() - (14 + 2*4 + 4)) # img width + margins + edge distance
    this.inputEl.focus()
    this.inputEl.select()
  }

  destroy(): void {
    //$.datepicker.dpDiv.stop(true, true)
    //@$datepicker.datepicker("hide")
    //@$datepicker.datepicker("destroy")
    super.destroy()
  }

  show(): void {
    //if @calendarOpen
    //  $.datepicker.dpDiv.stop(true, true).show()
    super.show()
  }

  hide(): void {
    //if @calendarOpen
    //  $.datepicker.dpDiv.stop(true, true).hide()
    super.hide()
  }

  position(/*_position*/): any {
    //if @calendarOpen
    //  $.datepicker.dpDiv.css(top: position.top + 30, left: position.left)
    return super.position()
  }

  getValue(): any {}
    //return @$datepicker.datepicker("getDate").getTime()

  setValue(_val: any): void {}
}
    //@$datepicker.datepicker("setDate", new Date(val))

export class DateEditor extends CellEditor {
  static initClass(): void {
    this.prototype.type = 'DateEditor'
    this.prototype.default_view = DateEditorView
  }
}
DateEditor.initClass()


text:
using System;
using log4net;
using log4net.Core;

namespace CrossCutting.Diagnostics
{
    public class Log4NetLogger : ILogger
    {
        private readonly ILog log4NetLog;

        public Log4NetLogger(ILog log4NetLog)
        {
            this.log4NetLog = log4NetLog;
        }

        public void Log(LogLevel level, string message)
        {
            log4NetLog.Logger.Log(new LoggingEvent(new LoggingEventData
            {
                LoggerName = log4NetLog.Logger.Name,
                Level = MapLogLevel(level),
                Message = message,
                TimeStamp = DateTime.UtcNow
            }));
        }

        public void Log(LogLevel level, Exception exception, string message)
        {
            log4NetLog.Logger.Log(new LoggingEvent(null, null, log4NetLog.Logger.Name, MapLogLevel(level), message, exception));
        }

        public bool LevelEnabled(LogLevel level)
        {
            return log4NetLog.Logger.IsEnabledFor(MapLogLevel(level));
        }

        private Level MapLogLevel(LogLevel logLevel)
        {
            switch (logLevel)
            {
                case LogLevel.Debug:
                    return Level.Debug;
                case LogLevel.Info:
                    return Level.Info;
                case LogLevel.Warn:
                    return Level.Warn;
                case LogLevel.Error:
                    return Level.Error;
                case LogLevel.Fatal:
                    return Level.Fatal;
                default:
                    return Level.Off;
            }
        }
    }
}


text:
Logger__callable_main() {
    Logger__callable_help
}

##################################################
# Displays relavant information on how to use
# this module
##################################################
Logger__callable_help() {
    more "$Ash__ACTIVE_MODULE_DIRECTORY/HELP.txt"
}

##################################################
# Clears the debug log file of all contents
##################################################
Logger__callable_clear() {
    > $(Logger_get_debug_file)
}

##################################################
# Watches the debug log file for any changes,
# and outputs them to stdout
##################################################
Logger__callable_watch() {
    tail -f $(Logger_get_debug_file)
}


text:
;

+
{ re:
    { id: "todos"
    , of: "わかった"
    , is: "ToDos for わかった, a Japanese language game"
    , by: "Michael Lee, iskitz.net, @iskitz"
    , at: "2016.11.12-08...01.23-07"
    , in: "san-jose.california.usa.earth"
    },

  todos:
    [ "simplify yes + no interaction"
    , "enable pairing hiragana, katakana, + romaji"
    , "add learn mode that only shows right answers"
    , "auto speed up or down per user's success speed"
    , "manage resources (css, audio, storage, etc) from ions"

    , { "save skill progress":
          [ "temporarily using SessionStorage or Cookies"
          , "persistently using LocalStorage, IndexedDB, or Server"
          , "user id + authentication can be a specific gesture over some period of time"
          ]
      }

    , "add romaji typing practice"
    , "add vocabulary, group by user's role(s) + interest(s)"
    , "add image: word pairing"
    , "add pronounciation audio: gendered voices"
    , "add statement confirmation"
    , "add image(s): statement pairing"

    , { perf:
          [ "test after each feature change"
          , "use http://webpagetest.org/"

          , { "http://tinyurl.com/wakatta-2016-03-10 http://tinyurl.com/wakatta-2016-03-10-noanimation":
                [ "1000 ms between 1st request + 1st render + animation ? css animation, js execution"
                , " 750 ms between 1st request + 1st render - animation ? looks like favicon"
                , " 536 ms idle time                                    ? why no activity"
                , " 706 ms between 1st render  + favicon available      ? why no main thread activity"
                , " 590 ms between 1st request + favicon requested      ? store as data-url to minimize"
                ]
            }
          ]
      }

    , { "proficiency progress":
          [ "per character"
          , 'per gojūon ("a,i,u,e,o") group'
          , "per alphabet"
          , "per character, group, + alphabet speed"
          , "using maturing avatar"
          ]
      }

    , { "proficiency coach":
          [ { "as success plateaus":
               [ "increase speed"
               , "increase complexity"
               , "suggest other skills"
               , "interact with others"
               ]
            }
          , "combine letters; i.e. ひろこ : ヒロコ"
          , "improve speed via auto-scroll and fade"
          ]
      }

    , { "add character writing practice":
          [ "look for existing web solutions"
          , "? use character svgs and canvas input"
          ]
      }

    , { "add speech practice":
          [ "look for existing web solutions"
          , "? use webrtc/microphone api and audio analysis"
          ]
      }
    ], //+.todos

  done:
    [ "rename kana.game folder to wakatta"
    , "Swipe left slows display, right quickens it"
    , "Manages css behavior from +view"
    , "Made +view, +game, + +kana.romaji own scripts"
    , "Gets alphabets via +kana not +game.make()"
    , "Moved todos to +todos + added initial +ionify.get + renamed +kana..core to +kana.gojuon"
    , "Renamed in code as わかった, Wakatta, I got it + Added, grouped, and prioritized todos + Renamed +ions to +ionify.hub + Added sokuon kana."
    , "Added re.view.guess() + preempted potential scoring bug in +view.guess() + tidied code."
    , "Yes & No input changes character colors instead of entire background, animation pauses during input, 1st answer wrong display bug fixed, + +game.play() scope loss preempted."
    , "Added fade animation + score display."
    , "Refined algorithm for matching letter pairs, added re.game.play()"
    , "Better mix of right & wrong answers, slower game speed, + beginning support for external scripts."
    , "Made dakuten, handakuten, and yōon characters named member sets of the hiragana, katana, and romaji character sets."
    + " Did this to make code using these character sets easier to understand."
    + " Previously, the dakuten, handakuten, and yōon character sets would need"
    + " to be accessed via index offsets of the single hiragana, katakana, and"
    + " romaji array lists."
    , "Added hiragana and katana yōon; e.g. ja:じゃ + adjusted visual alignment of all 3 character sets."
    , "Added romaji dakuten + handakuten + todos for yōon + child fields + Updated re.by, re.at and re.in formats and content."
    , "Added accented kana characters like be:べ and pe:ぺ"
    , "Made kana.js to map Japanese Kana to each other and romaji."
    , "Render brush-like Japanese characters on iOS + OS X, and set app's name via meta tags."
    , "Renamed game + added fullscreen support for add-to-homescreen on mobile"
    , "Enabled touch support for mobile"
    ]
} //+わかった.todos

;


text:
Nehan.TagAttrs = (function(){
  /**
     @memberof Nehan
     @class TagAttrs
     @classdesc tag attribute set wrapper
     @constructor
     @param src {String}
  */
  function TagAttrs(src){
    var attrs_raw = src? Nehan.TagAttrParser.parse(src) : {};
    this.classes = this._parseClasses(attrs_raw);
    this.attrs = this._parseAttrs(attrs_raw);
    this.dataset = this._parseDataset(attrs_raw);
  }

  var __data_name_of = function(name){
    return Nehan.Utils.camelize(name.slice(5));
  };

  /**
   @memberof Nehan.TagAttrs
   @param name {String} - attribute name
   @return {boolean}
   */
  TagAttrs.prototype.hasAttr = function(name){
    return (typeof this.attrs.name !== "undefined");
  };
  /**
   @memberof Nehan.TagAttrs
   @param klass {String} - css class name
   @return {boolean}
   */
  TagAttrs.prototype.hasClass = function(klass){
    return Nehan.List.exists(this.classes, Nehan.Closure.eq(klass));
  };
  /**
   @memberof Nehan.TagAttrs
   @param klass {String} - css class name
   @return {Array.<String>} current css classes
   */
  TagAttrs.prototype.addClass = function(klass){
    if(!this.hasClass(klass)){
      this.classes.push(klass);
      this.setAttr("class", [this.getAttr("class"), klass].join(" "));
    }
    return this.classes;
  };
  /**
   @memberof Nehan.TagAttrs
   @param klass {String} - css class name(prefiex by "nehan-")
   */
  TagAttrs.prototype.removeClass = function(klass){
    this.classes = Nehan.List.filter(this.classes, function(cls){
      return cls != klass;
    });
    this.setAttr("class", this.classes.join(" "));
    return this.classes;
  };
  /**
   @memberof Nehan.TagAttrs
   @param name {String}
   @param def_value {default_value}
   @return {attribute_value}
   */
  TagAttrs.prototype.getAttr = function(name, def_value){
    def_value = (typeof def_value === "undefined")? null : def_value;
    return (typeof this.attrs[name] === "undefined")? def_value : this.attrs[name];
  };
  /**
   get dataset value

   @memberof Nehan.TagAttrs
   @param name {String}
   @param def_value {default_value}
   @return {dataset_value}
   */
  TagAttrs.prototype.getData = function(name, def_value){
    def_value = (typeof def_value === "undefined")? null : def_value;
    return (typeof this.dataset[name] === "undefined")? def_value : this.dataset[name];
  };
  /**
   get cache key

   @memberof Nehan.TagAttrs
   @param name {String}
   @return {string}
   */
  TagAttrs.prototype.getKey = function(){
    var props = Object.keys(this.attrs).sort();
    return Nehan.List.map(props, function(prop){
      return prop + "=" + this.attrs[prop];
    }.bind(this)).join("&");
  };
  /**
   @memberof Nehan.TagAttrs
   @param name {String}
   @param value {attribute_value}
   */
  TagAttrs.prototype.setAttr = function(name, value){
    if(name.indexOf("data-") === 0){
      this.setData(__data_name_of(name), value);
    } else {
      this.attrs[name] = value;
    }
  };
  /**
   set dataset value

   @memberof Nehan.TagAttrs
   @param name {String}
   @param value {dataset_value}
   */
  TagAttrs.prototype.setData = function(name, value){
    this.dataset[name] = value;
  };

  // <p class='hi hey'>
  // => ["nehan-hi", "nehan-hey"]
  TagAttrs.prototype._parseClasses = function(attrs_raw){
    var class_name = attrs_raw["class"] || "";
    class_name = Nehan.Utils.trim(class_name.replace(/\s+/g, " "));
    var classes = (class_name === "")? [] : class_name.split(/\s+/);

    // replace 'nehan-' prefix for backword compatibility(version <= 5.1.0).
    return Nehan.List.map(classes, function(klass){
      return (klass.indexOf("nehan-") === 0)? klass.replace("nehan-", "") : klass;
    });
  };

  TagAttrs.prototype._parseAttrs = function(attrs_raw){
    var attrs = {};
    Nehan.Obj.iter(attrs_raw, function(name, value){
      if(name.indexOf("data-") < 0){
	attrs[name] = value;
      }
    });
    return attrs;
  };

  TagAttrs.prototype._parseDatasetValue = function(value){
    switch(value){
    case "true": return true;
    case "false": return false;
    default: return isNaN(value)? value : Number(value);
    }
  };

  TagAttrs.prototype._parseDataset = function(attrs_raw){
    var dataset = {};
    for(var name in attrs_raw){
      if(name.indexOf("data-") === 0){
	dataset[__data_name_of(name)] = this._parseDatasetValue(attrs_raw[name]);
      }
    }
    return dataset;
  };

  return TagAttrs;
})();


text:
package domain;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "books")
public class Book {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "book_id")
	private Long id;

	@Column(name = "title", length = 50)
	private String title;

	@ManyToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "author_id", referencedColumnName = "author_id")
	private Author author;

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "books_categories",
            joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "book_id"),
            inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "category_id"))
	private Set<Category> categories;

	@Basic
	private BigDecimal price;

	@Basic
	private Integer copies;

	@Column(name = "description", length = 255, nullable = true)
	private String description;

	@Column(name = "release_date", nullable = true)
	private Date releaseDate;

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "related_books",
    		joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "book_id"),
    		inverseJoinColumns = @JoinColumn(name = "related_book_id", referencedColumnName = "book_id"))
	private Set<Book> relatedBooks;

	@Column(name = "edition_type")
	private Integer editionType;

	public Book() {  }

	public Book(String title, Author author, BigDecimal price, Integer copies,
			String description, Date releaseDate) {
		super();
		this.title = title;
		this.author = author;
		this.categories = new HashSet<Category>();
		this.price = price;
		this.copies = copies;
		this.description = description;
		this.releaseDate = releaseDate;
		this.relatedBooks = new HashSet<Book>();
	}

	public void addCategory(Category category) {
		this.categories.add(category);
	}

	public void addRelatedBook(Book book) {
		if (this.relatedBooks == null) {
			this.relatedBooks = new HashSet<>();
		}
		this.relatedBooks.add(book);
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	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 Set<Category> getCategories() {
		return categories;
	}

	public void setCategories(Set<Category> categories) {
		this.categories = categories;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public Integer getCopies() {
		return copies;
	}

	public void setCopies(Integer copies) {
		this.copies = copies;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Date getReleaseDate() {
		return releaseDate;
	}

	public void setReleaseDate(Date releaseDate) {
		this.releaseDate = releaseDate;
	}

	public Set<Book> getRelatedBooks() {
		return relatedBooks;
	}

	public void setRelatedBooks(Set<Book> relatedBooks) {
		this.relatedBooks = relatedBooks;
	}

	public Integer getEditionType() {
		return editionType;
	}

	public void setEditionType(Integer editionType) {
		this.editionType = editionType;
	}

}