text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// Filing Returns Model
    /// </summary>
    public class FilingReturnModel
    {
        /// <summary>
        /// The unique ID number of this filing return.
        /// </summary>
        public Int64? id { get; set; }

        /// <summary>
        /// The region id that this return belongs too
        /// </summary>
        public Int64? filingRegionId { get; set; }

        /// <summary>
        /// The unique ID number of the filing calendar associated with this return.
        /// </summary>
        public Int64? filingCalendarId { get; set; }

        /// <summary>
        /// The resourceFileId of the return. Will be null if not available.
        /// </summary>
        public Int64? resourceFileId { get; set; }

        /// <summary>
        /// Tax Authority ID of this return
        /// </summary>
        public Int32? taxAuthorityId { get; set; }

        /// <summary>
        /// The current status of the filing return.
        /// </summary>
        public FilingStatusId? status { get; set; }

        /// <summary>
        /// The filing frequency of the return.
        /// </summary>
        public FilingFrequencyId? filingFrequency { get; set; }

        /// <summary>
        /// The date the return was filed by Avalara.
        /// </summary>
        public DateTime? filedDate { get; set; }

        /// <summary>
        /// The start date of this return
        /// </summary>
        public DateTime? startPeriod { get; set; }

        /// <summary>
        /// The end date of this return
        /// </summary>
        public DateTime? endPeriod { get; set; }

        /// <summary>
        /// The sales amount.
        /// </summary>
        public Decimal? salesAmount { get; set; }

        /// <summary>
        /// The filing type of the return.
        /// </summary>
        public FilingTypeId? filingType { get; set; }

        /// <summary>
        /// The name of the form.
        /// </summary>
        public String formName { get; set; }

        /// <summary>
        /// The remittance amount of the return.
        /// </summary>
        public Decimal? remitAmount { get; set; }

        /// <summary>
        /// The unique code of the form.
        /// </summary>
        public String formCode { get; set; }

        /// <summary>
        /// A description for the return.
        /// </summary>
        public String description { get; set; }

        /// <summary>
        /// The taxable amount.
        /// </summary>
        public Decimal? taxableAmount { get; set; }

        /// <summary>
        /// The tax amount.
        /// </summary>
        public Decimal? taxAmount { get; set; }

        /// <summary>
        /// The amount collected by avalara for this return
        /// </summary>
        public Decimal? collectAmount { get; set; }

        /// <summary>
        /// The tax due amount.
        /// </summary>
        public Decimal? taxDueAmount { get; set; }

        /// <summary>
        /// The non-taxable amount.
        /// </summary>
        public Decimal? nonTaxableAmount { get; set; }

        /// <summary>
        /// The non-taxable due amount.
        /// </summary>
        public Decimal? nonTaxableDueAmount { get; set; }

        /// <summary>
        /// Consumer use tax liability during the period.
        /// </summary>
        public Decimal? consumerUseTaxAmount { get; set; }

        /// <summary>
        /// Consumer use tax liability accrued during the period.
        /// </summary>
        public Decimal? consumerUseTaxDueAmount { get; set; }

        /// <summary>
        /// Consumer use non-taxable amount.
        /// </summary>
        public Decimal? consumerUseNonTaxableAmount { get; set; }

        /// <summary>
        /// Consumer use taxable amount.
        /// </summary>
        public Decimal? consumerUseTaxableAmount { get; set; }

        /// <summary>
        /// Total amount of adjustments on this return
        /// </summary>
        public Decimal? totalAdjustments { get; set; }

        /// <summary>
        /// The amount of sales excluded from the liability calculation
        /// </summary>
        public Decimal? excludedSalesAmount { get; set; }

        /// <summary>
        /// The amount of non-taxable sales excluded from the liability calculation
        /// </summary>
        public Decimal? excludedNonTaxableAmount { get; set; }

        /// <summary>
        /// The amount of tax excluded from the liability calculation
        /// </summary>
        public Decimal? excludedTaxAmount { get; set; }

        /// <summary>
        /// The amount of carry over sales applied to the liability calculation
        /// </summary>
        public Decimal? carryOverSalesAmount { get; set; }

        /// <summary>
        /// The amount of carry over non taxable sales applied to the liability calculation
        /// </summary>
        public Decimal? carryOverNonTaxableAmount { get; set; }

        /// <summary>
        /// The amount of carry over sales tax applied to the liability calculation
        /// </summary>
        public Decimal? carryOverTaxAmount { get; set; }

        /// <summary>
        /// The amount of carry over consumer use tax applied to the liability calculation
        /// </summary>
        public Decimal? carryOverConsumerUseTaxAmount { get; set; }

        /// <summary>
        /// The total amount of total tax accrued in the current active period
        /// </summary>
        public Decimal? taxAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of sales accrued in the current active period
        /// </summary>
        public Decimal? salesAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of nontaxable sales accrued in the current active period
        /// </summary>
        public Decimal? nonTaxableAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of taxable sales accrued in the current active period
        /// </summary>
        public Decimal? taxableAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of sales tax accrued in the current active period
        /// </summary>
        public Decimal? salesTaxAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of sellers use tax accrued in the current active period
        /// </summary>
        public Decimal? sellersUseTaxAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of consumer use tax accrued in the current active period
        /// </summary>
        public Decimal? consumerUseTaxAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of consumer use taxable sales accrued in the current active period
        /// </summary>
        public Decimal? consumerUseTaxableAccrualAmount { get; set; }

        /// <summary>
        /// The total amount of consumer use non taxable sales accrued in the current active period
        /// </summary>
        public Decimal? consumerUseNonTaxableAccrualAmount { get; set; }

        /// <summary>
        /// The Adjustments for this return.
        /// </summary>
        public List<FilingAdjustmentModel> adjustments { get; set; }

        /// <summary>
        /// Total amount of augmentations on this return
        /// </summary>
        public Decimal? totalAugmentations { get; set; }

        /// <summary>
        /// The Augmentations for this return.
        /// </summary>
        public List<FilingAugmentationModel> augmentations { get; set; }

        /// <summary>
        /// Total amount of payments on this return
        /// </summary>
        public Decimal? totalPayments { get; set; }

        /// <summary>
        /// The payments for this return.
        /// </summary>
        public List<FilingPaymentModel> payments { get; set; }

        /// <summary>
        /// Accrual type of the return
        /// </summary>
        public AccrualType? accrualType { get; set; }

        /// <summary>
        /// The month of the filing period for this tax filing.
        /// The filing period represents the year and month of the last day of taxes being reported on this filing.
        /// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
        /// </summary>
        public Int32? month { get; set; }

        /// <summary>
        /// The year of the filing period for this tax filing.
        /// The filing period represents the year and month of the last day of taxes being reported on this filing.
        /// For example, an annual tax filing for Jan-Dec 2015 would have a filing period of Dec 2015.
        /// </summary>
        public Int32? year { get; set; }

        /// <summary>
        /// The attachments for this return.
        /// </summary>
        public List<FilingAttachmentModel> attachments { get; set; }

        /// <summary>
        /// The excluded carry over credit documents
        /// </summary>
        public FilingReturnCreditModel excludedCarryOverCredits { get; set; }

        /// <summary>
        /// The applied carry over credit documents
        /// </summary>
        public FilingReturnCreditModel appliedCarryOverCredits { get; set; }

        /// <summary>
        /// The date when this record was created.
        /// </summary>
        public DateTime? createdDate { get; set; }

        /// <summary>
        /// The User ID of the user who created this record.
        /// </summary>
        public Int32? createdUserId { get; set; }

        /// <summary>
        /// The date/time when this record was last modified.
        /// </summary>
        public DateTime? modifiedDate { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
<?php

use Twig\Node\Expression\Test\ConstantTest;

class_exists('Twig\Node\Expression\Test\ConstantTest');

if (\false) {
    class Twig_Node_Expression_Test_Constant extends ConstantTest
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Observable } from "core/Misc/observable";
import { Tools } from "core/Misc/tools";
// eslint-disable-next-line import/no-internal-modules
import { isUrl, camelToKebab, kebabToCamel, deepmerge } from "../helper/index";

import * as Handlebars from "handlebars";
import { EventManager } from "./eventManager";
import type { ITemplateConfiguration } from "../configuration/interfaces/templateConfiguration";
import type { IFileRequest } from "core/Misc/fileRequest";

/**
 * The object sent when an event is triggered
 */
export interface EventCallback {
    event: Event;
    template: Template;
    selector: string;
    payload?: any;
}

/**
 * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
 * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
 */
export class TemplateManager {
    /**
     * Will be triggered when any template is initialized
     */
    public onTemplateInit: Observable<Template>;
    /**
     * Will be triggered when any template is fully loaded
     */
    public onTemplateLoaded: Observable<Template>;
    /**
     * Will be triggered when a template state changes
     */
    public onTemplateStateChange: Observable<Template>;
    /**
     * Will be triggered when all templates finished loading
     */
    public onAllLoaded: Observable<TemplateManager>;
    /**
     * Will be triggered when any event on any template is triggered.
     */
    public onEventTriggered: Observable<EventCallback>;

    /**
     * This template manager's event manager. In charge of callback registrations to native event types
     */
    public eventManager: EventManager;

    private _templates: { [name: string]: Template };

    constructor(public containerElement: Element) {
        this._templates = {};

        this.onTemplateInit = new Observable<Template>();
        this.onTemplateLoaded = new Observable<Template>();
        this.onTemplateStateChange = new Observable<Template>();
        this.onAllLoaded = new Observable<TemplateManager>();
        this.onEventTriggered = new Observable<EventCallback>();

        this.eventManager = new EventManager(this);
    }

    /**
     * Initialize the template(s) for the viewer. Called bay the Viewer class
     * @param templates the templates to be used to initialize the main template
     */
    public initTemplate(templates: { [key: string]: ITemplateConfiguration }) {
        const internalInit = (dependencyMap: any, name: string, parentTemplate?: Template) => {
            //init template
            const template = this._templates[name];

            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            Object.keys(dependencyMap).map((childName) => {
                return internalInit(dependencyMap[childName], childName, template);
            });

            // register the observers
            //template.onLoaded.add(() => {
            const addToParent = () => {
                const lastElements = parentTemplate && parentTemplate.parent.querySelectorAll(camelToKebab(name) as keyof HTMLElementTagNameMap);
                const containingElement = (lastElements && lastElements.length && lastElements.item(lastElements.length - 1)) || this.containerElement;
                template.appendTo(<HTMLElement>containingElement);
                this._checkLoadedState();
            };

            if (parentTemplate && !parentTemplate.parent) {
                parentTemplate.onAppended.add(() => {
                    addToParent();
                });
            } else {
                addToParent();
            }
            //});

            return template;
        };

        //build the html tree
        return this._buildHTMLTree(templates).then((htmlTree) => {
            if (this._templates["main"]) {
                internalInit(htmlTree, "main");
            } else {
                this._checkLoadedState();
            }
            return;
        });
    }

    /**
     *
     * This function will create a simple map with child-dependencies of the template html tree.
     * It will compile each template, check if its children exist in the configuration and will add them if they do.
     * It is expected that the main template will be called main!
     *
     * @param templates
     */
    private _buildHTMLTree(templates: { [key: string]: ITemplateConfiguration }): Promise<object> {
        const promises: Array<Promise<Template | boolean>> = Object.keys(templates).map((name) => {
            // if the template was overridden
            if (!templates[name]) {
                return Promise.resolve(false);
            }
            // else - we have a template, let's do our job!
            const template = new Template(name, templates[name]);
            template.onLoaded.add(() => {
                this.onTemplateLoaded.notifyObservers(template);
            });
            template.onStateChange.add(() => {
                this.onTemplateStateChange.notifyObservers(template);
            });
            this.onTemplateInit.notifyObservers(template);
            // make sure the global onEventTriggered is called as well
            template.onEventTriggered.add((eventData) => this.onEventTriggered.notifyObservers(eventData));
            this._templates[name] = template;
            return template.initPromise;
        });

        return Promise.all(promises).then(() => {
            const templateStructure = {};
            // now iterate through all templates and check for children:
            const buildTree = (parentObject: any, name: string) => {
                this._templates[name].isInHtmlTree = true;
                const childNodes = this._templates[name].getChildElements().filter((n) => !!this._templates[n]);
                childNodes.forEach((element) => {
                    parentObject[element] = {};
                    buildTree(parentObject[element], element);
                });
            };
            if (this._templates["main"]) {
                buildTree(templateStructure, "main");
            }
            return templateStructure;
        });
    }

    /**
     * Get the canvas in the template tree.
     * There must be one and only one canvas inthe template.
     */
    public getCanvas(): HTMLCanvasElement | null {
        return this.containerElement.querySelector("canvas");
    }

    /**
     * Get a specific template from the template tree
     * @param name the name of the template to load
     */
    public getTemplate(name: string): Template | undefined {
        return this._templates[name];
    }

    private _checkLoadedState() {
        const done =
            Object.keys(this._templates).length === 0 ||
            Object.keys(this._templates).every((key) => {
                return (this._templates[key].isLoaded && !!this._templates[key].parent) || !this._templates[key].isInHtmlTree;
            });

        if (done) {
            this.onAllLoaded.notifyObservers(this);
        }
    }

    /**
     * Dispose the template manager
     */
    public dispose() {
        // dispose all templates
        Object.keys(this._templates).forEach((template) => {
            this._templates[template].dispose();
        });
        this._templates = {};
        this.eventManager.dispose();

        this.onTemplateInit.clear();
        this.onAllLoaded.clear();
        this.onEventTriggered.clear();
        this.onTemplateLoaded.clear();
        this.onTemplateStateChange.clear();
    }
}

// register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
Handlebars.registerHelper("eachInMap", function (map, block) {
    let out = "";
    Object.keys(map).map(function (prop) {
        const data = map[prop];
        if (typeof data === "object") {
            data.id = data.id || prop;
            out += block.fn(data);
        } else {
            out += block.fn({ id: prop, value: data });
        }
    });
    return out;
});

Handlebars.registerHelper("add", function (a, b) {
    const out = a + b;
    return out;
});

Handlebars.registerHelper("eq", function (a, b) {
    const out = a == b;
    return out;
});

Handlebars.registerHelper("or", function (a, b) {
    const out = a || b;
    return out;
});

Handlebars.registerHelper("not", function (a) {
    const out = !a;
    return out;
});

Handlebars.registerHelper("count", function (map) {
    return map.length;
});

Handlebars.registerHelper("gt", function (a, b) {
    const out = a > b;
    return out;
});

/**
 * This class represents a single template in the viewer's template tree.
 * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
 * A template is injected using the template manager in the correct position.
 * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
 *
 * For further information please refer to the documentation page, https://doc.babylonjs.com
 */
export class Template {
    /**
     * Will be triggered when the template is loaded
     */
    public onLoaded: Observable<Template>;
    /**
     * will be triggered when the template is appended to the tree
     */
    public onAppended: Observable<Template>;
    /**
     * Will be triggered when the template's state changed (shown, hidden)
     */
    public onStateChange: Observable<Template>;
    /**
     * Will be triggered when an event is triggered on ths template.
     * The event is a native browser event (like mouse or pointer events)
     */
    public onEventTriggered: Observable<EventCallback>;

    public onParamsUpdated: Observable<Template>;

    public onHTMLRendered: Observable<Template>;

    /**
     * is the template loaded?
     */
    public isLoaded: boolean;
    /**
     * This is meant to be used to track the show and hide functions.
     * This is NOT (!!) a flag to check if the element is actually visible to the user.
     */
    public isShown: boolean;

    /**
     * Is this template a part of the HTML tree (the template manager injected it)
     */
    public isInHtmlTree: boolean;

    /**
     * The HTML element containing this template
     */
    public parent: HTMLElement;

    /**
     * A promise that is fulfilled when the template finished loading.
     */
    public initPromise: Promise<Template>;

    private _fragment: DocumentFragment | Element;
    private _addedFragment: DocumentFragment | Element;
    private _htmlTemplate: string;
    private _rawHtml: string;

    private _loadRequests: Array<IFileRequest>;

    constructor(public name: string, private _configuration: ITemplateConfiguration) {
        this.onLoaded = new Observable<Template>();
        this.onAppended = new Observable<Template>();
        this.onStateChange = new Observable<Template>();
        this.onEventTriggered = new Observable<EventCallback>();
        this.onParamsUpdated = new Observable<Template>();
        this.onHTMLRendered = new Observable<Template>();

        this._loadRequests = [];

        this.isLoaded = false;
        this.isShown = false;
        this.isInHtmlTree = false;

        const htmlContentPromise = this._getTemplateAsHtml(_configuration);

        this.initPromise = htmlContentPromise.then((htmlTemplate) => {
            if (htmlTemplate) {
                this._htmlTemplate = htmlTemplate;
                const compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: this._configuration.params && !!this._configuration.params.noEscape });
                const config = this._configuration.params || {};
                this._rawHtml = compiledTemplate(config);
                try {
                    this._fragment = document.createRange().createContextualFragment(this._rawHtml);
                } catch (e) {
                    const test = document.createElement(this.name);
                    test.innerHTML = this._rawHtml;
                    this._fragment = test;
                }
                this.isLoaded = true;
                this.isShown = true;
                this.onLoaded.notifyObservers(this);
            }
            return this;
        });
    }

    /**
     * Some templates have parameters (like background color for example).
     * The parameters are provided to Handlebars which in turn generates the template.
     * This function will update the template with the new parameters
     *
     * Note that when updating parameters the events will be registered again (after being cleared).
     *
     * @param params the new template parameters
     * @param append
     */
    public updateParams(params: { [key: string]: string | number | boolean | object }, append: boolean = true) {
        if (append) {
            this._configuration.params = deepmerge(this._configuration.params, params);
        } else {
            this._configuration.params = params;
        }
        // update the template
        if (this.isLoaded) {
            // this.dispose();
        }
        const compiledTemplate = Handlebars.compile(this._htmlTemplate);
        const config = this._configuration.params || {};
        this._rawHtml = compiledTemplate(config);
        try {
            this._fragment = document.createRange().createContextualFragment(this._rawHtml);
        } catch (e) {
            const test = document.createElement(this.name);
            test.innerHTML = this._rawHtml;
            this._fragment = test;
        }
        if (this.parent) {
            this.appendTo(this.parent, true);
        }
    }

    public redraw() {
        this.updateParams({});
    }

    /**
     * Get the template'S configuration
     */
    public get configuration(): ITemplateConfiguration {
        return this._configuration;
    }

    /**
     * A template can be a parent element for other templates or HTML elements.
     * This function will deliver all child HTML elements of this template.
     */
    public getChildElements(): Array<string> {
        const childrenArray: string[] = [];
        //Edge and IE don't support frage,ent.children
        let children: HTMLCollection | NodeListOf<Element> = this._fragment && this._fragment.children;
        if (!this._fragment) {
            const fragment = this.parent.querySelector(this.name);
            if (fragment) {
                children = fragment.querySelectorAll("*");
            }
        }
        if (!children) {
            // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
            children = this._fragment.querySelectorAll("*");
        }
        for (let i = 0; i < children.length; ++i) {
            const child = children.item(i);
            if (child) {
                childrenArray.push(kebabToCamel(child.nodeName.toLowerCase()));
            }
        }
        return childrenArray;
    }

    /**
     * Appending the template to a parent HTML element.
     * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
     * @param parent the parent to which the template is added
     * @param forceRemove if the parent already exists, shoud the template be removed from it?
     */
    public appendTo(parent: HTMLElement, forceRemove?: boolean) {
        if (this.parent) {
            if (forceRemove && this._addedFragment) {
                /*let fragement = this.parent.querySelector(this.name)
                if (fragement)
                    this.parent.removeChild(fragement);*/
                this.parent.innerHTML = "";
            } else {
                return;
            }
        }
        this.parent = parent;

        if (this._configuration.id) {
            this.parent.id = this._configuration.id;
        }
        if (this._fragment) {
            this.parent.appendChild(this._fragment);
            this._addedFragment = this._fragment;
        } else {
            this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
        }

        this.onHTMLRendered.notifyObservers(this);

        // appended only one frame after.
        setTimeout(() => {
            this._registerEvents();
            this.onAppended.notifyObservers(this);
        });
    }

    private _isShowing: boolean;
    private _isHiding: boolean;

    /**
     * Show the template using the provided visibilityFunction, or natively using display: flex.
     * The provided function returns a promise that should be fulfilled when the element is shown.
     * Since it is a promise async operations are more than possible.
     * See the default viewer for an opacity example.
     * @param visibilityFunction The function to execute to show the template.
     */
    public show(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
        if (this._isHiding) {
            return Promise.resolve(this);
        }
        return Promise.resolve()
            .then(() => {
                this._isShowing = true;
                if (visibilityFunction) {
                    return visibilityFunction(this);
                } else {
                    // flex? box? should this be configurable easier than the visibilityFunction?
                    this.parent.style.display = "flex";
                    // support old browsers with no flex:
                    if (this.parent.style.display !== "flex") {
                        this.parent.style.display = "";
                    }
                    return this;
                }
            })
            .then(() => {
                this.isShown = true;
                this._isShowing = false;
                this.onStateChange.notifyObservers(this);
                return this;
            });
    }

    /**
     * Hide the template using the provided visibilityFunction, or natively using display: none.
     * The provided function returns a promise that should be fulfilled when the element is hidden.
     * Since it is a promise async operations are more than possible.
     * See the default viewer for an opacity example.
     * @param visibilityFunction The function to execute to show the template.
     */
    public hide(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
        if (this._isShowing) {
            return Promise.resolve(this);
        }
        return Promise.resolve()
            .then(() => {
                this._isHiding = true;
                if (visibilityFunction) {
                    return visibilityFunction(this);
                } else {
                    // flex? box? should this be configurable easier than the visibilityFunction?
                    this.parent.style.display = "none";
                    return this;
                }
            })
            .then(() => {
                this.isShown = false;
                this._isHiding = false;
                this.onStateChange.notifyObservers(this);
                return this;
            });
    }

    /**
     * Dispose this template
     */
    public dispose() {
        this.onAppended.clear();
        this.onEventTriggered.clear();
        this.onLoaded.clear();
        this.onStateChange.clear();
        this.isLoaded = false;
        // remove from parent
        try {
            this.parent.removeChild(this._fragment);
        } catch (e) {
            //noop
        }

        this._loadRequests.forEach((request) => {
            request.abort();
        });

        if (this._registeredEvents) {
            this._registeredEvents.forEach((evt) => {
                evt.htmlElement.removeEventListener(evt.eventName, evt.function);
            });
        }
    }

    private _getTemplateAsHtml(templateConfig: ITemplateConfiguration): Promise<string> {
        if (!templateConfig) {
            return Promise.reject("No templateConfig provided");
        } else if (templateConfig.html && !templateConfig.location) {
            return Promise.resolve(templateConfig.html);
        } else {
            let location = this._getTemplateLocation(templateConfig);
            if (isUrl(location)) {
                return new Promise((resolve, reject) => {
                    const fileRequest = Tools.LoadFile(
                        location,
                        (data: string | ArrayBuffer) => {
                            resolve(data as string);
                        },
                        undefined,
                        undefined,
                        false,
                        (request, error: any) => {
                            reject(error);
                        }
                    );
                    this._loadRequests.push(fileRequest);
                });
            } else {
                location = location.replace("#", "");
                const element = document.getElementById(location);
                if (element) {
                    return Promise.resolve(element.innerHTML);
                } else {
                    return Promise.reject("Template ID not found");
                }
            }
        }
    }

    private _registeredEvents: Array<{ htmlElement: HTMLElement; eventName: string; function: EventListenerOrEventListenerObject }>;

    private _registerEvents() {
        this._registeredEvents = this._registeredEvents || [];
        if (this._registeredEvents.length) {
            // first remove the registered events
            this._registeredEvents.forEach((evt) => {
                evt.htmlElement.removeEventListener(evt.eventName, evt.function);
            });
        }
        if (this._configuration.events) {
            for (const eventName in this._configuration.events) {
                if (this._configuration.events && this._configuration.events[eventName]) {
                    const functionToFire = (selector: string, event: Event) => {
                        this.onEventTriggered.notifyObservers({ event, template: this, selector });
                    };

                    // if boolean, set the parent as the event listener
                    if (typeof this._configuration.events[eventName] === "boolean") {
                        let selector = this.parent.id;
                        if (selector) {
                            selector = "#" + selector;
                        } else {
                            selector = this.parent.tagName;
                        }
                        const binding = functionToFire.bind(this, selector);
                        this.parent.addEventListener(eventName, binding, false);
                        this._registeredEvents.push({
                            htmlElement: this.parent,
                            eventName: eventName,
                            function: binding,
                        });
                    } else if (typeof this._configuration.events[eventName] === "object") {
                        const selectorsArray: Array<string> = Object.keys((this._configuration.events[eventName] as object) || {});
                        // strict null check is working incorrectly, must override:
                        const event = this._configuration.events[eventName] || {};
                        selectorsArray
                            .filter((selector) => typeof event !== "boolean" && event[selector])
                            .forEach((selector) => {
                                let htmlElement = <HTMLElement>this.parent.querySelector(selector);
                                if (!htmlElement) {
                                    // backcompat, fallback to id
                                    if (selector && selector.indexOf("#") !== 0) {
                                        selector = "#" + selector;
                                    }
                                    try {
                                        htmlElement = <HTMLElement>this.parent.querySelector(selector);
                                    } catch (e) {}
                                }
                                if (htmlElement) {
                                    const binding = functionToFire.bind(this, selector);
                                    htmlElement.addEventListener(eventName, binding, false);
                                    this._registeredEvents.push({
                                        htmlElement: htmlElement,
                                        eventName: eventName,
                                        function: binding,
                                    });
                                }
                            });
                    }
                }
            }
        }
    }

    private _getTemplateLocation(templateConfig: ITemplateConfiguration): string {
        if (!templateConfig || typeof templateConfig === "string") {
            return templateConfig;
        } else {
            return templateConfig.location!;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Hosagoudar, Zoos' Print Journal 17(8): 835 (2002)

#### Original name
Asterina gomphandrae Hosag. & C.K. Biju

### Remarks
null


text:
// Generated from /POI/java/org/apache/poi/hssf/record/crypto/Biff8DecryptingStream.java

#pragma once

#include <fwd-POI.hpp>
#include <java/io/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/crypto/fwd-POI.hpp>
#include <org/apache/poi/poifs/crypt/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <org/apache/poi/hssf/record/BiffHeaderInput.hpp>
#include <org/apache/poi/util/LittleEndianInput.hpp>

struct default_init_tag;

class poi::hssf::record::crypto::Biff8DecryptingStream final
    : public virtual ::java::lang::Object
    , public ::poi::hssf::record::BiffHeaderInput
    , public ::poi::util::LittleEndianInput
{

public:
    typedef ::java::lang::Object super;
    static constexpr int32_t RC4_REKEYING_INTERVAL { int32_t(1024) };

private:
    ::poi::poifs::crypt::EncryptionInfo* info {  };
    ::poi::poifs::crypt::ChunkedCipherInputStream* ccis {  };
    ::int8_tArray* buffer {  };
    bool shouldSkipEncryptionOnCurrentRecord {  };
protected:
    void ctor(::java::io::InputStream* in, int32_t initialOffset, ::poi::poifs::crypt::EncryptionInfo* info) /* throws(RecordFormatException) */;

public:
    int32_t available() override;
    int32_t readRecordSID() override;
    int32_t readDataSize() override;
    double readDouble() override;
    void readFully(::int8_tArray* buf) override;
    void readFully(::int8_tArray* buf, int32_t off, int32_t len) override;
    int32_t readUByte() override;
    int8_t readByte() override;
    int32_t readUShort() override;
    int16_t readShort() override;
    int32_t readInt() override;
    int64_t readLong() override;
    int64_t getPosition();
    static bool isNeverEncryptedRecord(int32_t sid);
    void readPlain(::int8_tArray* b, int32_t off, int32_t len) override;

    // Generated
    Biff8DecryptingStream(::java::io::InputStream* in, int32_t initialOffset, ::poi::poifs::crypt::EncryptionInfo* info);
protected:
    Biff8DecryptingStream(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    void init();
    virtual ::java::lang::Class* getClass0();
};


text:
package org.springframework.data.solr.core.convert;

import java.util.Date;

import org.apache.solr.client.solrj.util.ClientUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;

/**
 * Converts a Date values into a solr readable String that can be directly used within the {@code q} parameter. Note
 * that Dates have to be UTC.

 *
 *   Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
 *   calendar.set(2012, 7, 23, 6, 10, 0);
 *
 *
 * will be formatted as
 *
 *

 * 2012-08-23T06:10:00.000Z
 *

 *
 * @author Christoph Strobl
 */
public final class DateTimeConverters {

	private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.dateTime().withZoneUTC();
	private static final DateTimeFormatter FORMATTER_WITHOUT_MILLIS = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC();

	/**
	 * Converter used to parse {@link DateTime} to {@link String} used for setting
	 * {@link org.apache.solr.client.solrj.SolrQuery} query string values
	 *
	 * @author Christoph Strobl
	 *
	 */
	@WritingConverter
	public enum JodaDateTimeConverter implements Converter<ReadableInstant, String> {
		INSTANCE;

		@Override
		public String convert(ReadableInstant source) {
			if (source == null) {
				return null;
			}
			return (ClientUtils.escapeQueryChars(FORMATTER.print(source.getMillis())));
		}

	}

	@ReadingConverter
	public enum StringToJodaDateTimeConverter implements Converter<String, DateTime> {
		INSTANCE;

		@Override
		public DateTime convert(String source) {
			if (source == null) {
				return null;
			}
			return DateTime.parse(source, FORMATTER_WITHOUT_MILLIS);
		}
	}

	/**
	 * Reading {@link Converter} parses {@link Date} from {@link org.apache.solr.common.SolrDocument} to {@link DateTime}
	 *
	 * @author Christoph Strobl
	 *
	 */
	@ReadingConverter
	public enum DateToJodaDateTimeConverter implements Converter<Date, DateTime> {
		INSTANCE;

		@Override
		public DateTime convert(Date source) {
			if (source == null) {
				return null;
			}
			return new DateTime(source.getTime());
		}
	}

	/**
	 * Writing {@link Converter} converts {@link DateTime} to {@link Date} so it can be used within
	 * {@link org.apache.solr.common.SolrInputDocument}
	 *
	 * @author Christoph Strobl
	 *
	 */
	@WritingConverter
	public enum JodaDateTimeToDateConverter implements Converter<DateTime, Date> {
		INSTANCE;

		@Override
		public Date convert(DateTime source) {
			if (source == null) {
				return null;
			}
			return source.toDate();
		}

	}

	/**
	 * Converter used to parse {@link LocalDateTime} to {@link String} used for setting
	 * {@link org.apache.solr.client.solrj.SolrQuery} query string values
	 *
	 * @author Christoph Strobl
	 *
	 */
	@WritingConverter
	public enum JodaLocalDateTimeConverter implements Converter<LocalDateTime, String> {
		INSTANCE;

		@Override
		public String convert(LocalDateTime source) {
			if (source == null) {
				return null;
			}
			return ClientUtils.escapeQueryChars(FORMATTER.print(source.toDateTime(DateTimeZone.UTC).getMillis()));
		}

	}

	/**
	 * Writing {@link Converter} converts {@link LocalDateTime} to {@link Date} so it can be used within
	 * {@link org.apache.solr.common.SolrInputDocument}
	 *
	 * @author Christoph Strobl
	 *
	 */
	@WritingConverter
	public enum JodaLocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
		INSTANCE;

		@Override
		public Date convert(LocalDateTime source) {
			if (source == null) {
				return null;
			}
			return source.toDate();
		}

	}

	/**
	 * Reading {@link Converter} parses {@link Date} from {@link org.apache.solr.common.SolrDocument} to
	 * {@link LocalDateTime}
	 *
	 * @author Christoph Strobl
	 *
	 */
	@ReadingConverter
	public enum DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
		INSTANCE;

		@Override
		public LocalDateTime convert(Date source) {
			if (source == null) {
				return null;
			}
			return new LocalDateTime(source.getTime());
		}

	}

	/**
	 * Converter used to parse {@link Date} to {@link String} used for setting
	 * {@link org.apache.solr.client.solrj.SolrQuery} query string values
	 *
	 * @author Christoph Strobl
	 *
	 */
	@WritingConverter
	public enum JavaDateConverter implements Converter<Date, String> {
		INSTANCE;

		@Override
		public String convert(Date source) {
			if (source == null) {
				return null;
			}

			return ClientUtils.escapeQueryChars(FORMATTER.print(source.getTime()));
		}

	}

}


text:
import template from './information.pug';

export default ['igniteInformation', [() => {
    return {
        scope: {
            title: '@'
        },
        restrict: 'E',
        template,
        replace: true,
        transclude: true
    };
}]];


text:
{{successMessage}}

Login

            <form ng-show="!isAuthenticated" ng-submit="signin(rememberMe)">

{{errorSignin.message}}

              <input ng-model="user.username" type="text" name="user" placeholder="Username" />
              <input ng-model="user.password" type="password" name="pass" placeholder="Password" />
              <button type="submit" class="btn btn-primary">Login</button>

                <input type="checkbox" ng-model="rememberMe" ng-init="rememberMe=true"> Keep me logged in
                Forgotten password?

            </form>

Ask for Recovery code

              <form ng-show="!isAuthenticated" ng-submit="recoveryRequest()">

{{errorRecoveryRequest.message}}

                <input ng-model="user.username" type="text" name="user" placeholder="Username" />
                <button type="submit" class="btn btn-info">Send email</button>
              </form>

Signup

              <form ng-show="!isAuthenticated" ng-submit="signup()">

{{errorSignup.message}}

                <input ng-model="user.username" type="text" name="user" placeholder="Username" />
                <input ng-model="user.password" type="password" name="pass" placeholder="Password" />
                <input ng-model="user.email" type="text" name="email" placeholder="Email" />
                 <button type="submit" class="btn btn-info">Signup</button>
              </form>

Change password

            <form ng-show="!isAuthenticated" ng-submit="recoveryChange()">

{{errorRecoveryChange.message}}

              <input ng-model="user.username" type="text" name="user" placeholder="Username" />
              <input ng-model="user.password" type="password" name="pass" placeholder="New Password" />
              <input ng-model="user.recoveryCode" type="text" name="recoveryCode" placeholder="Recovery code" />
              <button type="submit" class="btn btn-primary">Change password</button>
            </form>

      Back to login


text:
package org.optaplanner.benchmark.impl.ranking;

import org.junit.Test;
import org.optaplanner.benchmark.impl.result.ProblemBenchmarkResult;
import org.optaplanner.benchmark.impl.result.SingleBenchmarkResult;
import org.optaplanner.benchmark.impl.result.SolverBenchmarkResult;
import org.optaplanner.benchmark.impl.result.SubSingleBenchmarkResult;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;

import static org.mockito.Mockito.mock;
import static org.optaplanner.core.impl.testdata.util.PlannerAssert.assertCompareToOrder;

public class ScoreSubSingleBenchmarkRankingComparatorTest {

    @Test
    public void compareTo() {
        ScoreSubSingleBenchmarkRankingComparator comparator = new ScoreSubSingleBenchmarkRankingComparator();
        SingleBenchmarkResult singleBenchmarkResult = new SingleBenchmarkResult(mock(SolverBenchmarkResult.class), mock(ProblemBenchmarkResult.class));
        SubSingleBenchmarkResult a = new SubSingleBenchmarkResult(singleBenchmarkResult, 0);
        a.setSucceeded(false);
        a.setScore(null);
        SubSingleBenchmarkResult b = new SubSingleBenchmarkResult(singleBenchmarkResult, 1);
        b.setSucceeded(true);
        b.setScore(SimpleScore.valueOfUninitialized(-7, -1));
        SubSingleBenchmarkResult c = new SubSingleBenchmarkResult(singleBenchmarkResult, 2);
        c.setSucceeded(true);
        c.setScore(SimpleScore.valueOf(-300));
        SubSingleBenchmarkResult d = new SubSingleBenchmarkResult(singleBenchmarkResult, 3);
        d.setSucceeded(true);
        d.setScore(SimpleScore.valueOf(-20));
        assertCompareToOrder(comparator, a, b, c, d);
    }

}


text:
<?php

namespace Commun\Table;

/**
 * @author Antarus
 * @project Raid-TracKer
 */
class PagesTable extends \Core\Table\AbstractServiceTable
{

    /**
     * Nom de la  table.
     *
     * @var string
     */
    protected $table = 'pages';

    /**
     * Objet référent.
     *
     * @var \Commun\Model\Classes
     */
    protected $arrayObjectPrototypeClass = '\Commun\Model\Pages';

    /**
     * Clé primaire de la table.
     *
     * @var int
     */
    protected $nomCle = 'idPages';

}


text:
.. _grid_search:

==========================================
Grid Search: setting estimator parameters
==========================================

.. currentmodule:: sklearn

Grid Search is used to optimize the parameters of a model (e.g. ``C``,
``kernel`` and ``gamma`` for Support Vector Classifier, ``alpha`` for
Lasso, etc.) using an internal :ref:`cross_validation` scheme).

GridSearchCV
============

The main class for implementing hyperparameters grid search in
scikit-learn is :class:`grid_search.GridSearchCV`. This class is passed
a base model instance (for example ``sklearn.svm.SVC()``) along with a
grid of potential hyper-parameter values specified with the `param_grid`
attribute. For instace the following `param_grid`::

  param_grid = [
    {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
    {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
   ]

specifies that two grids should be explored: one with a linear kernel and
C values in [1, 10, 100, 1000], and the second one with an RBG kernel,
and the cross-product of C values ranging in [1, 10, 100, 1000] and gamma
values in [0.001, 0.0001].

The :class:`grid_search.GridSearchCV` instance implements the usual
estimator API: when "fitting" it on a dataset all the possible
combinations of hyperparameter values are evaluated and the best
combinations is retained.

.. topic:: Model selection: development and evaluation

  Model selection with ``GridSearchCV`` can be seen as a way to use the
  labeled data to "train" the hyper-parameters of the grid.

  When evaluating the resulting model it is important to do it on
  held-out samples that were not seen during the grid search process:
  it is recommended to split the data into a **development set** (to
  be fed to the ``GridSearchCV`` instance) and an **evaluation set**
  to compute performance metrics.

  This can be done by using the :func:`cross_validation.train_test_split`
  utility function.

.. currentmodule:: sklearn.grid_search

.. _gridsearch_scoring:

Scoring functions for GridSearchCV
----------------------------------
By default, :class:`GridSearchCV` uses the ``score`` function of the estimator
to evaluate a parameter setting. These are the :func:`sklearn.metrics.accuracy_score` for classification
and :func:`sklearn.metrics.r2_score` for regression.
For some applications, other scoring function are better suited (for example in
unbalanced classification, the accuracy score is often non-informative). An
alternative scoring function can be specified via the ``scoring`` parameter to
:class:`GridSearchCV`.
See :ref:`score_func_objects` for more details.

Examples
========

- See :ref:`example_grid_search_digits.py` for an example of
  Grid Search computation on the digits dataset.

- See :ref:`example_grid_search_text_feature_extraction.py` for an example
  of Grid Search coupling parameters from a text documents feature
  extractor (n-gram count vectorizer and TF-IDF transformer) with a
  classifier (here a linear SVM trained with SGD with either elastic
  net or L2 penalty) using a :class:`pipeline.Pipeline` instance.

.. note::

  Computations can be run in parallel if your OS supports it, by using
  the keyword n_jobs=-1, see function signature for more details.

Alternatives to brute force grid search
=======================================

Model specific cross-validation
-------------------------------

Some models can fit data for a range of value of some parameter almost
as efficiently as fitting the estimator for a single value of the
parameter. This feature can be leveraged to perform a more efficient
cross-validation used for model selection of this parameter.

The most common parameter amenable to this strategy is the parameter
encoding the strength of the regularizer. In this case we say that we
compute the **regularization path** of the estimator.

Here is the list of such models:

.. autosummary::
   :toctree: generated/
   :template: class.rst

   linear_model.RidgeCV
   linear_model.RidgeClassifierCV
   linear_model.LarsCV
   linear_model.LassoLarsCV
   linear_model.LassoCV
   linear_model.ElasticNetCV

Information Criterion
---------------------

Some models can offer an information-theoretic closed-form formula of the
optimal estimate of the regularization parameter by computing a single
regularization path (instead of several when using cross-validation).

Here is the list of models benefitting from the Aikike Information
Criterion (AIC) or the Bayesian Information Criterion (BIC) for automated
model selection:

.. autosummary::
   :toctree: generated/
   :template: class.rst

   linear_model.LassoLarsIC

.. _out_of_bag:

Out of Bag Estimates
--------------------

When using ensemble methods base upon bagging, i.e. generating new
training sets using sampling with replacement, part of the training set
remains unused.  For each classifier in the ensemble, a different part
of the training set is left out.

This left out portion can be used to estimate the generalization error
without having to rely on a separate validation set.  This estimate
comes "for free" as no addictional data is needed and can be used for
model selection.

This is currently implemented in the following classes:

.. autosummary::
   :toctree: generated/
   :template: class.rst

    ensemble.RandomForestClassifier
    ensemble.RandomForestRegressor
    ensemble.ExtraTreesClassifier
    ensemble.ExtraTreesRegressor
    ensemble.GradientBoostingClassifier
    ensemble.GradientBoostingRegressor


text:
package envcfg

import (
	"os"
	"testing"
)

type nestedStruct struct {
	SubStruct struct {
		Field string
	}
}

func TestNestedMapping(t *testing.T) {
	const ENV_KEY = "SUBSTRUCT_FIELD"
	const ENV_VAL = "Remember: testing is the future!"

	os.Clearenv()
	os.Setenv(ENV_KEY, ENV_VAL)

	s := nestedStruct{}

	ReadInto(&s)

	if s.SubStruct.Field != ENV_VAL {
		t.Errorf("expected '%s', got '%s'", ENV_VAL, s.SubStruct.Field)
	}
}

type deeplyNestedStruct struct {
	SubStruct struct {
		SubSubStruct struct {
			Field string
		}
	}
}

func TestDeeplyNestedMapping(t *testing.T) {
	const ENV_KEY = "SUBSTRUCT_SUBSUBSTRUCT_FIELD"
	const ENV_VAL = "Remember: testing is the future!"

	os.Clearenv()
	os.Setenv(ENV_KEY, ENV_VAL)

	s := deeplyNestedStruct{}

	ReadInto(&s)

	if s.SubStruct.SubSubStruct.Field != ENV_VAL {
		t.Errorf("expected '%s', got '%s'", ENV_VAL, s.SubStruct.SubSubStruct.Field)
	}
}


text:
An example of using [redmine_typical_entity](https://github.com/crosspath/redmine_typical_entity) to show, how to manipulate typical entity (model) in [Redmine](https://github.com/redmine/redmine).

## Description

Abstract:
Store list of clients in Redmine with history of changes and notes about their orders.

The company deliveres equipment for photo and video shooting.
A user of Redmine creates clients' orders in Redmine.
Each order contains client's name, expected date of delivery, delivery address, sum and list of ordered products.
Then workers of the company collect and pack products and pass it to delivery service.
The process of acquisition of the order is reflected in the change of status of the order.
So, orders may be represented as issues in Redmine.
These issues should have additional fields: "Client", "Expected date of delivery", "Delivery address", "Sum", "Products".
Viewing history of clients' orders should be available at any time with filtering orders by client's name.

Model/Attribute | Type
---|---
Client |
id | int, serial
name | string
notes | string
---|---
Product |
id | int, serial
name | string
descr | string
image | Attachment
---|---
Issue |
Client | Client
Expected date of delivery | date
Delivery address | string
Sum | string
Products | array<Product>


text:
package org.apache.kafka.common;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The consumer group state.
 */
public enum ConsumerGroupState {
    UNKNOWN("Unknown"),
    PREPARING_REBALANCE("PreparingRebalance"),
    COMPLETING_REBALANCE("CompletingRebalance"),
    STABLE("Stable"),
    DEAD("Dead"),
    EMPTY("Empty");

    private final static Map<String, ConsumerGroupState> NAME_TO_ENUM = Arrays.stream(values())
        .collect(Collectors.toMap(state -> state.name, Function.identity()));;

    private final String name;

    ConsumerGroupState(String name) {
        this.name = name;
    }

    /**
     * Parse a string into a consumer group state.
     */
    public static ConsumerGroupState parse(String name) {
        ConsumerGroupState state = NAME_TO_ENUM.get(name);
        return state == null ? UNKNOWN : state;
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
<?php
Class Customermodel extends CI_Model {
	function __construct() {
		parent::__construct();
	}

	// Get all dogs belongs to particular customer
	public function getDogs($model_data) {
		$this->db->select('*');
		$this->db->from('dog');
		$this->db->where('user_id', $model_data['user_id'] );
		return $this->db->get()->result();
	}

	// Delete single dog on basis of dog id
	public function deleteDog($model_data) {
		$this->db->where('dog_id', $model_data['dog_id'] );
		$this->db->delete('dog');
		return true;
	}

	// get users profile info
	public function getProfileInfo($model_data) {
		$this->db->select('*');
		$this->db->from('users');
		$this->db->where('user_id', $model_data['user_id'] );
		$query = $this->db->get();
		if ( $query->num_rows() > 0 )
		{
			$row = $query->row_array();
			return $row;
		}
	}

	// get users contact info
	public function getContactInfo($model_data) {
		$this->db->select('*');
		$this->db->from('contact');
		$this->db->where('user_id', $model_data['user_id'] );
		$query = $this->db->get();
		if ($query->num_rows() > 0 )
		{
			$rows = $query->row_array();
			return $rows;
		}
	}

	// add dog
	public function addDog($data) {
		$user_id = $data['user_id'];
		$name = $data['name'];
		$image_url = $data['image_url'];

		$sql = "INSERT INTO dog(`user_id`,`name`, `image_url`) VALUES('$user_id','$name','$image_url') ";
		$result = $this->db->query($sql);
		return true;
	}

	// customer request for a walk
	public function requestwalk($model_data) {
		$walkdate = $model_data['walkdate'];
		$walkfromtime = $model_data['walkfromtime'];
		$walktotime = $model_data['walktotime'];
		$walkfrequency = $model_data['walkfrequency'];
		$walkdogs = $model_data['walkdogs'];
		$status_code = "1";
		$noofwalkdogs = $model_data['array_length'];
		$customer_id  = $model_data['customer_id'];

		$dateOneYearAdded = strtotime(date("Y-m-d", strtotime($walkdate)) . " +1 year");
		$enddate1 = date('Y-m-d', $dateOneYearAdded)."<br>";

		$startdatetime = new datetime($walkdate);

		$new_date = date('Y-m-d H:i:s', $dateOneYearAdded);

		$enddatetime = new datetime($new_date);

		$interval = new DateInterval('P7D');
		$daterange = new DatePeriod($startdatetime, $interval ,$enddatetime);

		if($noofwalkdogs > 1) {
			$group_walk = "yes";
		} else {
			$group_walk = "no";
		}

		foreach($daterange as $date){
		    $walkdate1 = $date->format("Y-m-d");

			$sql = "INSERT INTO `walk`(`fromtime`,`totime`,`walk_frequency`,`status_code`,`customer_id`,`walkdate`) VALUES('$walkfromtime','$walktotime','$walkfrequency','$status_code','$customer_id','$walkdate1')";
			$result = $this->db->query($sql);
			$sql1 = "SELECT walk_id FROM walk ORDER BY date_of_booking DESC LIMIT 1";
			$dogwalk_id = $this->db->query($sql1)->row();
			$dogwalkid1 = $dogwalk_id->walk_id;

			if($noofwalkdogs == 1) {
				$sql2= "INSERT INTO walk_dogs(`walk_id`,`dog1_id`) VALUES('$dogwalkid1','$walkdogs[0]')";
				$this->db->query($sql2);
			} else if($noofwalkdogs == 2) {
				$sql3 = "INSERT INTO walk_dogs(`walk_id`,`dog1_id`,`dog2_id`) VALUES('$dogwalkid1','$walkdogs[0]','$walkdogs[1]')";
				$this->db->query($sql3);
			} else if($noofwalkdogs == 3) {
				$sql4 = "INSERT INTO walk_dogs(`walk_id`,`dog1_id`,`dog2_id`,`dog3_id`) VALUES('$dogwalkid1','$walkdogs[0]','$walkdogs[1]','$walkdogs[2]')";
				$this->db->query($sql4);
			} else if($noofwalkdogs == 4) {
				$sql5 = "INSERT INTO walk_dogs(`walk_id`,`dog1_id`,`dog2_id`,`dog3_id`,`dog4_id`) VALUES('$dogwalkid1','$walkdogs[0]','$walkdogs[1]','$walkdogs[2]','$walkdogs[3]')";
				$this->db->query($sql5);
			} else if($noofwalkdogs == 5) {
				$sql6 = "INSERT INTO walk_dogs(`walk_id`,`dog1_id`,`dog2_id`,`dog3_id`,`dog4_id`,'dog5_id') VALUES('$dogwalkid1','$walkdogs[0]','$walkdogs[1]','$walkdogs[2]','$walkdogs[3]','$walkdogs[4]','$walkdogs[5]')";
				$this->db->query($sql6);
			}
		}
		return true;
	}

	// get all walks related to customer
	public function getwalks($model_data) {
		$user_id = $model_data['user_id'];
		$this->db->select('*');
		$this->db->from('walk');
		$this->db->where('customer_id', $model_data['user_id'] );
		$this->db->LIMIT('7');
		$walks =  $this->db->get()->result();
		return $walks;
	}

	// cancel walk request
	public function cancelwalkrequest($model_data) {
		$walk_id = $model_data['walk_id'];
		$sql = "UPDATE walk SET status_code = '7' WHERE walk_id = '$walk_id'";
		$result= $this->db->query($sql);
		return true;
	}

	// get data from calendar
	public function getcalendardata() {
		$this->db->select('walk_id , walk_name, walkdate, fromtime, totime');
		$this->db->from('walk');
		$sql = "SELECT walk_id, walk_name AS title, walkdate AS start, fromtime, totime FROM walk";
		$result  = $this->db->query($sql)->result();
		return $result;
	}

	// Delete customer contact
	public function deleteCustomerContact($model_data) {
		$this->db->where('user_contact_id', $model_data['customercontact_id'] );
		$this->db->delete('user_contacts');
		return true;
	}
}
?>


text:
{% load i18n %}

{% blocktrans %}Dear {{ domain }} administrator,{% endblocktrans %}

    {% blocktrans %}
    Your 30 Day Trial for {{ domain }} ends soon! If you do not
    change your subscription before then, you will automatically be subscribed
    to the {{ product }} Community plan and lose access to all pay-only
    features {{ ending_on }}
    {% endblocktrans %}

    {% blocktrans %}
    To change your subscription, please log into your project on
    {{ product }} HQ and navigate to the
    subscription page in your
    project settings.
    {% endblocktrans %}

    {% blocktrans %}
    If you have questions about our pricing plans,
    you can review them here.
    {% endblocktrans %}

    {% blocktrans %}
    Thank you for your use and support of {{ product }}.
    {% endblocktrans %}

    {% blocktrans %}
    Best regards,
    {% endblocktrans %}

    {% blocktrans %}The {{ product }} HQ Team{% endblocktrans %}

    {{ base_url }}


text:
Copyright 2012, 2013, 2015 Matthew Harvey

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.

Style guide
===========

**Conditional statements**::

    // don't do this

    if (some_condition)
        not_ok();

    if (some_condition) {
        not_ok();
    }

    // these are OK

    if (some_condition) this_is_acceptable();

    if (some_condition)
    {
        this_is_acceptable();
    }

    if (some_condition)
    {
        this_is_acceptable();
        and_so_is_this();
    }

**Function definitions**::

    int some_function(int x)
    {
        do_function_body();
        return x * 2;
    }

**Function calls**::

    auto x = some_function_call(3, y, some_other_thing(y));

    auto x = some_quite_long_function_call
    (	with,
        lots,
        of,
        arguments_that_do_not_fit_on,
        one_line
    );

**Naming**::

    ClassName
    function_name
    local_variable_name
    local_constant_name
    file_name
    GUARD_header_guard_hpp
    m_member_variable
    s_static_class_variable
    p_parameter
    EnumName
    StructName
    MACRO
    Thing  // Name of class
    things  // name of SQL table
    thing_id  // name of primary key
    thing_id  // name of foreign key
    attribute // name of ordinary column

**Exceptions**

All exception classes should be derived from std::exception (either directly
or indirectly).

**Typedefs**::

    // don't do
    typedef Blah Bloob;

    // do do
    using Boob = Blah;

**Auto**::

Use auto unless there's a really good reason not to. Even if you need to
initialize a variable of one type by converting from another type, still prefer
auto - with a static_cast to make the conversion extra-obvious::

  auto const x = static_cast<int>(function_returning_a_double());


text:
namespace bubblefs{
namespace mybrpc {

// This data structure makes Read() almost lock-free by making Modify()
// *much* slower. It's very suitable for implementing LoadBalancers which
// have a lot of concurrent read-only ops from many threads and occasional
// modifications of data. As a side effect, this data structure can store
// a thread-local data for user.
//
// Read(): begin with a thread-local mutex locked then read the foreground
// instance which will not be changed before the mutex is unlocked. Since the
// mutex is only locked by Modify() with an empty critical section, the
// function is almost lock-free.
//
// Modify(): Modify background instance which is not used by any Read(), flip
// foreground and background, lock thread-local mutexes one by one to make
// sure all existing Read() finish and later Read() see new foreground,
// then modify background(foreground before flip) again.

class Void { };

template <typename T, typename TLS = Void>
class DoublyBufferedData {
    class Wrapper;
public:
    class ScopedPtr {
    friend class DoublyBufferedData;
    public:
        ScopedPtr() : _data(NULL), _w(NULL) {}
        ~ScopedPtr() {
            if (_w) {
                _w->EndRead();
            }
        }
        const T* get() const { return _data; }
        const T& operator*() const { return *_data; }
        const T* operator->() const { return _data; }
        TLS& tls() { return _w->user_tls(); }

    private:
        DISALLOW_COPY_AND_ASSIGN(ScopedPtr);
        const T* _data;
        Wrapper* _w;
    };

    DoublyBufferedData();
    ~DoublyBufferedData();

    // Put foreground instance into ptr. The instance will not be changed until
    // ptr is destructed.
    // This function is not blocked by Read() and Modify() in other threads.
    // Returns 0 on success, -1 otherwise.
    int Read(ScopedPtr* ptr);

    // Modify background and foreground instances. fn(T&, ...) will be called
    // twice. Modify() from different threads are exclusive from each other.
    // NOTE: Call same series of fn to different equivalent instances should
    // result in equivalent instances, otherwise foreground and background
    // instance will be inconsistent.
    template <typename Fn> size_t Modify(Fn& fn);
    template <typename Fn, typename Arg1> size_t Modify(Fn& fn, const Arg1&);
    template <typename Fn, typename Arg1, typename Arg2>
    size_t Modify(Fn& fn, const Arg1&, const Arg2&);

    // fn(T& background, const T& foreground, ...) will be called to background
    // and foreground instances respectively.
    template <typename Fn> size_t ModifyWithForeground(Fn& fn);
    template <typename Fn, typename Arg1>
    size_t ModifyWithForeground(Fn& fn, const Arg1&);
    template <typename Fn, typename Arg1, typename Arg2>
    size_t ModifyWithForeground(Fn& fn, const Arg1&, const Arg2&);

private:
    template <typename Fn>
    struct WithFG0 {
        WithFG0(Fn& fn, T* data) : _fn(fn), _data(data) { }
        size_t operator()(T& bg) {
            return _fn(bg, (const T&)_data[&bg == _data]);
        }
    private:
        Fn& _fn;
        T* _data;
    };

    template <typename Fn, typename Arg1>
    struct WithFG1 {
        WithFG1(Fn& fn, T* data, const Arg1& arg1)
            : _fn(fn), _data(data), _arg1(arg1) {}
        size_t operator()(T& bg) {
            return _fn(bg, (const T&)_data[&bg == _data], _arg1);
        }
    private:
        Fn& _fn;
        T* _data;
        const Arg1& _arg1;
    };

    template <typename Fn, typename Arg1, typename Arg2>
    struct WithFG2 {
        WithFG2(Fn& fn, T* data, const Arg1& arg1, const Arg2& arg2)
            : _fn(fn), _data(data), _arg1(arg1), _arg2(arg2) {}
        size_t operator()(T& bg) {
            return _fn(bg, (const T&)_data[&bg == _data], _arg1, _arg2);
        }
    private:
        Fn& _fn;
        T* _data;
        const Arg1& _arg1;
        const Arg2& _arg2;
    };

    template <typename Fn, typename Arg1>
    struct Closure1 {
        Closure1(Fn& fn, const Arg1& arg1) : _fn(fn), _arg1(arg1) {}
        size_t operator()(T& bg) { return _fn(bg, _arg1); }
    private:
        Fn& _fn;
        const Arg1& _arg1;
    };

    template <typename Fn, typename Arg1, typename Arg2>
    struct Closure2 {
        Closure2(Fn& fn, const Arg1& arg1, const Arg2& arg2)
            : _fn(fn), _arg1(arg1), _arg2(arg2) {}
        size_t operator()(T& bg) { return _fn(bg, _arg1, _arg2); }
    private:
        Fn& _fn;
        const Arg1& _arg1;
        const Arg2& _arg2;
    };

    const T* UnsafeRead() const { return _data + _index; }
    Wrapper* AddWrapper();
    void RemoveWrapper(Wrapper*);

    // Foreground and background void.
    T _data[2];

    // Index of foreground instance.
    short _index;

    // Key to access thread-local wrappers.
    bool _created_key;
    pthread_key_t _wrapper_key;

    // All thread-local instances.
    std::vector<Wrapper*> _wrappers;

    // Sequence access to _wrappers.
    pthread_mutex_t _wrappers_mutex;

    // Sequence modifications.
    pthread_mutex_t _modify_mutex;
};

static const pthread_key_t INVALID_PTHREAD_KEY = (pthread_key_t)-1;

template <typename T, typename TLS>
class DoublyBufferedDataWrapperBase {
public:
    TLS& user_tls() { return _user_tls; }
protected:
    TLS _user_tls;
};

template <typename T>
class DoublyBufferedDataWrapperBase<T, Void> {
};

template <typename T, typename TLS>
class DoublyBufferedData<T, TLS>::Wrapper
    : public DoublyBufferedDataWrapperBase<T, TLS> {
friend class DoublyBufferedData;
public:
    explicit Wrapper(DoublyBufferedData* c) : _control(c) {
        pthread_mutex_init(&_mutex, NULL);
    }

    ~Wrapper() {
        if (_control != NULL) {
            _control->RemoveWrapper(this);
        }
        pthread_mutex_destroy(&_mutex);
    }

    // _mutex will be locked by the calling pthread and DoublyBufferedData.
    // Most of the time, no modifications are done, so the mutex is
    // uncontended and fast.
    inline void BeginRead() {
        pthread_mutex_lock(&_mutex);
    }

    inline void EndRead() {
        pthread_mutex_unlock(&_mutex);
    }

    inline void WaitReadDone() {
        BASE_SCOPED_LOCK(_mutex);
    }

private:
    DoublyBufferedData* _control;
    pthread_mutex_t _mutex;
};

// Called when thread initializes thread-local wrapper.
template <typename T, typename TLS>
typename DoublyBufferedData<T, TLS>::Wrapper*
DoublyBufferedData<T, TLS>::AddWrapper() {
    Wrapper* w = new (std::nothrow) Wrapper(this);
    if (NULL == w) {
        return NULL;
    }
    try {
        BASE_SCOPED_LOCK(_wrappers_mutex);
        _wrappers.push_back(w);
    } catch (std::exception& e) {
        return NULL;
    }
    return w;
}

// Called when thread quits.
template <typename T, typename TLS>
void DoublyBufferedData<T, TLS>::RemoveWrapper(
    typename DoublyBufferedData<T, TLS>::Wrapper* w) {
    if (NULL == w) {
        return;
    }
    BASE_SCOPED_LOCK(_wrappers_mutex);
    for (size_t i = 0; i < _wrappers.size(); ++i) {
        if (_wrappers[i] == w) {
            _wrappers[i] = _wrappers.back();
            _wrappers.pop_back();
            return;
        }
    }
}

template <typename T, typename TLS>
DoublyBufferedData<T, TLS>::DoublyBufferedData()
    : _index(0)
    , _created_key(false)
    , _wrapper_key(0) {
    _wrappers.reserve(64);
    pthread_mutex_init(&_modify_mutex, NULL);
    pthread_mutex_init(&_wrappers_mutex, NULL);
    const int rc = pthread_key_create(&_wrapper_key,
                                      base::delete_object<Wrapper>);
    if (rc != 0) {
        LOG(FATAL) << "Fail to pthread_key_create: " << strerror(rc);
    } else {
        _created_key = true;
    }
    // Initialize _data for some POD types. This is essential for pointer
    // types because they should be Read() as NULL before any Modify().
    if (std::is_integral<T>::value || std::is_floating_point<T>::value ||
        std::is_pointer<T>::value || std::is_member_function_pointer<T>::value) {
        _data[0] = T();
        _data[1] = T();
    }
}

template <typename T, typename TLS>
DoublyBufferedData<T, TLS>::~DoublyBufferedData() {
    // User is responsible for synchronizations between Read()/Modify() and
    // this function.
    if (_created_key) {
        pthread_key_delete(_wrapper_key);
    }

    {
        BASE_SCOPED_LOCK(_wrappers_mutex);
        for (size_t i = 0; i < _wrappers.size(); ++i) {
            _wrappers[i]->_control = NULL;  // hack: disable removal.
            delete _wrappers[i];
        }
        _wrappers.clear();
    }
    pthread_mutex_destroy(&_modify_mutex);
    pthread_mutex_destroy(&_wrappers_mutex);
}

template <typename T, typename TLS>
int DoublyBufferedData<T, TLS>::Read(
    typename DoublyBufferedData<T, TLS>::ScopedPtr* ptr) {
    if (UNLIKELY(!_created_key)) {
        return -1;
    }
    Wrapper* w = static_cast<Wrapper*>(pthread_getspecific(_wrapper_key));
    if (LIKELY(w != NULL)) {
        w->BeginRead();
        ptr->_data = UnsafeRead();
        ptr->_w = w;
        return 0;
    }
    w = AddWrapper();
    if (LIKELY(w != NULL)) {
        const int rc = pthread_setspecific(_wrapper_key, w);
        if (rc == 0) {
            w->BeginRead();
            ptr->_data = UnsafeRead();
            ptr->_w = w;
            return 0;
        }
    }
    return -1;
}

template <typename T, typename TLS>
template <typename Fn>
size_t DoublyBufferedData<T, TLS>::Modify(Fn& fn) {
    // _modify_mutex sequences modifications. Using a separate mutex rather
    // than _wrappers_mutex is to avoid blocking threads calling
    // AddWrapper() or RemoveWrapper() too long. Most of the time, modifications
    // are done by one thread, contention should be negligible.
    BASE_SCOPED_LOCK(_modify_mutex);
    // background instance is not accessed by other threads, being safe to
    // modify.
    const size_t ret = fn(_data[!_index]);
    if (!ret) {
        return 0;
    }

    // Publish, flip background and foreground.
    _index = !_index;

    // Wait until all threads finishes current reading. When they begin next
    // read, they should see updated _index.
    {
        BASE_SCOPED_LOCK(_wrappers_mutex);
        for (size_t i = 0; i < _wrappers.size(); ++i) {
            _wrappers[i]->WaitReadDone();
        }
    }

    const size_t ret2 = fn(_data[!_index]);
    CHECK_EQ(ret2, ret) << "index=" << _index;
    return ret2;
}

template <typename T, typename TLS>
template <typename Fn, typename Arg1>
size_t DoublyBufferedData<T, TLS>::Modify(Fn& fn, const Arg1& arg1) {
    Closure1<Fn, Arg1> c(fn, arg1);
    return Modify(c);
}

template <typename T, typename TLS>
template <typename Fn, typename Arg1, typename Arg2>
size_t DoublyBufferedData<T, TLS>::Modify(
    Fn& fn, const Arg1& arg1, const Arg2& arg2) {
    Closure2<Fn, Arg1, Arg2> c(fn, arg1, arg2);
    return Modify(c);
}

template <typename T, typename TLS>
template <typename Fn>
size_t DoublyBufferedData<T, TLS>::ModifyWithForeground(Fn& fn) {
    WithFG0<Fn> c(fn, _data);
    return Modify(c);
}

template <typename T, typename TLS>
template <typename Fn, typename Arg1>
size_t DoublyBufferedData<T, TLS>::ModifyWithForeground(Fn& fn, const Arg1& arg1) {
    WithFG1<Fn, Arg1> c(fn, _data, arg1);
    return Modify(c);
}

template <typename T, typename TLS>
template <typename Fn, typename Arg1, typename Arg2>
size_t DoublyBufferedData<T, TLS>::ModifyWithForeground(
    Fn& fn, const Arg1& arg1, const Arg2& arg2) {
    WithFG2<Fn, Arg1, Arg2> c(fn, _data, arg1, arg2);
    return Modify(c);
}

}  // namespace mybrpc
}  // namespace bubblefs

#endif  // BUBBLEFS_UTILS_BRPC_DOUBLY_BUFFERED_DATA_H_


text:
package org.estatio.module.application.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.wicketstuff.pdfjs.Scale;

import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.CollectionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.value.Blob;

import org.isisaddons.wicket.pdfjs.cpt.applib.PdfJsViewer;

import org.incode.module.document.dom.impl.docs.Document;
import org.incode.module.document.dom.impl.docs.DocumentAbstract;

import org.estatio.module.capex.dom.documents.LookupAttachedPdfService;
import org.estatio.module.capex.dom.invoice.IncomingInvoice;
import org.estatio.module.capex.dom.invoice.IncomingInvoiceRepository;
import org.estatio.module.capex.dom.invoice.IncomingInvoiceRoleTypeEnum;
import org.estatio.module.capex.dom.invoice.approval.IncomingInvoiceApprovalState;
import org.estatio.module.lease.dom.LeaseAgreementRoleTypeEnum;
import org.estatio.module.party.app.services.ChamberOfCommerceCodeLookUpService;
import org.estatio.module.party.app.services.OrganisationNameNumberViewModel;
import org.estatio.module.party.dom.Organisation;
import org.estatio.module.party.dom.role.PartyRole;
import org.estatio.module.party.dom.role.PartyRoleType;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@DomainObject(objectType = "party.MissingChamberOfCommerceCodeManager")
@DomainObjectLayout(cssClassFa = "fa-wrench")
@XmlRootElement(name = "missingChamberOfCommerceCodeViewModel")
@XmlAccessorType(XmlAccessType.FIELD)
@NoArgsConstructor
public class MissingChamberOfCommerceCodeManager {

    public String title() {
        return "Fix missing Chamber of Commerce codes";
    }

    public MissingChamberOfCommerceCodeManager(final List<Organisation> remainingOrganisations) {
        this.remainingOrganisations = remainingOrganisations;
        this.organisation = this.remainingOrganisations.remove(0);
    }

    @Getter @Setter
    private Organisation organisation;

    public String getRoles() {
        return organisation.getRoles().stream()
                .map(PartyRole::getRoleType)
                .filter(type -> type.getKey().equals(LeaseAgreementRoleTypeEnum.TENANT.getKey()) || type.getKey().equals(IncomingInvoiceRoleTypeEnum.SUPPLIER.getKey()))
                .map(PartyRoleType::getTitle)
                .collect(Collectors.joining(", "));
    }

    @Getter @Setter
    @Property(editing = Editing.ENABLED)
    private String chamberOfCommerceCode;

    @Getter @Setter
    public List<Organisation> remainingOrganisations = new ArrayList<>();

    @Getter @Setter
    public List<Organisation> skippedOrganisations = new ArrayList<>();

    @Getter @Setter
    @CollectionLayout(named = "No suggestions and no invoice")
    public List<Organisation> noSuggestions = new ArrayList<>();

    @Action(associateWith = "candidateCodes", semantics = SemanticsOf.IDEMPOTENT)
    public MissingChamberOfCommerceCodeManager chooseChamberOfCommerceCode(final List<OrganisationNameNumberViewModel> choice) {
        setChamberOfCommerceCode(choice.get(0).getChamberOfCommerceCode());
        return this;
    }

    public String validateChooseChamberOfCommerceCode(final List<OrganisationNameNumberViewModel> choice) {
        return choice.size() != 1 ?
                "Must select exactly one option from the list of suggestions" :
                null;
    }

    public List<OrganisationNameNumberViewModel> getCandidateCodes() {
        return lookUpService.getChamberOfCommerceCodeCandidatesByOrganisation(organisation);
    }

    @PdfJsViewer(initialPageNum = 1, initialScale = Scale.PAGE_WIDTH, initialHeight = 1500)
    @Action(semantics = SemanticsOf.SAFE)
    @ActionLayout(contributed = Contributed.AS_ASSOCIATION)
    public Blob getNewestInvoice() {
        Optional<IncomingInvoice> invoiceIfAny = incomingInvoiceRepository.findBySellerAndApprovalStates(organisation, Arrays.asList(IncomingInvoiceApprovalState.values()))
                .stream()
                .max(Comparator.comparing(IncomingInvoice::getInvoiceDate, Comparator.nullsFirst(Comparator.naturalOrder())));

        Optional<Document> documentIfAny = invoiceIfAny.isPresent() ?
                pdfService.lookupIncomingInvoicePdfFrom(invoiceIfAny.get()) :
                Optional.empty();

        return documentIfAny.map(DocumentAbstract::getBlob).orElse(null);
    }

    public MissingChamberOfCommerceCodeManager save() {
        this.organisation.setChamberOfCommerceCode(getChamberOfCommerceCode());

        prepareForNextOrganisation();

        return this;
    }

    public String disableSave() {
        return chamberOfCommerceCode == null ? "Chamber of Commerce code is required to save" : null;
    }

    public MissingChamberOfCommerceCodeManager skip() {
        this.skippedOrganisations.add(this.organisation);

        prepareForNextOrganisation();

        return this;
    }

    @Action(semantics = SemanticsOf.IDEMPOTENT)
    public MissingChamberOfCommerceCodeManager skipToSpecificOrganisation(final Organisation organisation) {
        final List<Organisation> toBeSkipped = new ArrayList<>();

        for (final Organisation current : remainingOrganisations) {
            if (!current.equals(organisation)) {
                toBeSkipped.add(current);
            } else {
                this.organisation = current;
                this.chamberOfCommerceCode = null;
                break;
            }
        }

        skippedOrganisations.addAll(toBeSkipped);
        remainingOrganisations.removeAll(toBeSkipped);

        return this;
    }

    public List<Organisation> choices0SkipToSpecificOrganisation() {
        return remainingOrganisations;
    }

    private void prepareForNextOrganisation() {
        if (organisation == null)
            return; // we hit the end of the recursive cycle

        this.organisation = this.remainingOrganisations.isEmpty() ? null : this.remainingOrganisations.remove(0);
        this.chamberOfCommerceCode = null;

        // not very helpful to the user, skip to next in line
        if (getNewestInvoice() == null && getCandidateCodes().isEmpty()) {
            this.noSuggestions.add(this.organisation);
            prepareForNextOrganisation();
        }
    }

    @XmlTransient
    @Inject
    IncomingInvoiceRepository incomingInvoiceRepository;

    @XmlTransient
    @Inject
    LookupAttachedPdfService pdfService;

    @XmlTransient
    @Inject
    ChamberOfCommerceCodeLookUpService lookUpService;

}


text: Utilities for managing a collection of Magic: The Gathering Basic Land cards.


text:
package org.workcraft.plugins.plato.commands;

import org.workcraft.Framework;
import org.workcraft.commands.AbstractConversionCommand;
import org.workcraft.plugins.plato.gui.WriterDialog;
import org.workcraft.plugins.plato.tasks.PlatoResultHandler;
import org.workcraft.plugins.plato.tasks.PlatoTask;
import org.workcraft.plugins.stg.VisualStg;
import org.workcraft.tasks.TaskManager;
import org.workcraft.utils.FileUtils;
import org.workcraft.utils.WorkspaceUtils;
import org.workcraft.workspace.ModelEntry;
import org.workcraft.workspace.WorkspaceEntry;

import java.io.File;

public class StgConversionCommand extends AbstractConversionCommand {

    private boolean dotLayout;

    @Override
    public boolean isApplicableTo(WorkspaceEntry we) {
        return WorkspaceUtils.isApplicable(we, VisualStg.class);
    }

    @Override
    public Position getPosition() {
        return Position.BOTTOM;
    }

    @Override
    public String getDisplayName() {
        return "Translate concepts...";
    }

    @Override
    public ModelEntry convert(ModelEntry me) {
        final Framework framework = Framework.getInstance();
        WriterDialog dialog = new WriterDialog(framework.getMainWindow(), false);
        if (dialog.reveal()) {
            WorkspaceEntry we = framework.getWorkspaceEntry(me);
            File inputFile = dialog.getFile();
            dotLayout = dialog.getDotLayoutState();
            PlatoTask task = new PlatoTask(inputFile, dialog.getIncludeList(), false, isSystem(dialog));
            String name = FileUtils.getFileNameWithoutExtension(inputFile);
            PlatoResultHandler resultHandler = new PlatoResultHandler(this, name, we, isSystem(dialog));
            TaskManager taskManager = framework.getTaskManager();
            taskManager.queue(task, "Plato - Translating concepts to STG", resultHandler);
        }
        return null;
    }

    public boolean getDotLayout() {
        return dotLayout;
    }

    private boolean isSystem(WriterDialog dialog) {
        return dialog.isSystem();
    }

}


text:
  <title>The source code</title>
    <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @class Ext.EventManager
 */
Ext.apply(Ext.EventManager, function(){
	var resizeEvent,
    	resizeTask,
    	textEvent,
    	textSize,
    	D = Ext.lib.Dom,
    	E = Ext.lib.Event,
    	propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
        curWidth = 0,
        curHeight = 0,
        // note 1: IE fires ONLY the keydown event on specialkey autorepeat
        // note 2: Safari < 3.1, Gecko (Mac/Linux) & Opera fire only the keypress event on specialkey autorepeat
        // (research done by @Jan Wolter at http://unixpapa.com/js/key.html)
        useKeydown = Ext.isSafari ?
                    Ext.num(navigator.userAgent.toLowerCase().match(/version\/(\d+\.\d)/)[1] || 2) >= 3.1 :
                    !((Ext.isGecko && !Ext.isWindows) || Ext.isOpera);

	return {
		// private
	    doResizeEvent: function(){
            var h = D.getViewHeight(),
                w = D.getViewWidth();

            //whacky problem in IE where the resize event will fire even though the w/h are the same.
            if(curHeight != h || curWidth != w){
                resizeEvent.fire(curWidth = w, curHeight = h);
            }
	    },

/**
	     * Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
	     * @param {Function} fn        The method the event invokes
	     * @param {Object}   scope    An object that becomes the scope of the handler
	     * @param {boolean}  options
	     */
	    onWindowResize : function(fn, scope, options){
	        if(!resizeEvent){
	            resizeEvent = new Ext.util.Event();
	            resizeTask = new Ext.util.DelayedTask(this.doResizeEvent);
	            E.on(window, "resize", this.fireWindowResize, this);
	        }
	        resizeEvent.addListener(fn, scope, options);
	    },

	    // exposed only to allow manual firing
	    fireWindowResize : function(){
	        if(resizeEvent){
	            if((Ext.isIE||Ext.isAir) && resizeTask){
	                resizeTask.delay(50);
	            }else{
	                resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
	            }
	        }
	    },

/**
	     * Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
	     * @param {Function} fn        The method the event invokes
	     * @param {Object}   scope    An object that becomes the scope of the handler
	     * @param {boolean}  options
	     */
	    onTextResize : function(fn, scope, options){
	        if(!textEvent){
	            textEvent = new Ext.util.Event();
	            var textEl = new Ext.Element(document.createElement('div'));
	            textEl.dom.className = 'x-text-resize';
	            textEl.dom.innerHTML = 'X';
	            textEl.appendTo(document.body);
	            textSize = textEl.dom.offsetHeight;
	            setInterval(function(){
	                if(textEl.dom.offsetHeight != textSize){
	                    textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
	                }
	            }, this.textResizeInterval);
	        }
	        textEvent.addListener(fn, scope, options);
	    },

/**
	     * Removes the passed window resize listener.
	     * @param {Function} fn        The method the event invokes
	     * @param {Object}   scope    The scope of handler
	     */
	    removeResizeListener : function(fn, scope){
	        if(resizeEvent){
	            resizeEvent.removeListener(fn, scope);
	        }
	    },

	    // private
	    fireResize : function(){
	        if(resizeEvent){
	            resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
	        }
	    },

/**
	     * The frequency, in milliseconds, to check for text resize events (defaults to 50)
	     */
	    textResizeInterval : 50,

/**
         * Url used for onDocumentReady with using SSL (defaults to Ext.SSL_SECURE_URL)
         */
        ieDeferSrc : false,

        // protected for use inside the framework
        // detects whether we should use keydown or keypress based on the browser.
        useKeydown: useKeydown
    };
}());

Ext.EventManager.on = Ext.EventManager.addListener;

Ext.apply(Ext.EventObjectImpl.prototype, {

/** Key constant @type Number */
    BACKSPACE: 8,

/** Key constant @type Number */
    TAB: 9,

/** Key constant @type Number */
    NUM_CENTER: 12,

/** Key constant @type Number */
    ENTER: 13,

/** Key constant @type Number */
    RETURN: 13,

/** Key constant @type Number */
    SHIFT: 16,

/** Key constant @type Number */
    CTRL: 17,
    CONTROL : 17, // legacy

/** Key constant @type Number */
    ALT: 18,

/** Key constant @type Number */
    PAUSE: 19,

/** Key constant @type Number */
    CAPS_LOCK: 20,

/** Key constant @type Number */
    ESC: 27,

/** Key constant @type Number */
    SPACE: 32,

/** Key constant @type Number */
    PAGE_UP: 33,
    PAGEUP : 33, // legacy

/** Key constant @type Number */
    PAGE_DOWN: 34,
    PAGEDOWN : 34, // legacy

/** Key constant @type Number */
    END: 35,

/** Key constant @type Number */
    HOME: 36,

/** Key constant @type Number */
    LEFT: 37,

/** Key constant @type Number */
    UP: 38,

/** Key constant @type Number */
    RIGHT: 39,

/** Key constant @type Number */
    DOWN: 40,

/** Key constant @type Number */
    PRINT_SCREEN: 44,

/** Key constant @type Number */
    INSERT: 45,

/** Key constant @type Number */
    DELETE: 46,

/** Key constant @type Number */
    ZERO: 48,

/** Key constant @type Number */
    ONE: 49,

/** Key constant @type Number */
    TWO: 50,

/** Key constant @type Number */
    THREE: 51,

/** Key constant @type Number */
    FOUR: 52,

/** Key constant @type Number */
    FIVE: 53,

/** Key constant @type Number */
    SIX: 54,

/** Key constant @type Number */
    SEVEN: 55,

/** Key constant @type Number */
    EIGHT: 56,

/** Key constant @type Number */
    NINE: 57,

/** Key constant @type Number */
    A: 65,

/** Key constant @type Number */
    B: 66,

/** Key constant @type Number */
    C: 67,

/** Key constant @type Number */
    D: 68,

/** Key constant @type Number */
    E: 69,

/** Key constant @type Number */
    F: 70,

/** Key constant @type Number */
    G: 71,

/** Key constant @type Number */
    H: 72,

/** Key constant @type Number */
    I: 73,

/** Key constant @type Number */
    J: 74,

/** Key constant @type Number */
    K: 75,

/** Key constant @type Number */
    L: 76,

/** Key constant @type Number */
    M: 77,

/** Key constant @type Number */
    N: 78,

/** Key constant @type Number */
    O: 79,

/** Key constant @type Number */
    P: 80,

/** Key constant @type Number */
    Q: 81,

/** Key constant @type Number */
    R: 82,

/** Key constant @type Number */
    S: 83,

/** Key constant @type Number */
    T: 84,

/** Key constant @type Number */
    U: 85,

/** Key constant @type Number */
    V: 86,

/** Key constant @type Number */
    W: 87,

/** Key constant @type Number */
    X: 88,

/** Key constant @type Number */
    Y: 89,

/** Key constant @type Number */
    Z: 90,

/** Key constant @type Number */
    CONTEXT_MENU: 93,

/** Key constant @type Number */
    NUM_ZERO: 96,

/** Key constant @type Number */
    NUM_ONE: 97,

/** Key constant @type Number */
    NUM_TWO: 98,

/** Key constant @type Number */
    NUM_THREE: 99,

/** Key constant @type Number */
    NUM_FOUR: 100,

/** Key constant @type Number */
    NUM_FIVE: 101,

/** Key constant @type Number */
    NUM_SIX: 102,

/** Key constant @type Number */
    NUM_SEVEN: 103,

/** Key constant @type Number */
    NUM_EIGHT: 104,

/** Key constant @type Number */
    NUM_NINE: 105,

/** Key constant @type Number */
    NUM_MULTIPLY: 106,

/** Key constant @type Number */
    NUM_PLUS: 107,

/** Key constant @type Number */
    NUM_MINUS: 109,

/** Key constant @type Number */
    NUM_PERIOD: 110,

/** Key constant @type Number */
    NUM_DIVISION: 111,

/** Key constant @type Number */
    F1: 112,

/** Key constant @type Number */
    F2: 113,

/** Key constant @type Number */
    F3: 114,

/** Key constant @type Number */
    F4: 115,

/** Key constant @type Number */
    F5: 116,

/** Key constant @type Number */
    F6: 117,

/** Key constant @type Number */
    F7: 118,

/** Key constant @type Number */
    F8: 119,

/** Key constant @type Number */
    F9: 120,

/** Key constant @type Number */
    F10: 121,

/** Key constant @type Number */
    F11: 122,

/** Key constant @type Number */
    F12: 123,

    /** @private */
    isNavKeyPress : function(){
        var me = this,
        	k = this.normalizeKey(me.keyCode);
        return (k >= 33 && k <= 40) ||  // Page Up/Down, End, Home, Left, Up, Right, Down
		k == me.RETURN ||
		k == me.TAB ||
		k == me.ESC;
    },

    isSpecialKey : function(){
        var k = this.normalizeKey(this.keyCode);
        return (this.type == 'keypress' && this.ctrlKey) ||
		this.isNavKeyPress() ||
        (k == this.BACKSPACE) || // Backspace
		(k >= 16 && k <= 20) || // Shift, Ctrl, Alt, Pause, Caps Lock
		(k >= 44 && k <= 45);   // Print Screen, Insert
    },

	getPoint : function(){
	    return new Ext.lib.Point(this.xy[0], this.xy[1]);
	},

/**
     * Returns true if the control, meta, shift or alt key was pressed during this event.
     * @return {Boolean}
     */
    hasModifier : function(){
        return ((this.ctrlKey || this.altKey) || this.shiftKey);
    }
});


text:
"Jason Williams" <jdw@cromulence.co>

### DARPA performer group
Cromulence LLC (CROMU)

## Description

This service is an fictional implementation of a radio receiver after demodulation. The service reads in raw data bits, acquires preamble lock, bit/byte synchronization and begins decoding packets and rendering them as they are received to stdout.

### Feature List

The service features preamble locking (0101010101 or 1010101010 sequence), bit/byte synchronization using 16-bits to acquire byte pattern lock, and checksums for packet integrity checking. Packets support 32-bit and 16-bit checksums as well as fragmentation. Fragmentation is optional and up to 16 fragments can be assembled into a full message packet. Fragmentation uses a fragmentation list to assemble packets with the same sequence numbers into a completed message. After reassembly a message is rendered using a combination of text markup (underline, bold, italics) and formatting characters (tabstop, break, paragraph, and newline) to standard output.

## Vulnerability

There are two vulnerabilities present in this service. The first vulnerability is in the packet fragmentation code. It is possible to send a packet outside of the maximum fragment number (a last packet bit signifies the maximum number of fragments to the reassembler). An invalid calculation of length occurs when the assembled size of the full message is calculated up all of the sub packets within range but during assembly all the packets are concatenated together resulting in a heap overwrite. The last bug is in the message renderer a stack overflow can occur when a message is assembled that exceeds the render buffer. This is possible becomes the render buffer naively assumes that full messages cannot exceed the number of bytes in a maximum fully assembled packet. The error exists due to the special formatting codes that result in writing data to the render buffer that exceeds 1-byte in length, therefore allowing a stack overflow to occur.

### Generic class of vulnerability

Improper calculation of Buffer Size
Out of bounds write

### CWE classification
CWE-131: Improper Calculation of Buffer Size
CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-121: Stack-based Buffer Overflow

## Challenges

This CB has two vulnerabilities. These vulnerabilities will require a CRS system to reason at the bit level to generate properly formatted packets. Proper state machine tracking is required in both cases as both vulnerabilities are accessible via packet fragmentation. As this service mimics an RF front-end (which is always subjected to noise) fuzzing will be statistically improbable to yield any results (unlikely to ever pass bit/byte synchronization let alone checksum verification of the packet).


text:
using ODDCIS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VDS.RDF;
using VDS.RDF.Query;

namespace ODDCIS.Query
{
    public class QueryHelper
    {
        private readonly Queries queries;
        public QueryHelper(Queries queries)
        {
            this.queries = queries;
        }
        public string GetQueryAllPredicates(IEnumerable<RdfNode> clases)
        {
            if (clases.ToList().Count > 0)
            {
                var query = queries.AllPredicatesOf;
                var classes = clases.Where(x => x.Type == RdfNodeType.Class).ToList();
                return query.Replace("@classTriplets", GetClassTriplets(classes));
            }
            return string.Empty;
        }

        public string GetQueryAllObjectsOf(Uri predicateUri)
        {
            var query = queries.AllObjectsOf;
            var parmeterizedString = new SparqlParameterizedString(query);
            parmeterizedString.SetUri("predicateUri", predicateUri);
            return parmeterizedString.ToSafeString();
        }

        public string GetQueryResults(IList<RdfNode> rdfNodes)
        {
            var query = queries.Results;
            return query.Replace("@triples", new ResultQueryMaker(rdfNodes).GetTriples());
        }

        public string GetQueryAllSubClassesOf(Uri superCLass)
        {
            var query = queries.AllSubClassesOf;
            var parmeterizedString = new SparqlParameterizedString(query);
            parmeterizedString.SetUri("superClass", superCLass);
            return parmeterizedString.ToSafeString();
        }

        public string GetSemanticQuery(IList<RdfNode> rdfNodes)
        {
            var query = string.Empty;
            foreach (var rdfNode in rdfNodes)
            {
                query += $"{rdfNode.Label} ";
            }

            return query;
        }

        #region Privates
        private string GetClassTriplets(IList<RdfNode> classes)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < classes.Count; i++)
            {
                sb.Append($" {{<{classes[i].Uri}> (rdfs:subClassOf|(owl:equivalentClass|^owl:equivalentClass))* ?super . ?item <{NamespaceMapper.RDFS}domain>  ?super .}} ");

                if (i != classes.Count - 1)
                {
                    sb.Append(" UNION ");
                }
            }
            return sb.ToString();
        }

        #endregion
    }
}