text:
const expect = require('expect');
const queryform = require('../queryform');

const {featureCollection} = require('../../test-resources/featureCollectionZone.js');

describe('Test the queryform reducer', () => {

    it('returns the initial state on unrecognized action', () => {

        const initialState = {
            filterFields: [
                {
                    rowId: 0,
                    attribute: "",
                    operator: null,
                    value: null,
                    exception: null
                }
            ],
            attributes: [
                {
                    id: "Province",
                    type: "list",
                    values: [
                        "province1",
                        "province2",
                        "province3",
                        "province4",
                        "province5"
                    ]
                }
            ]
        };

        let state = queryform(initialState, {type: 'UNKNOWN'});
        expect(state).toBe(initialState);
    });

    it('Add a new filter field', () => {
        let testAction = {
            type: 'ADD_FILTER_FIELD'
        };

        let initialState = {
            filterFields: [{
                rowId: 100,
                attribute: "attributeName",
                operator: "=",
                value: "attributeValue",
                exception: null
            }]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(2);

        expect(state.filterFields[0].rowId).toBe(100);
        expect(state.filterFields[0].attribute).toBe("attributeName");
        expect(state.filterFields[0].operator).toBe("=");
        expect(state.filterFields[0].value).toBe("attributeValue");
        expect(state.filterFields[0].exception).toBe(null);

        expect(state.filterFields[1].rowId).toNotEqual(state.filterFields[0].rowId);
        expect(state.filterFields[1].attribute).toBe(null);
        expect(state.filterFields[1].operator).toBe("=");
        expect(state.filterFields[1].value).toBe(null);
        expect(state.filterFields[1].exception).toBe(null);
    });

    it('Remove an existing filter field', () => {
        let testAction = {
            type: 'REMOVE_FILTER_FIELD',
            rowId: 100
        };

        let initialState = {
            filterFields: [{
                rowId: 100,
                attribute: "attributeName",
                operator: "=",
                value: "attributeValue",
                exception: null
            }, {
                rowId: 200,
                attribute: "attributeName2",
                operator: ">",
                value: "attributeValue2",
                exception: null
            }]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(1);

        expect(state.filterFields[0].rowId).toBe(200);
        expect(state.filterFields[0].attribute).toBe("attributeName2");
        expect(state.filterFields[0].operator).toBe(">");
        expect(state.filterFields[0].value).toBe("attributeValue2");
        expect(state.filterFields[0].exception).toBe(null);
    });

    it('Update an existing filter field', () => {
        let testAction = {
            type: 'UPDATE_FILTER_FIELD',
            rowId: 100,
            fieldName: "attribute",
            fieldValue: "attributeName1"
        };

        let initialState = {
            filterFields: [{
                rowId: 100,
                attribute: "attributeName",
                operator: "=",
                value: "attributeValue",
                exception: null
            }, {
                rowId: 200,
                attribute: "attributeName2",
                operator: ">",
                value: "attributeValue2",
                exception: null
            }]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(2);
        expect(state.filterFields[0].attribute).toBe("attributeName1");

        testAction = {
            type: 'UPDATE_FILTER_FIELD',
            rowId: 100,
            fieldName: "operator",
            fieldValue: "<"
        };

        state = queryform(state, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(2);
        expect(state.filterFields[0].attribute).toBe("attributeName1");
        expect(state.filterFields[0].operator).toBe("<");

        testAction = {
            type: 'UPDATE_FILTER_FIELD',
            rowId: 100,
            fieldName: "value",
            fieldValue: "attributeValue1"
        };

        state = queryform(state, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(2);
        expect(state.filterFields[0].attribute).toBe("attributeName1");
        expect(state.filterFields[0].operator).toBe("<");
        expect(state.filterFields[0].value).toBe("attributeValue1");
    });

    it('Update the exception for a filter field', () => {
        let testAction = {
            type: 'UPDATE_EXCEPTION_FIELD',
            rowId: 100,
            fieldName: "attribute",
            fieldValue: "attributeName1",
            exceptionMessage: "exception message"
        };

        let initialState = {
            filterFields: [{
                rowId: 100,
                attribute: "attributeName",
                operator: "=",
                value: "attributeValue",
                exception: null
            }, {
                rowId: 200,
                attribute: "attributeName2",
                operator: ">",
                value: "attributeValue2",
                exception: null
            }]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.filterFields.length).toBe(2);
        expect(state.filterFields[0].exception).toBe("exception message");
    });

    it('Add a new group field', () => {
        let testAction = {
            type: 'ADD_GROUP_FIELD',
            groupId: 1,
            index: 0
        };

        let initialState = {
            groupFields: [
                {
                    id: 1,
                    logic: "OR",
                    index: 0
                }
            ]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.groupFields.length).toBe(2);
        expect(state.groupFields[1].index).toBe(1);
        expect(state.groupFields[1].groupId).toBe(1);
        expect(state.groupFields[1].logic).toBe("OR");
    });

    it('Update a logic combo box', () => {
        let testAction = {
            type: 'UPDATE_LOGIC_COMBO',
            groupId: 1,
            logic: "AND"
        };

        let initialState = {
            groupFields: [
                {
                    id: 1,
                    logic: "OR",
                    index: 0
                }
            ]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.groupFields.length).toBe(1);
        expect(state.groupFields[0].index).toBe(0);
        expect(state.groupFields[0].id).toBe(1);
        expect(state.groupFields[0].logic).toBe("AND");
    });

    it('Remove a group field', () => {
        let testAction = {
            type: 'REMOVE_GROUP_FIELD',
            groupId: 2
        };

        let initialState = {
            groupFields: [
                {
                    id: 1,
                    logic: "OR",
                    index: 0
                }, {
                    id: 2,
                    logic: "AND",
                    index: 1
                }
            ],
            filterFields: [{
                rowId: 100,
                groupId: 2,
                attribute: "attributeName",
                operator: "=",
                value: "attributeValue",
                exception: null
            }, {
                rowId: 200,
                groupId: 2,
                attribute: "attributeName2",
                operator: ">",
                value: "attributeValue2",
                exception: null
            }]
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.groupFields.length).toBe(1);
        expect(state.groupFields[0].index).toBe(0);
        expect(state.groupFields[0].id).toBe(1);
        expect(state.groupFields[0].logic).toBe("OR");

        expect(state.filterFields.length).toBe(0);
    });

    it('Expand the Attribute Filter Panel', () => {
        let testAction = {
            type: 'EXPAND_ATTRIBUTE_PANEL',
            expand: false
        };

        const initialState = {
            attributePanelExpanded: true,
            spatialPanelExpanded: true
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.attributePanelExpanded).toEqual(false);
    });

    it('Expand the Spatial Filter Panel', () => {
        let testAction = {
            type: 'EXPAND_SPATIAL_PANEL',
            expand: false
        };

        const initialState = {
            attributePanelExpanded: true,
            spatialPanelExpanded: true
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.spatialPanelExpanded).toEqual(false);
    });

    it('Select Spatial Method', () => {
        let testAction = {
            type: "SELECT_SPATIAL_METHOD",
            fieldName: "method",
            method: "BBOX"
        };

        const initialState = {
            spatialField: {
                method: null,
                attribute: "the_geom",
                operation: "INTERSECTS",
                geometry: null
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.spatialField.method).toEqual("BBOX");
    });

    it('Select Spatial Operation', () => {
        let testAction = {
            type: "SELECT_SPATIAL_OPERATION",
            fieldName: "operation",
            operation: "DWITHIN"
        };

        const initialState = {
            spatialField: {
                method: null,
                attribute: "the_geom",
                operation: "INTERSECTS",
                geometry: null
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.spatialField.operation).toEqual("DWITHIN");
    });

    it('Remove Spatial Selection', () => {
        let testAction = {
            type: "REMOVE_SPATIAL_SELECT"
        };

        const initialState = {
            spatialField: {
                method: "BBOX",
                attribute: "the_geom",
                operation: "DWITHIN",
                geometry: '{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-635956.0753326667,5466776.262955805],[-635956.0753326667,4723196.8517976105],[-29351.81886150781,4723196.8517976105],[-29351.81886150781,5466776.262955805],[-635956.0753326667,5466776.262955805]]]},"properties":null}'
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();

        expect(state.spatialField.method).toEqual(null);
        expect(state.spatialField.attribute).toEqual("the_geom");
        expect(state.spatialField.operation).toEqual("INTERSECTS");
        expect(state.spatialField.geometry).toEqual(null);
    });

    it('Show Spatial Details Panel', () => {
        let testAction = {
            type: "SHOW_SPATIAL_DETAILS",
            show: true
        };

        const initialState = {
            showDetailsPanel: false
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.showDetailsPanel).toEqual(true);
    });

    it('Query Form Reset', () => {
        let testAction = {
            type: "QUERY_FORM_RESET"
        };

        const initialState = {
            test: true
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.test).toEqual(true);
    });

    it('Show Generated Filter', () => {
        let testAction = {
            type: "SHOW_GENERATED_FILTER",
            data: "data"
        };

        const initialState = {
            showGeneratedFilter: "test"
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();

        expect(state.showGeneratedFilter).toEqual("data");
    });

    it('Zone Filter', () => {
        let testAction = {
            type: "ZONE_FILTER",
            data: {features: [{
                id: 1,
                name: "value1"
            }, {
                id: 2,
                name: "value2"
            }]},
            id: 1
        };

        const initialState = {
            spatialField: {
                method: "ZONE",
                attribute: "geom3857",
                operation: "INTERSECTS",
                geometry: null,
                zoneFields: [{
                    id: 1,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: [],
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute"
                }, {
                    id: 2,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: [],
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute",
                    disabled: true,
                    dependson: {
                        id: 1,
                        field: "att3",
                        value: null
                    }
                }]
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();
        expect(state.spatialField.zoneFields[0].values.length).toBe(2);

        expect(state.spatialField.zoneFields[0].open).toBe(true);
    });

    it('Zone Search', () => {
        let testAction = {
            type: "ZONE_SEARCH",
            active: true,
            id: 1
        };

        const initialState = {
            spatialField: {
                method: "ZONE",
                attribute: "geom3857",
                operation: "INTERSECTS",
                geometry: null,
                zoneFields: [{
                    id: 1,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: [],
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute"
                }, {
                    id: 2,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: [],
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute",
                    disabled: true,
                    dependson: {
                        id: 1,
                        field: "att3",
                        value: null
                    }
                }]
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();
        expect(state.spatialField.zoneFields[0].busy).toBe(true);
    });

    it('Zone Change', () => {
        let testAction = {
            type: "ZONE_CHANGE",
            id: 1,
            value: {
                value: ["Five"],
                feature: [
                    {
                        "type": "Feature",
                        "id": "zones.5",
                        "geometry": {
                            "type": "MultiPolygon",
                            "coordinates": [
                                [
                                    [
                                        [
                                            -112.52004032,
                                            43.54002689
                                        ],
                                        [
                                            -112.52008024,
                                            43.42515586
                                        ],
                                        [
                                            -112.2234772,
                                            43.42473004
                                        ],
                                        [
                                            -112.1032533,
                                            43.42498078
                                        ],
                                        [
                                            -112.52004032,
                                            43.54002689
                                        ]
                                    ]
                                ]
                            ]
                        },
                        "geometry_name": "the_geom",
                        "properties": {
                            "Shape_Leng": 732018.056416,
                            "Shape_Area": 2.44128352236E10,
                            "District_N": "5",
                            "SUM_Counti": 7,
                            "Orient": 0,
                            "OrientPg": 0,
                            "ITD_Dist_n": 5,
                            "DistNum": "Five",
                            "Area_sqmi": 9425.848
                        }
                    }
                ]
            }
        };

        const initialState = {
            spatialField: {
                method: "ZONE",
                attribute: "the_geom",
                operation: "INTERSECTS",
                geometry: null,
                zoneFields: [{
                    id: 1,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: featureCollection.features,
                    value: null,
                    multivalue: false,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute"
                }, {
                    id: 2,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: [],
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute",
                    disabled: true,
                    dependson: {
                        id: 1,
                        field: "att3",
                        value: null
                    }
                }]
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();

        expect(state.spatialField.zoneFields[0].value).toEqual("Five");
        expect(state.spatialField.zoneFields[0].geometryName).toEqual("the_geom");
    });

    it('Zone Reset', () => {
        let testAction = {
            type: "ZONES_RESET"
        };

        const initialState = {
            spatialField: {
                method: "ZONE",
                attribute: "the_geom",
                operation: "INTERSECTS",
                geometry: null,
                zoneFields: [{
                    id: 1,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: featureCollection.features,
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute"
                }]
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();
        expect(state.spatialField.zoneFields[0].values).toBe(null);
    });

    it('Simple Filter update', () => {
        let testAction = {
            type: "SIMPLE_FILTER_FIELD_UPDATE",
            id: 1,
            properties: {combo: true}
        };

        let state = queryform({simpleFilterFields: [{fieldId: 1, combo: false}, {fieldId: 2, combo: true}]}, testAction);
        expect(state).toExist();
        expect(state.simpleFilterFields).toExist();
        expect(state.simpleFilterFields[0].combo).toBe(true);
    });

    it('Add Simple Filter', () => {
        let testAction = {
            type: "ADD_SIMPLE_FILTER_FIELD",
            properties: {fieldId: 1, combo: true}
        };

        let state = queryform( {simpleFilterFields: []}, testAction);
        expect(state).toExist();
        expect(state.simpleFilterFields).toExist();
        expect(state.simpleFilterFields[0].combo).toBe(true);
        expect(state.simpleFilterFields[0].fieldId).toBe(1);
    });

    it('Remove Simple Filter', () => {
        let testAction = {
            type: "REMOVE_SIMPLE_FILTER_FIELD",
            id: 1
        };

        let state = queryform({simpleFilterFields: [{fieldId: 1, combo: false}]}, testAction);
        expect(state).toExist();
        expect(state.simpleFilterFields).toExist();
        expect(state.simpleFilterFields.length).toBe(0);
    });

    it('Remove All Simple Filter', () => {
        let testAction = {
            type: "REMOVE_ALL_SIMPLE_FILTER_FIELDS"
        };

        let state = queryform({simpleFilterFields: [{fieldId: 1, combo: false}]}, testAction);
        expect(state).toExist();
        expect(state.simpleFilterFields).toExist();
        expect(state.simpleFilterFields.length).toBe(0);
    });

    /*it('Open Zones Menu', () => {
        let testAction = {
            type: "OPEN_MENU",
            active: true,
            id: 1
        };

        const initialState = {
            spatialField: {
                method: "ZONE",
                attribute: "the_geom",
                operation: "INTERSECTS",
                geometry: null,
                zoneFields: [{
                    id: 1,
                    url: "http://localhost:8080/",
                    typeName: "typeName1",
                    values: featureCollection.features,
                    value: null,
                    valueField: "properties.attr1",
                    textField: "properties.attr2",
                    searchText: "*",
                    searchMethod: "ilike",
                    searchAttribute: "att2",
                    label: "Attribute"
                }]
            }
        };

        let state = queryform(initialState, testAction);
        expect(state).toExist();
        expect(state.spatialField).toExist();
        expect(state.spatialField.zoneFields[0].open).toBe(true);
    });*/
});


text:
import { el, $, Component } from './react-utils';

import Transactions from './model/Transactions';

import { Chart } from './components/Chart';
import { Analysis } from './components/Analysis';
import { SelectFilters } from './components/SelectFilters';
import { TransactionList } from './components/TransactionList';
import { StatementUploadForm } from './components/StatementUploadForm';

export class Statements extends Component {
  constructor(props) {
    super(props);

    this.state = {
      transactions: new Transactions(),
      filteredTransactions: new Transactions()
    };
  }

  componentDidMount() {
    this.loadTransactions();
  }

  loadTransactions() {
    return Transactions
      .get()
      .then(transactions => {
        this.setState({
          transactions: transactions,
          filteredTransactions: transactions // TODO
        });
      })
  }

  applyFilter(filter) {
    this.setState({
      filteredTransactions: this.state.transactions.filter(filter)
    });
  }

  render() {
    return el('div', { className: 'container statements' },
      StatementUploadForm.create({
        onStatementsSubmit: this.loadTransactions.bind(this)
      }),
      SelectFilters.create({
        onFilter: this.applyFilter.bind(this)
      }),
      TransactionList.create({
        transactions: this.state.filteredTransactions
      }),
      Chart.create({
        transactions: this.state.filteredTransactions
      }),
      Analysis.create({
        transactions: this.state.filteredTransactions
      })
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
package templates

import (
	"fmt"
	html "html/template"
	"io"
	"os"
	"path/filepath"
	"strings"
	text "text/template"

	"bitbucket.org/j1436go/inflect"
)

type TemplateType int

const (
	HTMLTemplate = iota
	TextTemplate
)

// Templater is an interface for both text/template
// and html/template.
// Use type hinting to access template specific members.
type Templater interface {
	Execute(wr io.Writer, data interface{}) error
	ExecuteTemplate(wr io.Writer, name string, data interface{}) error
}

func ParseRecursive(root string, typ TemplateType, exts ...string) (Templater, error) {
	var paths []string

	filepath.Walk(root, func(
		path string,
		info os.FileInfo,
		err error) error {
		if strInSlice(filepath.Ext(path), exts) {
			paths = append(paths, path)
		}
		return nil
	})

	switch typ {
	case HTMLTemplate:
		return html.ParseFiles(paths...)
	case TextTemplate:
		return text.ParseFiles(paths...)
	}

	return nil, fmt.Errorf("Undefined template type.")
}

func strInSlice(str string, sl []string) bool {
	for _, s := range sl {
		if s == str {
			return true
		}
	}
	return false
}

// HelperFuncMap provides all string functions in the strings package
// along with simple arithmetic and inflection functions.
var TemplateFuncs = map[string]interface{}{
	"Contains":       strings.Contains,
	"ContainsAny":    strings.ContainsAny,
	"ContainsRune":   strings.ContainsRune,
	"Count":          strings.Count,
	"EqualFold":      strings.EqualFold,
	"Fields":         strings.Fields,
	"HasPrefix":      strings.HasPrefix,
	"HasSuffix":      strings.HasSuffix,
	"Index":          strings.Index,
	"IndexAny":       strings.IndexAny,
	"IndexByte":      strings.IndexByte,
	"IndexFunc":      strings.IndexFunc,
	"IndexRune":      strings.IndexRune,
	"Join":           strings.Join,
	"LastIndex":      strings.LastIndex,
	"LastIndexAny":   strings.LastIndexAny,
	"Map":            strings.Map,
	"Repeat":         strings.Repeat,
	"Replace":        strings.Replace,
	"Split":          strings.Split,
	"SplitAfter":     strings.SplitAfter,
	"SplitAfterN":    strings.SplitAfterN,
	"SplitN":         strings.SplitN,
	"Title":          strings.Title,
	"ToLower":        strings.ToLower,
	"ToLowerSpecial": strings.ToLowerSpecial,
	"ToTitle":        strings.ToTitle,
	"ToTitleSpecial": strings.ToTitleSpecial,
	"ToUpper":        strings.ToUpper,
	"ToUpperSpecial": strings.ToUpperSpecial,
	"Trim":           strings.Trim,
	"TrimFunc":       strings.TrimFunc,
	"TrimLeft":       strings.TrimLeft,
	"TrimLeftFunc":   strings.TrimLeftFunc,
	"TrimPrefix":     strings.TrimPrefix,
	"TrimRight":      strings.TrimRight,
	"TrimRightFunc":  strings.TrimRightFunc,
	"TrimSpace":      strings.TrimSpace,
	"TrimSuffix":     strings.TrimSuffix,

	"Asciify":             inflect.Asciify,
	"Camelize":            inflect.Camelize,
	"CamelizeDownFirst":   inflect.CamelizeDownFirst,
	"Capitalize":          inflect.Capitalize,
	"Dasherize":           inflect.Dasherize,
	"ForeignKey":          inflect.ForeignKey,
	"ForeignKeyCondensed": inflect.ForeignKeyCondensed,
	"Humanize":            inflect.Humanize,
	"Ordinalize":          inflect.Ordinalize,
	"Parameterize":        inflect.Parameterize,
	"ParameterizeJoin":    inflect.ParameterizeJoin,
	"Pluralize":           inflect.Pluralize,
	"Singularize":         inflect.Singularize,
	"Tableize":            inflect.Tableize,
	"Titleize":            inflect.Titleize,
	"Typeify":             inflect.Typeify,
	"Uncountables":        inflect.Uncountables,
	"Underscore":          inflect.Underscore,

	"Sprintf": fmt.Sprintf,

	"Incr": func(a int64) int64 { return a + 1 },
	"Decr": func(a int64) int64 { return a - 1 },
}


text:
@interface NSString (NSString_SqlExtensions)

- (NSString *)encodedForLike;
- (NSString *)encodedForSql;

@end


text:
using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System.IO;
using System;
using InfluxDB.LineProtocol.Client;
using InfluxDB.LineProtocol.Payload;
using System.Net.Http;
using System.Threading;

namespace backend
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var reader = new StreamReader(context.Request.Body);
                //var line = await reader.ReadLineAsync();

                var http = new HttpClient();
                while (true)
                {
                    var line = $"client_metrics,clientid=1 expenditure={new Random().Next(10)}";
                    Thread.Sleep(1000);
                    Console.Write(line);
                    var r = await http.PostAsync("http://localhost:8086/write?db=fraud&precision=ms",
                        new StringContent(line));
                    Console.WriteLine(r.StatusCode);
                }
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}


text:
        <title>
            My First Website, with CSS!
        </title>
        <link rel="stylesheet" href="styles/style.css" />

Now I can center my content!


text:
package org.joda.time.tz;

import java.text.DateFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.joda.time.DateTimeUtils;

/**
 * The default name provider acquires localized names from
 * {@link DateFormatSymbols java.text.DateFormatSymbols}.
 * <p>
 * DefaultNameProvider is thread-safe and immutable.
 *
 * @author Brian S O'Neill
 * @since 1.0
 */
@SuppressWarnings("unchecked")
public class DefaultNameProvider implements NameProvider {
    // locale -> (id -> (nameKey -> [shortName, name]))
    private HashMap<Locale, Map<String, Map<String, Object>>> iByLocaleCache = createCache();

    public DefaultNameProvider() {
    }

    public String getShortName(Locale locale, String id, String nameKey) {
        String[] nameSet = getNameSet(locale, id, nameKey);
        return nameSet == null ? null : nameSet[0];
    }

    public String getName(Locale locale, String id, String nameKey) {
        String[] nameSet = getNameSet(locale, id, nameKey);
        return nameSet == null ? null : nameSet[1];
    }

    private synchronized String[] getNameSet(Locale locale, String id, String nameKey) {
        if (locale == null || id == null || nameKey == null) {
            return null;
        }

        Map<String, Map<String, Object>> byIdCache = iByLocaleCache.get(locale);
        if (byIdCache == null) {
            iByLocaleCache.put(locale, byIdCache = createCache());
        }

        Map<String, Object> byNameKeyCache = byIdCache.get(id);
        if (byNameKeyCache == null) {
            byIdCache.put(id, byNameKeyCache = createCache());
            String[][] zoneStrings = DateTimeUtils.getDateFormatSymbols(locale).getZoneStrings();
            for (int i=0; i<zoneStrings.length; i++) {
                String[] set = zoneStrings[i];
                if (set != null && set.length == 5 && id.equals(set[0])) {
                    byNameKeyCache.put(set[2], new String[] {set[2], set[1]});
                    // need to handle case where summer and winter have the same
                    // abbreviation, such as EST in Australia [1716305]
                    // we handle this by appending "-Summer", cf ZoneInfoCompiler
                    if (set[2].equals(set[4])) {
                        byNameKeyCache.put(set[4] + "-Summer", new String[] {set[4], set[3]});
                    } else {
                        byNameKeyCache.put(set[4], new String[] {set[4], set[3]});
                    }
                    break;
                }
            }
        }

        return (String[])byNameKeyCache.get(nameKey);
    }

    private HashMap createCache() {
        return new HashMap(7);
    }
}


text:
namespace lime {

	ValuePointer* ClipboardEvent::callback = 0;
	ValuePointer* ClipboardEvent::eventObject = 0;

	static int id_type;
	static bool init = false;

	ClipboardEvent::ClipboardEvent () {

		type = CLIPBOARD_UPDATE;

	}

	void ClipboardEvent::Dispatch (ClipboardEvent* event) {

		if (ClipboardEvent::callback) {

			if (ClipboardEvent::eventObject->IsCFFIValue ()) {

				if (!init) {

					id_type = val_id ("type");
					init = true;

				}

				value object = (value)ClipboardEvent::eventObject->Get ();

				alloc_field (object, id_type, alloc_int (event->type));

			} else {

				ClipboardEvent* eventObject = (ClipboardEvent*)ClipboardEvent::eventObject->Get ();

				eventObject->type = event->type;

			}

			ClipboardEvent::callback->Call ();

		}

	}

}


text:
"""
This module defines exceptions commonly used in scikit-ci.
"""

import os
import textwrap

class SKCIError(RuntimeError):
    """Exception raised when an scikit-ci error occurs.
    """
    pass

class SKCIStepExecutionError(SKCIError):
    """Exception raised when an error occurs while executing a step.
    """
    def __init__(self, step, return_code, cmd, output=None):
        self.step = step
        self.return_code = return_code
        self.cmd = cmd
        self.output = output

    def __str__(self):
        return textwrap.dedent(
            r"""
            A command failed while executing {step} step.
              Return code:
                {return_code}
              Command:
                {cmd}
              Working directory:
                {cwd}

            Please see above for more information.
            """.format(
                step=self.step.upper(),
                return_code=self.return_code,
                cmd=self.cmd,
                cwd=os.getcwd()
            )
        )


text:
package com.faforever.client.replay;

import com.faforever.client.config.ClientProperties;
import com.faforever.client.i18n.I18n;
import com.faforever.client.preferences.PreferencesService;
import com.faforever.commons.io.Bytes;
import com.faforever.commons.replay.QtCompress;
import com.google.common.io.BaseEncoding;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Path;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE_NEW;

@Lazy
@Component
public class ReplayFileWriterImpl implements ReplayFileWriter {

  private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
  private final Gson gson;

  private final I18n i18n;
  private final ClientProperties clientProperties;
  private final PreferencesService preferencesService;

  @Inject
  public ReplayFileWriterImpl(I18n i18n, ClientProperties clientProperties, PreferencesService preferencesService) {
    this.i18n = i18n;
    this.clientProperties = clientProperties;
    this.preferencesService = preferencesService;

    gson = ReplayFiles.gson();
  }

  @Override
  public void writeReplayDataToFile(ByteArrayOutputStream replayData, LocalReplayInfo replayInfo) throws IOException {
    String fileName = String.format(clientProperties.getReplay().getReplayFileFormat(), replayInfo.getUid(), replayInfo.getRecorder());
    Path replayFile = preferencesService.getReplaysDirectory().resolve(fileName);

    logger.info("Writing replay file to {} ({})", replayFile, Bytes.formatSize(replayData.size(), i18n.getUserSpecificLocale()));

    Files.createDirectories(replayFile.getParent());

    try (BufferedWriter writer = Files.newBufferedWriter(replayFile, UTF_8, CREATE_NEW)) {
      byte[] compressedBytes = QtCompress.qCompress(replayData.toByteArray());
      String base64ReplayData = BaseEncoding.base64().encode(compressedBytes);

      gson.toJson(replayInfo, writer);
      writer.write('\n');
      writer.write(base64ReplayData);
    }
  }
}


text:
<?php include('../config.php');?>
<?php include('header.php');?>
<?php

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$middlename = $_POST['middlename'];
$user_ID = $_POST['ID'];
$middlename	= substr($middlename, 0,1);
$name = $firstname." ".$middlename.". ".$lastname;
$h = "-8";// Hour for time zone goes here e.g. +7 or -4, just remove the + or -
$hm = $h * 60;
$ms = $hm * 60;
$time=gmdate("M d Y, g:i A", time()+28800);

$sql_insert = "INSERT INTO tracking (name, timeIN, user_ID) VALUES ('$name', '$time', '$user_ID')";
if(mysql_query($sql_insert)){
?>

Success You have logged in successfully

<?php
}
else{
	echo "ERROR ". mysql_error();
	echo '
Oh snap! Change a few things up and try submitting again.
';
}
?>


text:
type A1 = {| p: number |};
type B1 = {...A1, [number]: string};
({p: 3}: B1);

type A2 = {| p: string |};
type B2 = {...A2, p?: string};
declare var x: {p?: string}
(x: B2);

type A3 = { p: number };
type B3 = {...A3, [number]: string};
({p: 3}: B3); // Ok! even though A3 is inexact.
// You can't specify an indexer inline at runtime, so this is sound!

type A4 = { p: string };
type B4 = {...A4, p?: string};
declare var x: {p?: string}
(x: B4); // Ok for the same reason as above, except for optional props

// Ensuring we still error in these cases when the RHS is a spread
// is handled by all_cases.js


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using clipr;

namespace PyriteCliCommon
{
    [ApplicationInfo(Description = "PyriteCli Options")]
    public class Options
    {
        [NamedArgument('x', "xsize", Action = ParseAction.Store,
            Description = "The number of times to subdivide in the X dimension.  Default 10.")]
        public int XSize { get; set; }

        [NamedArgument('y', "ysize", Action = ParseAction.Store,
            Description = "The number of times to subdivide in the Y dimension.  Default 10.")]
        public int YSize { get; set; }

        [NamedArgument('z', "zsize", Action = ParseAction.Store,
            Description = "The number of times to subdivide in the Z dimension.  Default 10.")]
        public int ZSize { get; set; }

        [NamedArgument('u', "texturex", Action = ParseAction.Store,
            Description = "The number of times to subdivide texture in the X dimension. Default 4.")]
        public int TextureXSize { get; set; }

        [NamedArgument('v', "texturey", Action = ParseAction.Store,
            Description = "The number of times to subdivide texture in the Y dimension. Default 4.")]
        public int TextureYSize { get; set; }

        [NamedArgument('s', "scaletexture", Action = ParseAction.Store,
            Description = "A number between 0 and 1 telling PyriteCli how to resize/scale the texture when using -t.  Default 1.")]
        public float ScaleTexture { get; set; }

        [NamedArgument('m', "mtl", Action = ParseAction.Store,
            Description = "Override the MTL field in output obj files. e.g. -z model.mtl")]
        public string MtlOverride { get; set; }

        [NamedArgument('t', "texture", Action = ParseAction.Store,
            Description = "Include a texture to partition during cube slicing. Will rewrite UV's in output files. Requires -tx -ty parameters.")]
        public string Texture { get; set; }

        [NamedArgument('o', "obj", Action = ParseAction.StoreTrue,
            Description = "Generate OBJ files designed for use with CubeServer")]
        public bool Obj { get; set; }

        [NamedArgument("writemtl", Action = ParseAction.StoreTrue,
            Description = "Writes one MTL file per texture and updates OBJ reference")]
        public bool WriteMtl { get; set; }

        [NamedArgument('e', "ebo", Action = ParseAction.StoreTrue,
            Description = "Generate EBO files designed for use with CubeServer")]
        public bool Ebo { get; set; }

        [NamedArgument('p', "openctm", Action = ParseAction.StoreTrue,
            Description = "Generate OpenCtm files designed for use with CubeServer")]
        public bool OpenCtm { get; set; }

        [NamedArgument('a', "markupUV", Action = ParseAction.StoreTrue,
            Description = "Draws UVW's on a texture")]
        public bool MarkupUV { get; set; }

        [NamedArgument('c', "forcecubical", Action = ParseAction.StoreTrue,
            Description = "X Y Z grid dimensions will be equal, and world space will be grown to fill a containing cube.")]
        public bool ForceCubical { get; set; }

        [NamedArgument('d', "debug", Action = ParseAction.StoreTrue,
            Description = "Generate various additional debug data during error states")]
        public bool Debug { get; set; }

        [PositionalArgument(0, MetaVar = "OUT",
            Description = "Output folder")]
        public string OutputPath { get; set; }

        [PositionalArgument(1, MetaVar = "IN",
            NumArgs = 1,
            Constraint = NumArgsConstraint.AtLeast,
            Description = "A list of .obj files to process")]
        public List<string> Input { get; set; }

        public Options()
        {
            XSize = 2;
            YSize = 2;
            ZSize = 2;
            ScaleTexture = 1;
            TextureXSize = 4;
            TextureYSize = 4;
            ForceCubical = false;
            Debug = false;
        }
    }

}


text:
package com.seatgeek.placesautocomplete.json;

import java.io.IOException;

public class JsonWritingException extends IOException {

    public JsonWritingException() {
    }

    public JsonWritingException(final String detailMessage) {
        super(detailMessage);
    }

    public JsonWritingException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public JsonWritingException(final Throwable cause) {
        super(cause);
    }
}


text:
<!---
Copyright 2017 The AMP HTML Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# myWidget

myWidget is a service for personalizing content and increasing user metrics.

Our NeuroClick technology uses behavioral data of eighty million users, collaborative filtering algorithms and neural networks. NeuroClick delivers the most relevant content to every user of the site.

myWidget is a free platform used by web publishers to improve metrics and audience loyalty.

Please visit our [website](https://widget.my.com) for more information about us.

## Example

```html
<amp-embed height="250" type="mywidget" data-cid="your-campaign-id">
</amp-embed>
```

## Configuration

For semantics of configuration, please see [myWidget documentation](https://widget.my.com/docs/dev/amp/).

### Required parameters

- `data-cid`


text:
namespace {

void LogHistogramValue(int action) {
  UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
                            signin_metrics::HISTOGRAM_MAX);
}

// Returns true if |profile| is a system profile or created from one.
bool IsSystemProfile(Profile* profile) {
  return profile->GetOriginalProfile()->IsSystemProfile();
}

void RedirectToNtpOrAppsPage(content::WebContents* contents,
                             signin_metrics::AccessPoint access_point) {
  // Do nothing if a navigation is pending, since this call can be triggered
  // from DidStartLoading. This avoids deleting the pending entry while we are
  // still navigating to it. See crbug/346632.
  if (contents->GetController().GetPendingEntry())
    return;

  VLOG(1) << "RedirectToNtpOrAppsPage";
  // Redirect to NTP/Apps page and display a confirmation bubble
  GURL url(access_point ==
                   signin_metrics::AccessPoint::ACCESS_POINT_APPS_PAGE_LINK
               ? chrome::kChromeUIAppsURL
               : chrome::kChromeUINewTabURL);
  content::OpenURLParams params(url,
                                content::Referrer(),
                                CURRENT_TAB,
                                ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                false);
  contents->OpenURL(params);
}

void RedirectToNtpOrAppsPageIfNecessary(
    content::WebContents* contents,
    signin_metrics::AccessPoint access_point) {
  if (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS)
    RedirectToNtpOrAppsPage(contents, access_point);
}

class ConfirmEmailDialogDelegate : public TabModalConfirmDialogDelegate {
 public:
  // Callback indicating action performed by the user.
  typedef base::Callback<void(InlineSigninHelper::Action)> Callback;

  // Ask the user for confirmation before starting to sync.
  static void AskForConfirmation(content::WebContents* contents,
                                 const std::string& last_email,
                                 const std::string& email,
                                 Callback callback);

 private:
  ConfirmEmailDialogDelegate(content::WebContents* contents,
                             const std::string& last_email,
                             const std::string& email,
                             Callback callback);
  ~ConfirmEmailDialogDelegate() override;

  // TabModalConfirmDialogDelegate:
  base::string16 GetTitle() override;
  base::string16 GetDialogMessage() override;
  base::string16 GetAcceptButtonTitle() override;
  base::string16 GetCancelButtonTitle() override;
  base::string16 GetLinkText() const override;
  void OnAccepted() override;
  void OnCanceled() override;
  void OnClosed() override;
  void OnLinkClicked(WindowOpenDisposition disposition) override;

  std::string last_email_;
  std::string email_;
  Callback callback_;

  // Web contents from which the "Learn more" link should be opened.
  content::WebContents* web_contents_;

  DISALLOW_COPY_AND_ASSIGN(ConfirmEmailDialogDelegate);
};

// static
void ConfirmEmailDialogDelegate::AskForConfirmation(
    content::WebContents* contents,
    const std::string& last_email,
    const std::string& email,
    Callback callback) {
  content::RecordAction(
      base::UserMetricsAction("Signin_Show_ImportDataPrompt"));
  TabModalConfirmDialog::Create(
      new ConfirmEmailDialogDelegate(contents, last_email, email, callback),
      contents);
}

ConfirmEmailDialogDelegate::ConfirmEmailDialogDelegate(
    content::WebContents* contents,
    const std::string& last_email,
    const std::string& email,
    Callback callback)
  : TabModalConfirmDialogDelegate(contents),
    last_email_(last_email),
    email_(email),
    callback_(callback),
    web_contents_(contents) {
}

ConfirmEmailDialogDelegate::~ConfirmEmailDialogDelegate() {
}

base::string16 ConfirmEmailDialogDelegate::GetTitle() {
  return l10n_util::GetStringUTF16(
      IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_TITLE);
}

base::string16 ConfirmEmailDialogDelegate::GetDialogMessage() {
  return l10n_util::GetStringFUTF16(
      IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_MESSAGE,
      base::UTF8ToUTF16(last_email_), base::UTF8ToUTF16(email_));
}

base::string16 ConfirmEmailDialogDelegate::GetAcceptButtonTitle() {
  return l10n_util::GetStringUTF16(
      IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_OK_BUTTON);
}

base::string16 ConfirmEmailDialogDelegate::GetCancelButtonTitle() {
  return l10n_util::GetStringUTF16(
      IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_CANCEL_BUTTON);
}

base::string16 ConfirmEmailDialogDelegate::GetLinkText() const {
  return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}

void ConfirmEmailDialogDelegate::OnAccepted() {
  base::ResetAndReturn(&callback_).Run(InlineSigninHelper::CREATE_NEW_USER);
}

void ConfirmEmailDialogDelegate::OnCanceled() {
  base::ResetAndReturn(&callback_).Run(InlineSigninHelper::START_SYNC);
}

void ConfirmEmailDialogDelegate::OnClosed() {
  base::ResetAndReturn(&callback_).Run(InlineSigninHelper::CLOSE);
}

void ConfirmEmailDialogDelegate::OnLinkClicked(
    WindowOpenDisposition disposition) {
  content::OpenURLParams params(
      GURL(chrome::kChromeSyncMergeTroubleshootingURL),
      content::Referrer(),
      NEW_POPUP,
      ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
      false);
  // It is guaranteed that |web_contents_| is valid here because when it's
  // deleted, the dialog is immediately closed and no further action can be
  // performed.
  web_contents_->OpenURL(params);
}

}  // namespace

InlineSigninHelper::InlineSigninHelper(
    base::WeakPtr<InlineLoginHandlerImpl> handler,
    net::URLRequestContextGetter* getter,
    Profile* profile,
    const GURL& current_url,
    const std::string& email,
    const std::string& gaia_id,
    const std::string& password,
    const std::string& session_index,
    const std::string& auth_code,
    const std::string& signin_scoped_device_id,
    bool choose_what_to_sync,
    bool confirm_untrusted_signin)
    : gaia_auth_fetcher_(this, GaiaConstants::kChromeSource, getter),
      handler_(handler),
      profile_(profile),
      current_url_(current_url),
      email_(email),
      gaia_id_(gaia_id),
      password_(password),
      session_index_(session_index),
      auth_code_(auth_code),
      choose_what_to_sync_(choose_what_to_sync),
      confirm_untrusted_signin_(confirm_untrusted_signin) {
  DCHECK(profile_);
  DCHECK(!email_.empty());
  if (!auth_code_.empty()) {
    gaia_auth_fetcher_.StartAuthCodeForOAuth2TokenExchangeWithDeviceId(
        auth_code, signin_scoped_device_id);
  } else {
    DCHECK(!session_index_.empty());
    gaia_auth_fetcher_.StartCookieForOAuthLoginTokenExchangeWithDeviceId(
        session_index_, signin_scoped_device_id);
  }
}

InlineSigninHelper::~InlineSigninHelper() {}

void InlineSigninHelper::OnClientOAuthSuccess(const ClientOAuthResult& result) {
  content::WebContents* contents = NULL;
  Browser* browser = NULL;
  if (handler_) {
    contents = handler_->web_ui()->GetWebContents();
    browser = handler_->GetDesktopBrowser();
  }

  AboutSigninInternals* about_signin_internals =
      AboutSigninInternalsFactory::GetForProfile(profile_);
  about_signin_internals->OnRefreshTokenReceived("Successful");

  // Prime the account tracker with this combination of gaia id/display email.
  std::string account_id =
      AccountTrackerServiceFactory::GetForProfile(profile_)
          ->SeedAccountInfo(gaia_id_, email_);

  signin_metrics::AccessPoint access_point =
      signin::GetAccessPointForPromoURL(current_url_);
  signin_metrics::Reason reason =
      signin::GetSigninReasonForPromoURL(current_url_);

  SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile_);
  std::string primary_email =
      signin_manager->GetAuthenticatedAccountInfo().email;
  if (gaia::AreEmailsSame(email_, primary_email) &&
      (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
       reason == signin_metrics::Reason::REASON_UNLOCK) &&
      switches::IsNewProfileManagement() && !password_.empty() &&
      profiles::IsLockAvailable(profile_)) {
    LocalAuth::SetLocalAuthCredentials(profile_, password_);
  }

  if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
      reason == signin_metrics::Reason::REASON_UNLOCK ||
      reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) {
    ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->
        UpdateCredentials(account_id, result.refresh_token);

    if (signin::IsAutoCloseEnabledInURL(current_url_)) {
      // Close the gaia sign in tab via a task to make sure we aren't in the
      // middle of any webui handler code.
      base::ThreadTaskRunnerHandle::Get()->PostTask(
          FROM_HERE,
          base::Bind(&InlineLoginHandlerImpl::CloseTab, handler_,
                     signin::ShouldShowAccountManagement(current_url_)));
    }

    if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION ||
        reason == signin_metrics::Reason::REASON_UNLOCK) {
      signin_manager->MergeSigninCredentialIntoCookieJar();
    }
    LogSigninReason(reason);
  } else {
    ProfileSyncService* sync_service =
        ProfileSyncServiceFactory::GetForProfile(profile_);
    SigninErrorController* error_controller =
        SigninErrorControllerFactory::GetForProfile(profile_);

    OneClickSigninSyncStarter::StartSyncMode start_mode =
        OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST;
    if (access_point == signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS ||
        choose_what_to_sync_) {
      bool show_settings_without_configure =
          error_controller->HasError() &&
          sync_service &&
          sync_service->HasSyncSetupCompleted();
      start_mode = show_settings_without_configure ?
          OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
          OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST;
    }

    OneClickSigninSyncStarter::ConfirmationRequired confirmation_required =
        confirm_untrusted_signin_ ?
            OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN :
            OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;

    bool start_signin = !HandleCrossAccountError(
        result.refresh_token, confirmation_required, start_mode);
    if (start_signin) {
      CreateSyncStarter(browser, contents, current_url_,
                        signin::GetNextPageURLForPromoURL(current_url_),
                        result.refresh_token, start_mode,
                        confirmation_required);
      base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
    }
  }
}

void InlineSigninHelper::CreateSyncStarter(
    Browser* browser,
    content::WebContents* contents,
    const GURL& current_url,
    const GURL& continue_url,
    const std::string& refresh_token,
    OneClickSigninSyncStarter::StartSyncMode start_mode,
    OneClickSigninSyncStarter::ConfirmationRequired confirmation_required) {
  // OneClickSigninSyncStarter will delete itself once the job is done.
  new OneClickSigninSyncStarter(
      profile_, browser, gaia_id_, email_, password_, refresh_token, start_mode,
      contents, confirmation_required, current_url, continue_url,
      base::Bind(&InlineLoginHandlerImpl::SyncStarterCallback, handler_));
}

bool InlineSigninHelper::HandleCrossAccountError(
    const std::string& refresh_token,
    OneClickSigninSyncStarter::ConfirmationRequired confirmation_required,
    OneClickSigninSyncStarter::StartSyncMode start_mode) {
  std::string last_email =
      profile_->GetPrefs()->GetString(prefs::kGoogleServicesLastUsername);

  InvestigatorDependencyProvider provider(profile_);
  InvestigatedScenario scenario =
      SigninInvestigator(email_, gaia_id_, &provider).Investigate();

  // TODO(skym): Warn for high risk upgrade scenario, crbug.com/572754.
  if (scenario != InvestigatedScenario::DIFFERENT_ACCOUNT) {
    return false;
  }

  Browser* browser = chrome::FindLastActiveWithProfile(
      profile_, chrome::GetActiveDesktop());
  content::WebContents* web_contents =
      browser->tab_strip_model()->GetActiveWebContents();

  ConfirmEmailDialogDelegate::AskForConfirmation(
      web_contents,
      last_email,
      email_,
      base::Bind(&InlineSigninHelper::ConfirmEmailAction,
                 base::Unretained(this),
                 web_contents,
                 refresh_token,
                 confirmation_required,
                 start_mode));
  return true;
}

void InlineSigninHelper::ConfirmEmailAction(
    content::WebContents* web_contents,
    const std::string& refresh_token,
    OneClickSigninSyncStarter::ConfirmationRequired confirmation_required,
    OneClickSigninSyncStarter::StartSyncMode start_mode,
    InlineSigninHelper::Action action) {
  Browser* browser = chrome::FindLastActiveWithProfile(
      profile_, chrome::GetActiveDesktop());
  switch (action) {
    case InlineSigninHelper::CREATE_NEW_USER:
      content::RecordAction(
          base::UserMetricsAction("Signin_ImportDataPrompt_DontImport"));
      if (handler_) {
        handler_->SyncStarterCallback(
            OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
      }
      chrome::ShowSettingsSubPage(browser,
                                  std::string(chrome::kCreateProfileSubPage));
      break;
    case InlineSigninHelper::START_SYNC:
      content::RecordAction(
          base::UserMetricsAction("Signin_ImportDataPrompt_ImportData"));
      CreateSyncStarter(browser, web_contents, current_url_, GURL(),
                        refresh_token, start_mode, confirmation_required);
      break;
    case InlineSigninHelper::CLOSE:
      content::RecordAction(
          base::UserMetricsAction("Signin_ImportDataPrompt_Cancel"));
      if (handler_) {
        handler_->SyncStarterCallback(
            OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
      }
      break;
    default:
      DCHECK(false) << "Invalid action";
  }
  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}

void InlineSigninHelper::OnClientOAuthFailure(
  const GoogleServiceAuthError& error) {
  if (handler_)
    handler_->HandleLoginError(error.ToString());

  AboutSigninInternals* about_signin_internals =
    AboutSigninInternalsFactory::GetForProfile(profile_);
  about_signin_internals->OnRefreshTokenReceived("Failure");

  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}

InlineLoginHandlerImpl::InlineLoginHandlerImpl()
      : confirm_untrusted_signin_(false),
        weak_factory_(this) {
}

InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}

// This method is not called with webview sign in enabled.
void InlineLoginHandlerImpl::DidCommitProvisionalLoadForFrame(
    content::RenderFrameHost* render_frame_host,
    const GURL& url,
    ui::PageTransition transition_type) {
  if (!web_contents())
    return;

  // Returns early if this is not a gaia iframe navigation.
  const GURL kGaiaExtOrigin(
      GaiaUrls::GetInstance()->signin_completed_continue_url().GetOrigin());
  content::RenderFrameHost* gaia_frame = InlineLoginUI::GetAuthFrame(
      web_contents(), kGaiaExtOrigin, "signin-frame");
  if (render_frame_host != gaia_frame)
    return;

  // Loading any untrusted (e.g., HTTP) URLs in the privileged sign-in process
  // will require confirmation before the sign in takes effect.
  if (!url.is_empty()) {
    GURL origin(url.GetOrigin());
    if (url.spec() != url::kAboutBlankURL &&
        origin != kGaiaExtOrigin &&
        !gaia::IsGaiaSignonRealm(origin)) {
      confirm_untrusted_signin_ = true;
    }
  }
}

// static
bool InlineLoginHandlerImpl::CanOffer(Profile* profile,
                                      CanOfferFor can_offer_for,
                                      const std::string& gaia_id,
                                      const std::string& email,
                                      std::string* error_message) {
  if (error_message)
    error_message->clear();

  if (!profile)
    return false;

  SigninManager* manager = SigninManagerFactory::GetForProfile(profile);
  if (manager && !manager->IsSigninAllowed())
    return false;

  if (!ChromeSigninClient::ProfileAllowsSigninCookies(profile))
    return false;

  if (!email.empty()) {
    if (!manager)
      return false;

    // Make sure this username is not prohibited by policy.
    if (!manager->IsAllowedUsername(email)) {
      if (error_message) {
        error_message->assign(
            l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED));
      }
      return false;
    }

    if (can_offer_for == CAN_OFFER_FOR_SECONDARY_ACCOUNT)
      return true;

    // If the signin manager already has an authenticated name, then this is a
    // re-auth scenario.  Make sure the email just signed in corresponds to
    // the one sign in manager expects.
    std::string current_email = manager->GetAuthenticatedAccountInfo().email;
    const bool same_email = gaia::AreEmailsSame(current_email, email);
    if (!current_email.empty() && !same_email) {
      UMA_HISTOGRAM_ENUMERATION("Signin.Reauth",
                                signin_metrics::HISTOGRAM_ACCOUNT_MISSMATCH,
                                signin_metrics::HISTOGRAM_MAX);
      if (error_message) {
        error_message->assign(
            l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
                                      base::UTF8ToUTF16(current_email)));
      }
      return false;
    }

    // If some profile, not just the current one, is already connected to this
    // account, don't show the infobar.
    if (g_browser_process && !same_email) {
      ProfileManager* profile_manager = g_browser_process->profile_manager();
      if (profile_manager) {
        ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
        for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
          // For backward compatibility, need to also check the username of the
          // profile, since the GAIA ID may not have been set yet for the
          // profile cache info.  It will get set once the profile is opened.
          std::string profile_gaia_id = cache.GetGAIAIdOfProfileAtIndex(i);
          std::string profile_email =
              base::UTF16ToUTF8(cache.GetUserNameOfProfileAtIndex(i));
          if (gaia_id == profile_gaia_id ||
              gaia::AreEmailsSame(email, profile_email)) {
            if (error_message) {
              error_message->assign(
                  l10n_util::GetStringUTF8(IDS_SYNC_USER_NAME_IN_USE_ERROR));
            }
            return false;
          }
        }
      }
    }
  }

  return true;
}

void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
  params.SetString("service", "chromiumsync");

  // If this was called from the user manager to reauthenticate the profile,
  // make sure the webui is aware.
  Profile* profile = Profile::FromWebUI(web_ui());
  if (IsSystemProfile(profile))
    params.SetBoolean("dontResizeNonEmbeddedPages", true);

  content::WebContents* contents = web_ui()->GetWebContents();
  const GURL& current_url = contents->GetURL();
  signin_metrics::Reason reason =
      signin::GetSigninReasonForPromoURL(current_url);

  std::string is_constrained;
  net::GetValueForKeyInQuery(current_url, "constrained", &is_constrained);

  // Use new embedded flow if in constrained window.
  if (is_constrained == "1") {
    const bool is_new_gaia_flow = switches::UsePasswordSeparatedSigninFlow();
    const GURL& url = is_new_gaia_flow
            ? GaiaUrls::GetInstance()->embedded_signin_url()
            : GaiaUrls::GetInstance()->password_combined_embedded_signin_url();
    params.SetBoolean("isNewGaiaFlow", is_new_gaia_flow);
    params.SetString("clientId",
                     GaiaUrls::GetInstance()->oauth2_chrome_client_id());
    params.SetString("gaiaPath", url.path().substr(1));

    std::string flow;
    switch (reason) {
      case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT:
        flow = "addaccount";
        break;
      case signin_metrics::Reason::REASON_REAUTHENTICATION:
      case signin_metrics::Reason::REASON_UNLOCK:
        flow = "reauth";
        break;
      default:
        flow = "signin";
        break;
    }
    params.SetString("flow", flow);
  }

  content::WebContentsObserver::Observe(contents);
  LogHistogramValue(signin_metrics::HISTOGRAM_SHOWN);
}

void InlineLoginHandlerImpl::CompleteLogin(const base::ListValue* args) {
  content::WebContents* contents = web_ui()->GetWebContents();
  const GURL& current_url = contents->GetURL();

  const base::DictionaryValue* dict = NULL;
  args->GetDictionary(0, &dict);

  bool skip_for_now = false;
  dict->GetBoolean("skipForNow", &skip_for_now);
  if (skip_for_now) {
    signin::SetUserSkippedPromo(Profile::FromWebUI(web_ui()));
    SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
    return;
  }

  // This value exists only for webview sign in.
  bool trusted = false;
  if (dict->GetBoolean("trusted", &trusted))
    confirm_untrusted_signin_ = !trusted;

  base::string16 email_string16;
  dict->GetString("email", &email_string16);
  DCHECK(!email_string16.empty());
  std::string email(base::UTF16ToASCII(email_string16));

  base::string16 password_string16;
  dict->GetString("password", &password_string16);
  std::string password(base::UTF16ToASCII(password_string16));

  base::string16 gaia_id_string16;
  dict->GetString("gaiaId", &gaia_id_string16);
  DCHECK(!gaia_id_string16.empty());
  std::string gaia_id = base::UTF16ToASCII(gaia_id_string16);

  std::string is_constrained;
  net::GetValueForKeyInQuery(current_url, "constrained", &is_constrained);
  const bool is_password_separated_signin_flow = is_constrained == "1" &&
      switches::UsePasswordSeparatedSigninFlow();

  base::string16 session_index_string16;
  dict->GetString("sessionIndex", &session_index_string16);
  std::string session_index = base::UTF16ToASCII(session_index_string16);
  DCHECK(is_password_separated_signin_flow || !session_index.empty());

  base::string16 auth_code_string16;
  dict->GetString("authCode", &auth_code_string16);
  std::string auth_code = base::UTF16ToASCII(auth_code_string16);
  DCHECK(!is_password_separated_signin_flow || !auth_code.empty());

  bool choose_what_to_sync = false;
  dict->GetBoolean("chooseWhatToSync", &choose_what_to_sync);

  content::StoragePartition* partition =
      content::BrowserContext::GetStoragePartitionForSite(
          contents->GetBrowserContext(), signin::GetSigninPartitionURL());

  // If this was called from the user manager to reauthenticate the profile,
  // the current profile is the system profile.  In this case, use the email to
  // find the right profile to reauthenticate.  Otherwise the profile can be
  // taken from web_ui().
  Profile* profile = Profile::FromWebUI(web_ui());
  if (IsSystemProfile(profile)) {
    // Switch to the profile and finish the login.  Don't pass a handler pointer
    // since it will be destroyed before the callback runs.
    ProfileManager* manager = g_browser_process->profile_manager();
    base::FilePath path = profiles::GetPathOfProfileWithEmail(manager, email);
    if (!path.empty()) {
      FinishCompleteLoginParams params(nullptr, partition, current_url, path,
                                       confirm_untrusted_signin_, email,
                                       gaia_id, password, session_index,
                                       auth_code, choose_what_to_sync);
      ProfileManager::CreateCallback callback = base::Bind(
          &InlineLoginHandlerImpl::FinishCompleteLogin, params);
      profiles::SwitchToProfile(path, chrome::GetActiveDesktop(), true,
          callback, ProfileMetrics::SWITCH_PROFILE_UNLOCK);
    }
  } else {
    FinishCompleteLogin(
        FinishCompleteLoginParams(this, partition, current_url,
                                  base::FilePath(), confirm_untrusted_signin_,
                                  email, gaia_id, password, session_index,
                                  auth_code, choose_what_to_sync),
        profile,
        Profile::CREATE_STATUS_CREATED);
  }
}

InlineLoginHandlerImpl::FinishCompleteLoginParams::FinishCompleteLoginParams(
    InlineLoginHandlerImpl* handler,
    content::StoragePartition* partition,
    const GURL& url,
    const base::FilePath& profile_path,
    bool confirm_untrusted_signin,
    const std::string& email,
    const std::string& gaia_id,
    const std::string& password,
    const std::string& session_index,
    const std::string& auth_code,
    bool choose_what_to_sync)
    : handler(handler),
      partition(partition),
      url(url),
      profile_path(profile_path),
      confirm_untrusted_signin(confirm_untrusted_signin),
      email(email),
      gaia_id(gaia_id),
      password(password),
      session_index(session_index),
      auth_code(auth_code),
      choose_what_to_sync(choose_what_to_sync) {}

InlineLoginHandlerImpl::
    FinishCompleteLoginParams::~FinishCompleteLoginParams() {}

// static
void InlineLoginHandlerImpl::FinishCompleteLogin(
    const FinishCompleteLoginParams& params,
    Profile* profile,
    Profile::CreateStatus status) {
  if (params.handler && switches::UsePasswordSeparatedSigninFlow()) {
    Browser* browser = params.handler->GetDesktopBrowser();
    if (browser)
      browser->window()->CloseModalSigninWindow();
  }

  // When doing a SAML sign in, this email check may result in a false
  // positive.  This happens when the user types one email address in the
  // gaia sign in page, but signs in to a different account in the SAML sign in
  // page.
  std::string default_email;
  std::string validate_email;
  if (net::GetValueForKeyInQuery(params.url, "email", &default_email) &&
      net::GetValueForKeyInQuery(params.url, "validateEmail",
                                 &validate_email) &&
      validate_email == "1") {
    if (!gaia::AreEmailsSame(params.email, default_email)) {
      if (params.handler) {
        params.handler->HandleLoginError(
            l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
                                      base::UTF8ToUTF16(default_email)));
      }
      return;
    }
  }

  signin_metrics::AccessPoint access_point =
      signin::GetAccessPointForPromoURL(params.url);
  signin_metrics::Reason reason =
      signin::GetSigninReasonForPromoURL(params.url);
  LogHistogramValue(signin_metrics::HISTOGRAM_ACCEPTED);
  bool switch_to_advanced =
      params.choose_what_to_sync &&
      (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS);
  LogHistogramValue(
      switch_to_advanced ? signin_metrics::HISTOGRAM_WITH_ADVANCED :
                           signin_metrics::HISTOGRAM_WITH_DEFAULTS);

  CanOfferFor can_offer_for = CAN_OFFER_FOR_ALL;
  switch (reason) {
    case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT:
      can_offer_for = CAN_OFFER_FOR_SECONDARY_ACCOUNT;
      break;
    case signin_metrics::Reason::REASON_REAUTHENTICATION:
    case signin_metrics::Reason::REASON_UNLOCK: {
      std::string primary_username =
          SigninManagerFactory::GetForProfile(profile)
              ->GetAuthenticatedAccountInfo()
              .email;
      if (!gaia::AreEmailsSame(default_email, primary_username))
        can_offer_for = CAN_OFFER_FOR_SECONDARY_ACCOUNT;
      break;
    }
    default:
      // No need to change |can_offer_for|.
      break;
  }

  std::string error_msg;
  bool can_offer = CanOffer(profile, can_offer_for, params.gaia_id,
                            params.email, &error_msg);
  if (!can_offer) {
    if (params.handler)
      params.handler->HandleLoginError(error_msg);
    return;
  }

  AboutSigninInternals* about_signin_internals =
      AboutSigninInternalsFactory::GetForProfile(profile);
  about_signin_internals->OnAuthenticationResultReceived("Successful");

  SigninClient* signin_client =
      ChromeSigninClientFactory::GetForProfile(profile);
  std::string signin_scoped_device_id =
      signin_client->GetSigninScopedDeviceId();
  base::WeakPtr<InlineLoginHandlerImpl> handler_weak_ptr;
  if (params.handler)
    handler_weak_ptr = params.handler->GetWeakPtr();

  // InlineSigninHelper will delete itself.
  new InlineSigninHelper(handler_weak_ptr,
                         params.partition->GetURLRequestContext(), profile,
                         params.url,
                         params.email, params.gaia_id, params.password,
                         params.session_index, params.auth_code,
                         signin_scoped_device_id,
                         params.choose_what_to_sync,
                         params.confirm_untrusted_signin);

  // If opened from user manager to reauthenticate, make sure the user manager
  // is closed and that the profile is marked as unlocked.
  if (!params.profile_path.empty()) {
    UserManager::Hide();
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    if (profile_manager) {
      ProfileAttributesEntry* entry;
      if (profile_manager->GetProfileInfoCache()
            .GetProfileAttributesWithPath(params.profile_path, &entry)) {
        entry->SetIsSigninRequired(false);
      }
    }
  }

  if (params.handler)
    params.handler->
        web_ui()->CallJavascriptFunction("inline.login.closeDialog");
}

void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg) {
  SyncStarterCallback(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);

  Browser* browser = GetDesktopBrowser();
  if (browser && !error_msg.empty()) {
    LoginUIServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()))->
        DisplayLoginResult(browser, base::UTF8ToUTF16(error_msg));
  }
}

Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
  Browser* browser = chrome::FindBrowserWithWebContents(
      web_ui()->GetWebContents());
  if (!browser) {
    browser = chrome::FindLastActiveWithProfile(
        Profile::FromWebUI(web_ui()), chrome::GetActiveDesktop());
  }
  return browser;
}

void InlineLoginHandlerImpl::SyncStarterCallback(
    OneClickSigninSyncStarter::SyncSetupResult result) {
  content::WebContents* contents = web_ui()->GetWebContents();

  if (contents->GetController().GetPendingEntry()) {
    // Do nothing if a navigation is pending, since this call can be triggered
    // from DidStartLoading. This avoids deleting the pending entry while we are
    // still navigating to it. See crbug/346632.
    return;
  }

  const GURL& current_url = contents->GetLastCommittedURL();
  signin_metrics::AccessPoint access_point =
      signin::GetAccessPointForPromoURL(current_url);
  bool auto_close = signin::IsAutoCloseEnabledInURL(current_url);

  if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE) {
    RedirectToNtpOrAppsPage(contents, access_point);
  } else if (auto_close) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::Bind(&InlineLoginHandlerImpl::CloseTab,
                   weak_factory_.GetWeakPtr(),
                   signin::ShouldShowAccountManagement(current_url)));
  } else {
    RedirectToNtpOrAppsPageIfNecessary(contents, access_point);
  }
}

void InlineLoginHandlerImpl::CloseTab(bool show_account_management) {
  content::WebContents* tab = web_ui()->GetWebContents();
  Browser* browser = chrome::FindBrowserWithWebContents(tab);
  if (browser) {
    TabStripModel* tab_strip_model = browser->tab_strip_model();
    if (tab_strip_model) {
      int index = tab_strip_model->GetIndexOfWebContents(tab);
      if (index != TabStripModel::kNoTab) {
        tab_strip_model->ExecuteContextMenuCommand(
            index, TabStripModel::CommandCloseTab);
      }
    }

    if (show_account_management) {
      browser->window()->ShowAvatarBubbleFromAvatarButton(
          BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT,
          signin::ManageAccountsParams(),
          signin_metrics::AccessPoint::ACCESS_POINT_AVATAR_BUBBLE_SIGN_IN);
    }
  }
}


text:
package org.apache.isis.viewer.wicket.ui.components.collection.selector;

import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons;

import java.util.List;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.isis.core.commons.lang.StringExtensions;
import org.apache.isis.viewer.wicket.model.hints.IsisUiHintEvent;
import org.apache.isis.viewer.wicket.model.hints.UiHintContainer;
import org.apache.isis.viewer.wicket.model.hints.UiHintPathSignificant;
import org.apache.isis.viewer.wicket.model.models.EntityCollectionModel;
import org.apache.isis.viewer.wicket.model.models.EntityModel;
import org.apache.isis.viewer.wicket.ui.CollectionContentsAsFactory;
import org.apache.isis.viewer.wicket.ui.ComponentFactory;
import org.apache.isis.viewer.wicket.ui.panels.PanelAbstract;
import org.apache.isis.viewer.wicket.ui.util.CssClassAppender;

/**
 * Provides a list of links for selecting other views that support
 * {@link org.apache.isis.viewer.wicket.ui.ComponentType#COLLECTION_CONTENTS} with a backing
 * {@link org.apache.isis.viewer.wicket.model.models.EntityCollectionModel}.
 */
public class CollectionSelectorPanel
        extends PanelAbstract<EntityCollectionModel> implements UiHintPathSignificant {

    private static final long serialVersionUID = 1L;

    private static final String ID_VIEWS = "views";
    private static final String ID_VIEW_LIST = "viewList";
    private static final String ID_VIEW_LINK = "viewLink";
    private static final String ID_VIEW_ITEM = "viewItem";
    private static final String ID_VIEW_ITEM_TITLE = "viewItemTitle";
    private static final String ID_VIEW_ITEM_ICON = "viewItemIcon";

    private static final String ID_VIEW_BUTTON_TITLE = "viewButtonTitle";
    private static final String ID_VIEW_BUTTON_ICON = "viewButtonIcon";

    private final CollectionSelectorHelper selectorHelper;

    private ComponentFactory selectedComponentFactory;

    public CollectionSelectorPanel(final String id, final EntityCollectionModel model) {
        super(id, model);
        selectorHelper = new CollectionSelectorHelper(model, getComponentFactoryRegistry());
    }

    /**
     * Build UI only after added to parent.
     */
    public void onInitialize() {
        super.onInitialize();
        addDropdown();
    }

    private void addDropdown() {
        final List<ComponentFactory> componentFactories = selectorHelper.getComponentFactories();
        final int selected = selectorHelper.honourViewHintElseDefault(this);

        // selector
        if (componentFactories.size() <= 1) {
            permanentlyHide(ID_VIEWS);
        } else {
            final Model<ComponentFactory> componentFactoryModel = new Model<>();

            this.selectedComponentFactory = componentFactories.get(selected);
            componentFactoryModel.setObject(this.selectedComponentFactory);

            final WebMarkupContainer views = new WebMarkupContainer(ID_VIEWS);

            final Label viewButtonTitle = new Label(ID_VIEW_BUTTON_TITLE, "Hidden");
            views.addOrReplace(viewButtonTitle);

            final Label viewButtonIcon = new Label(ID_VIEW_BUTTON_ICON, "");
            views.addOrReplace(viewButtonIcon);

            final WebMarkupContainer container = new WebMarkupContainer(ID_VIEW_LIST);

            views.addOrReplace(container);
            views.setOutputMarkupId(true);

            this.setOutputMarkupId(true);

            final ListView<ComponentFactory> listView = new ListView<ComponentFactory>(ID_VIEW_ITEM, componentFactories) {

                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(ListItem<ComponentFactory> item) {

                    final int underlyingViewNum = item.getIndex();

                    final ComponentFactory componentFactory = item.getModelObject();
                    final AbstractLink link = new AjaxLink<Void>(ID_VIEW_LINK) {
                        private static final long serialVersionUID = 1L;
                        @Override
                        public void onClick(AjaxRequestTarget target) {
                            CollectionSelectorPanel linksSelectorPanel = CollectionSelectorPanel.this;
                            linksSelectorPanel.setViewHintAndBroadcast(underlyingViewNum, target);

                            linksSelectorPanel.selectedComponentFactory = componentFactory;
                            target.add(linksSelectorPanel, views);
                        }

                        @Override
                        protected void onComponentTag(ComponentTag tag) {
                            super.onComponentTag(tag);
                            Buttons.fixDisabledState(this, tag);
                        }
                    };

                    IModel<String> title = nameFor(componentFactory);
                    Label viewItemTitleLabel = new Label(ID_VIEW_ITEM_TITLE, title);
                    link.add(viewItemTitleLabel);

                    Label viewItemIcon = new Label(ID_VIEW_ITEM_ICON, "");
                    link.add(viewItemIcon);

                    boolean isEnabled = componentFactory != CollectionSelectorPanel.this.selectedComponentFactory;
                    if (!isEnabled) {
                        viewButtonTitle.setDefaultModel(title);
                        IModel<String> cssClass = cssClassFor(componentFactory, viewButtonIcon);
                        viewButtonIcon.add(AttributeModifier.replace("class", "ViewLinkItem " + cssClass.getObject()));
                        link.setVisible(false);
                    } else {
                        IModel<String> cssClass = cssClassFor(componentFactory, viewItemIcon);
                        viewItemIcon.add(new CssClassAppender(cssClass));
                    }

                    item.add(link);
                }

                private IModel<String> cssClassFor(final ComponentFactory componentFactory, Label viewIcon) {
                    IModel<String> cssClass = null;
                    if (componentFactory instanceof CollectionContentsAsFactory) {
                        CollectionContentsAsFactory collectionContentsAsFactory = (CollectionContentsAsFactory) componentFactory;
                        cssClass = collectionContentsAsFactory.getCssClass();
                        viewIcon.setDefaultModelObject("");
                        viewIcon.setEscapeModelStrings(true);
                    }
                    if (cssClass == null) {
                        String name = componentFactory.getName();
                        cssClass = Model.of(StringExtensions.asLowerDashed(name));
                        // Small hack: if there is no specific CSS class then we assume that background-image is used
                        // the span.ViewItemLink should have some content to show it
                        // FIX: find a way to do this with CSS (width and height don't seems to help)
                        viewIcon.setDefaultModelObject("     ");
                        viewIcon.setEscapeModelStrings(false);
                    }
                    return cssClass;
                }

                private IModel<String> nameFor(final ComponentFactory componentFactory) {
                    IModel<String> name = null;
                    if (componentFactory instanceof CollectionContentsAsFactory) {
                        CollectionContentsAsFactory collectionContentsAsFactory = (CollectionContentsAsFactory) componentFactory;
                        name = collectionContentsAsFactory.getTitleLabel();
                    }
                    if (name == null) {
                        name = Model.of(componentFactory.getName());
                    }
                    return name;
                }
            };
            container.add(listView);
            addOrReplace(views);
        }
    }

    protected void setViewHintAndBroadcast(int viewNum, AjaxRequestTarget target) {
        final UiHintContainer uiHintContainer = getUiHintContainer(getModel().isParented()? EntityModel.class: EntityCollectionModel.class);
        if(uiHintContainer == null) {
            return;
        }
        uiHintContainer.setHint(CollectionSelectorPanel.this, CollectionSelectorHelper.UIHINT_EVENT_VIEW_KEY, ""+viewNum);
        send(getPage(), Broadcast.EXACT, new IsisUiHintEvent(uiHintContainer, target));
    }
}


text:
package il.stqa.pft.addressbook.tests;

import il.stqa.pft.addressbook.model.GroupData;
import il.stqa.pft.addressbook.model.Groups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;

/**
 * Created by Irena on 8/22/2016.
 */
public class GroupModificationTests extends TestBase {

  /*@BeforeMethod
  public void ensurePreconditions() {
    app.goTo().groupPage();
    if (app.group().all().size() == 0) {
      app.group().create(new GroupData().withName("test1"));
    }
  }

  @Test
  public void testGroupModification() {
    Groups before = app.group().all();
    GroupData modifiedGroup = before.iterator().next();
    // int index = before.size()- 1;
    GroupData group = new GroupData()
            .withId(modifiedGroup.getId()).withName("test1").withHeader("test2").withFooter("test3");
    app.group().modify(group);
    Groups after = app.group().all();
    assertEquals(after.size(), before.size());

    //before.remove(modifiedGroup);
    //before.add(group);
    //  Comparator<? super GroupData> byId = (g1, g2) -> Integer.compare(g1.getId(), g2.getId());
    //   before.sort(byId);
    //   after.sort(byId);
    //Assert.assertEquals(before, after);
    assertThat(after, equalTo(before.withOut(modifiedGroup).withAdded(group)));
  }

}*/

  @BeforeMethod
  public void ensurePreconditions() {
    if (app.db().groups().size() == 0){
      app.goTo().groupPage();
      app.group().create(new GroupData().withName("test1"));
    }
  }

  @Test
  public void testGroupModification() {
    Groups before = app.db().groups();
    GroupData modifiedGroup = before.iterator().next();
    // int index = before.size()- 1;
    GroupData group = new GroupData()
            .withId(modifiedGroup.getId()).withName("test1").withHeader("test2").withFooter("test3");
    app.goTo().groupPage();
    app.group().modify(group);
    Groups after = app.db().groups();
    assertEquals(after.size(), before.size());

    //before.remove(modifiedGroup);
    //before.add(group);
    //  Comparator<? super GroupData> byId = (g1, g2) -> Integer.compare(g1.getId(), g2.getId());
    //   before.sort(byId);
    //   after.sort(byId);
    //Assert.assertEquals(before, after);
    assertThat(after, equalTo(before.withOut(modifiedGroup).withAdded(group)));
    verifyGroupListInUI();
  }

}


text:
/****************************************************************************
 * board/artik05x/src/artik05x.h
 *
 *   Copyright (C) 2013 Gregory Nutt. All rights reserved.
 *   Authors: Gregory Nutt <gnutt@nuttx.org>
 *            Laurent Latil <laurent@latil.nom.fr>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
#ifndef __ARCH_ARM_SRC_ARTIK05X_SRC_ARTIK05X_H__
#define __ARCH_ARM_SRC_ARTIK05X_SRC_ARTIK05X_H__

/****************************************************************************
 * Included Files
 ****************************************************************************/

#ifdef CONFIG_MTD_CONFIG
enum configdata_id {
	/* Application-specific */
	ARTIK05X_CONFIGDATA_APPLICATION = 0x0000,

	/* Platform-specific */
	ARTIK05X_CONFIGDATA_PLATFORM = 0xff00,
	ARTIK05X_CONFIGDATA_WIFI_NVRAM,
};
#endif

#endif /* __ARCH_ARM_SRC_ARTIK05X_SRC_ARTIK05X_H__ */


text:
{{ include ('partials/page-header.html', {
	    title: 'Advanced clinic search',
	    tagline: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet neque vestibulum, commodo lacus ornare, tincidunt elit. Maecenas id lorem eget quam pretium blandit. Aenean urna lectus, fermentum eget suscipit a, condimentum a nisi. Nulla ultricies erat lectus, ac bibendum leo posuere nec.',
	}) }}

		Change search criteria

			<form>

						    Search by postcode

> Why is this important?

						    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Postcode / Region">

						    Do you know the name of the clinic you're looking for?

						    <input type="text" class="form-control" id="exampleInputName2" placeholder="Clinic name">

						    Distance from postcode

0

								  		<button type="button" class="btn btn-default">-</button>

								  		<button type="button" class="btn btn-default">+</button>

Clinic Type

						    	<input type="checkbox" value="">
						    	Clinic Type

						    	<input type="checkbox" value="">
						    	IUI

						    	<input checked type="checkbox" value="">
						    	IVF

						    	<input type="checkbox" value="">
						    	Donor Conception

						    	<input type="checkbox" value="">
						    	Embryo testing

						    	<input type="checkbox" value="">
						    	Satellite & transport

						    	<input type="checkbox" value="">
						    	Research

Facilities

						    	<input type="checkbox" value="">
						    	Parking

						    	<input type="checkbox" value="">
						    	Disabled access

				  Search terms

Treatments

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs1" value="option1" >
						    	IVF

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs2" value="option2">
						    	ICSI

						   		<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs3" value="option3" >
						    	Surgical sperm collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs4" value="option4" >
						    	Ovarian tissue collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs5" value="option5">
						    	In vitro maturation

Screening services

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs6" value="option1" >
						    	IVF

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs7" value="option2">
						    	ICSI

						   		<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs8" value="option3" >
						    	Surgical sperm collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs9" value="option4" >
						    	Ovarian tissue collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs10" value="option5">
						    	In vitro maturation

Donor services

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs11" value="option1" >
						    	IVF

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs12" value="option2">
						    	ICSI

						   		<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs13" value="option3" >
						    	Surgical sperm collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionscheckboxs14" value="option4" >
						    	Ovarian tissue collection

						    	<input type="checkbox" checked name="optionscheckboxs" id="optionsRadios15" value="option5">
						    	In vitro maturation

							    Please enter additional treatments you require

								<input type="text" class="form-control typeahead" name="search" id="typeahead" placeholder="Treatment" >

					Search for clinic

				Back to basic search
			</form>

Your search found 5 clinics

Distance

Grid

Map

					{{ include ('partials/clinic-listing.html',{
							clinics: [
								{
									title: "Barts Health Centre for Reproduction Medicine",
									type: "Treatment Centre",
									treatments: [
										{
											tag: "IVF"
										},
										{
											tag: "ICSI"
										},
										{
											tag: "IUI"
										}
									],
									review_rating: "4",
									reviewers: "159",
									patient_rating : "green",
									embryo_rating : "green",
									it_rating : "amber",
									experience_rating : "red",
									success_rate : "30",
									image: "barts.jpeg"
								},
								{
									title: "Homerton Fertility Centre",
									type: "Treatment Centre",
									treatments: [
										{
											tag: "IVF"
										},
										{
											tag: "ICSI"
										},
										{
											tag: "IUI"
										}
									],
									review_rating: "3",
									reviewers: "84",
									patient_rating : "green",
									embryo_rating : "green",
									it_rating : "amber",
									experience_rating : "green",
									success_rate : "23",
									image: "homerton.jpeg"
								},
								{
									title: "The Whittington Hospital Fertility Unit",
									type: "Treatment Centre",
									treatments: [
										{
											tag: "IVF"
										},
										{
											tag: "ICSI"
										},
										{
											tag: "IUI"
										}
									],
									review_rating: "5",
									reviewers: "20",
									patient_rating : "green",
									embryo_rating : "amber",
									it_rating : "amber",
									experience_rating : "red",
									success_rate : "30",
									image: "whittington.jpeg"
								},
								{
									title: "North Middlesex University Hospital (Reproductive Medicines Unit)",
									type: "Treatment Centre",
									treatments: [
										{
											tag: "IVF"
										},
										{
											tag: "ICSI"
										},
										{
											tag: "IUI"
										}
									],
									review_rating: "4",
									reviewers: "25",
									patient_rating : "green",
									embryo_rating : "amber",
									it_rating : "amber",
									experience_rating : "red",
									success_rate : "70",
									image: "middlesex.jpeg"
								},
								{
									title: "Reproductive Medicine Unit",
									type: "Treatment Centre",
									treatments: [
										{
											tag: "IVF"
										},
										{
											tag: "ICSI"
										},
										{
											tag: "IUI"
										}
									],
									review_rating: "3",
									reviewers: "63",
									patient_rating : "green",
									embryo_rating : "amber",
									it_rating : "amber",
									experience_rating : "red",
									success_rate : "64",
									image: "reproductive-medicine.jpeg"
								}
							]

						})
					}}

			  			Map View