text:
package liquibase.integration.ant;

import liquibase.CatalogAndSchema;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.diff.output.DiffOutputControl;
import liquibase.diff.output.StandardObjectChangeFilter;
import liquibase.diff.output.changelog.DiffToChangeLog;
import liquibase.exception.DatabaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.integration.ant.type.ChangeLogOutputFile;
import liquibase.serializer.ChangeLogSerializer;
import liquibase.serializer.ChangeLogSerializerFactory;
import liquibase.serializer.core.json.JsonChangeLogSerializer;
import liquibase.serializer.core.string.StringChangeLogSerializer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.util.FileUtils;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashSet;
import java.util.Set;

public class GenerateChangeLogTask extends BaseLiquibaseTask {
    private Set<ChangeLogOutputFile> changeLogOutputFiles = new LinkedHashSet<>();
    private boolean includeSchema = true;
    private boolean includeCatalog = true;
    private boolean includeTablespace = true;
    private String includeObjects;
    private String excludeObjects;

    @Override
	public void executeWithLiquibaseClassloader() throws BuildException {
        Liquibase liquibase = getLiquibase();
        Database database = liquibase.getDatabase();
        CatalogAndSchema catalogAndSchema = buildCatalogAndSchema(database);
        DiffOutputControl diffOutputControl = getDiffOutputControl();
        DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffOutputControl);

        for(ChangeLogOutputFile changeLogOutputFile : changeLogOutputFiles) {
            String encoding = getOutputEncoding(changeLogOutputFile);
            PrintStream printStream = null;
            try {
                FileResource outputFile = changeLogOutputFile.getOutputFile();
                ChangeLogSerializer changeLogSerializer = changeLogOutputFile.getChangeLogSerializer();
                log("Writing change log file " + outputFile.toString(), Project.MSG_INFO);
                printStream = new PrintStream(outputFile.getOutputStream(), true, encoding);
                liquibase.generateChangeLog(catalogAndSchema, diffToChangeLog, printStream, changeLogSerializer);
            } catch (UnsupportedEncodingException e) {
                throw new BuildException("Unable to generate a change log. Encoding [" + encoding + "] is not supported.", e);
            } catch (IOException e) {
                throw new BuildException("Unable to generate a change log. Error creating output stream.", e);
            } catch (ParserConfigurationException e) {
                throw new BuildException("Unable to generate a change log. Error configuring parser.", e);
            } catch (DatabaseException e) {
                throw new BuildException("Unable to generate a change log: " + e.getMessage(), e);
            } finally {
                FileUtils.close(printStream);
            }
        }
	}

    @Override
    protected void validateParameters() {
        super.validateParameters();

        if((changeLogOutputFiles == null) || changeLogOutputFiles.isEmpty()) {
            throw new BuildException("Unable to generate a change log. No output file defined. Add at least one <xml>, <json>, <yaml>, or <txt> nested element.");
        }
    }

    private String getOutputEncoding(ChangeLogOutputFile changeLogOutputFile) {
        String encoding = changeLogOutputFile.getEncoding();
        return (encoding == null) ? getDefaultOutputEncoding() : encoding;
    }

    private CatalogAndSchema buildCatalogAndSchema(Database database) {
        return new CatalogAndSchema(database.getDefaultCatalogName(), database.getDefaultSchemaName());
    }

    private DiffOutputControl getDiffOutputControl() {
        DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace, null);

        if ((excludeObjects != null) && (includeObjects != null)) {
            throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
        }
        if (excludeObjects != null) {
            diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects));
        }
        if (includeObjects != null) {
            diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects));
        }

        return diffOutputControl;
    }

    public void addConfiguredJson(ChangeLogOutputFile changeLogOutputFile) {
        changeLogOutputFile.setChangeLogSerializer(new JsonChangeLogSerializer());
        changeLogOutputFiles.add(changeLogOutputFile);
    }

    public void addConfiguredXml(ChangeLogOutputFile changeLogOutputFile) {
        changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("xml"));
        changeLogOutputFiles.add(changeLogOutputFile);
    }

    public void addConfiguredYaml(ChangeLogOutputFile changeLogOutputFile) {
        changeLogOutputFile.setChangeLogSerializer(ChangeLogSerializerFactory.getInstance().getSerializer("yaml"));
        changeLogOutputFiles.add(changeLogOutputFile);
    }

    public void addConfiguredTxt(ChangeLogOutputFile changeLogOutputFile) {
        changeLogOutputFile.setChangeLogSerializer(new StringChangeLogSerializer());
        changeLogOutputFiles.add(changeLogOutputFile);
    }

    public boolean getIncludeCatalog() {
        return includeCatalog;
    }

    public void setIncludeCatalog(boolean includeCatalog) {
        this.includeCatalog = includeCatalog;
    }

    public boolean getIncludeSchema() {
        return includeSchema;
    }

    public void setIncludeSchema(boolean includeSchema) {
        this.includeSchema = includeSchema;
    }

    public boolean getIncludeTablespace() {
        return includeTablespace;
    }

    public void setIncludeTablespace(boolean includeTablespace) {
        this.includeTablespace = includeTablespace;
    }

    public String getIncludeObjects() {
        return includeObjects;
    }

    public void setIncludeObjects(String includeObjects) {
        this.includeObjects = includeObjects;
    }

    public String getExcludeObjects() {
        return excludeObjects;
    }

    public void setExcludeObjects(String excludeObjects) {
        this.excludeObjects = excludeObjects;
    }
}


text:
import {Component} from "../../widgets/component";
import {Column} from "../../entities/column";
import {Utils as _} from "../../utils";
import {ColumnGroup} from "../../entities/columnGroup";
import {ColumnApi} from "../../columnController/columnApi";
import {ColumnController} from "../../columnController/columnController";
import {GridOptionsWrapper} from "../../gridOptionsWrapper";
import {HorizontalDragService} from "../horizontalDragService";
import {Autowired, Context, PostConstruct} from "../../context/context";
import {CssClassApplier} from "../cssClassApplier";
import {
    DragAndDropService,
    DragItem,
    DragSource,
    DragSourceType,
    DropTarget
} from "../../dragAndDrop/dragAndDropService";
import {SetLeftFeature} from "../../rendering/features/setLeftFeature";
import {IHeaderGroupComp, IHeaderGroupParams} from "./headerGroupComp";
import {GridApi} from "../../gridApi";
import {ComponentRecipes} from "../../components/framework/componentRecipes";
import {Beans} from "../../rendering/beans";

export class HeaderGroupWrapperComp extends Component {

    private static TEMPLATE =
        '
' +
          '

' +
        '
';

    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
    @Autowired('columnController') private columnController: ColumnController;
    @Autowired('horizontalDragService') private dragService: HorizontalDragService;
    @Autowired('dragAndDropService') private dragAndDropService: DragAndDropService;
    @Autowired('context') private context: Context;
    @Autowired('componentRecipes') private componentRecipes: ComponentRecipes;
    @Autowired('gridApi') private gridApi: GridApi;
    @Autowired('columnApi') private columnApi: ColumnApi;
    @Autowired('beans') private beans: Beans;

    private columnGroup: ColumnGroup;
    private dragSourceDropTarget: DropTarget;
    private pinned: string;
    private eRoot: HTMLElement;

    private eHeaderCellResize: HTMLElement;
    private groupWidthStart: number;
    private childrenWidthStarts: number[];

    // the children can change, we keep destroy functions related to listening to the children here
    private childColumnsDestroyFuncs: Function[] = [];

    constructor(columnGroup: ColumnGroup, eRoot: HTMLElement, dragSourceDropTarget: DropTarget, pinned: string) {
        super(HeaderGroupWrapperComp.TEMPLATE);
        this.columnGroup = columnGroup;
        this.eRoot = eRoot;
        this.dragSourceDropTarget = dragSourceDropTarget;
        this.pinned = pinned;
    }

    @PostConstruct
    private postConstruct(): void {

        CssClassApplier.addHeaderClassesFromColDef(this.columnGroup.getColGroupDef(), this.getGui(), this.gridOptionsWrapper, null, this.columnGroup);

        let displayName = this.columnController.getDisplayNameForColumnGroup(this.columnGroup, 'header');

        this.appendHeaderGroupComp(displayName);

        this.setupResize();
        this.addClasses();
        this.setupWidth();
        this.addAttributes();
        this.setupMovingCss();

        let setLeftFeature = new SetLeftFeature(this.columnGroup, this.getGui(), this.beans);
        setLeftFeature.init();
        this.addDestroyFunc(setLeftFeature.destroy.bind(setLeftFeature));
    }

    private setupMovingCss(): void {
        let originalColumnGroup = this.columnGroup.getOriginalColumnGroup();
        let leafColumns = originalColumnGroup.getLeafColumns();
        leafColumns.forEach( col => {
            this.addDestroyableEventListener(col, Column.EVENT_MOVING_CHANGED, this.onColumnMovingChanged.bind(this));
        });
        this.onColumnMovingChanged();
    }

    private onColumnMovingChanged(): void {
        // this function adds or removes the moving css, based on if the col is moving.
        // this is what makes the header go dark when it is been moved (gives impression to
        // user that the column was picked up).
        if (this.columnGroup.isMoving()) {
            _.addCssClass(this.getGui(), 'ag-header-cell-moving');
        } else {
            _.removeCssClass(this.getGui(), 'ag-header-cell-moving');
        }
    }

    private addAttributes(): void {
        this.getGui().setAttribute("col-id", this.columnGroup.getUniqueId());
    }

    private appendHeaderGroupComp(displayName: string): void {
        let params: IHeaderGroupParams = {
            displayName: displayName,
            columnGroup: this.columnGroup,
            setExpanded: (expanded:boolean)=>{
                this.columnController.setColumnGroupOpened(this.columnGroup.getOriginalColumnGroup(), expanded);
            },
            api: this.gridApi,
            columnApi: this.columnApi,
            context: this.gridOptionsWrapper.getContext()
        };

        if(!displayName) {
            let leafCols = this.columnGroup.getLeafColumns();
            displayName = leafCols ? leafCols[0].getColDef().headerName : '';
        }

        let callback = this.afterHeaderCompCreated.bind(this, displayName);

        this.componentRecipes.newHeaderGroupComponent(params).then(callback);
    }

    private afterHeaderCompCreated(displayName: string, headerGroupComp: IHeaderGroupComp): void {
        this.appendChild(headerGroupComp);
        this.setupMove(headerGroupComp.getGui(), displayName);

        if (headerGroupComp.destroy) {
            this.addDestroyFunc(headerGroupComp.destroy.bind(headerGroupComp));
        }
    }

    private addClasses(): void {
        // having different classes below allows the style to not have a bottom border
        // on the group header, if no group is specified
        // columnGroup.getColGroupDef
        if (this.columnGroup.isPadding()) {
            this.addCssClass('ag-header-group-cell-no-group');
        } else {
            this.addCssClass('ag-header-group-cell-with-group');
        }
    }

    private setupMove(eHeaderGroup: HTMLElement, displayName: string): void {
        if (!eHeaderGroup) { return; }

        if (this.isSuppressMoving()) { return; }

        let allLeafColumns = this.columnGroup.getOriginalColumnGroup().getLeafColumns();

        if (eHeaderGroup) {
            let dragSource: DragSource = {
                type: DragSourceType.HeaderCell,
                eElement: eHeaderGroup,
                dragItemName: displayName,
                // we add in the original group leaf columns, so we move both visible and non-visible items
                dragItemCallback: this.getDragItemForGroup.bind(this),
                dragSourceDropTarget: this.dragSourceDropTarget,
                dragStarted: () => allLeafColumns.forEach( col => col.setMoving(true) ),
                dragStopped: () => allLeafColumns.forEach( col => col.setMoving(false) )
            };
            this.dragAndDropService.addDragSource(dragSource, true);
            this.addDestroyFunc( ()=> this.dragAndDropService.removeDragSource(dragSource) );
        }
    }

    // when moving the columns, we want to move all the columns (contained within the DragItem) in this group in one go,
    // and in the order they are currently in the screen.
    public getDragItemForGroup(): DragItem {
        let allColumnsOriginalOrder = this.columnGroup.getOriginalColumnGroup().getLeafColumns();

        // capture visible state, used when reentering grid to dictate which columns should be visible
        let visibleState: { [key: string]: boolean } = {};
        allColumnsOriginalOrder.forEach(column => visibleState[column.getId()] = column.isVisible());

        let allColumnsCurrentOrder: Column[] = [];
        this.columnController.getAllDisplayedColumns().forEach(column => {
            if (allColumnsOriginalOrder.indexOf(column) >= 0) {
                allColumnsCurrentOrder.push(column);
                _.removeFromArray(allColumnsOriginalOrder, column);
            }
        });

        // we are left with non-visible columns, stick these in at the end
        allColumnsOriginalOrder.forEach(column => allColumnsCurrentOrder.push(column));

        // create and return dragItem
        return {
            columns: allColumnsCurrentOrder,
            visibleState: visibleState
        };
    }

    private isSuppressMoving(): boolean {
        // if any child is fixed, then don't allow moving
        let childSuppressesMoving = false;
        this.columnGroup.getLeafColumns().forEach( (column: Column) => {
            if (column.getColDef().suppressMovable) {
                childSuppressesMoving = true;
            }
        });

        let result = childSuppressesMoving
            || this.gridOptionsWrapper.isSuppressMovableColumns()
            || this.gridOptionsWrapper.isForPrint();

        return result;
    }

    private setupWidth(): void {

        // we need to listen to changes in child columns, as they impact our width
        this.addListenersToChildrenColumns();

        // the children belonging to this group can change, so we need to add and remove listeners as they change
        this.addDestroyableEventListener(this.columnGroup, ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED, this.onDisplayedChildrenChanged.bind(this));

        this.onWidthChanged();

        // the child listeners are not tied to this components lifecycle, as children can get added and removed
        // to the group - hence they are on a different lifecycle. so we must make sure the existing children
        // listeners are removed when we finally get destroyed
        this.addDestroyFunc(this.destroyListenersOnChildrenColumns.bind(this));
    }

    private onDisplayedChildrenChanged(): void {
        this.addListenersToChildrenColumns();
        this.onWidthChanged();
    }

    private addListenersToChildrenColumns(): void {
        // first destroy any old listeners
        this.destroyListenersOnChildrenColumns();

        // now add new listeners to the new set of children
        let widthChangedListener = this.onWidthChanged.bind(this);
        this.columnGroup.getLeafColumns().forEach( column => {
            column.addEventListener(Column.EVENT_WIDTH_CHANGED, widthChangedListener);
            column.addEventListener(Column.EVENT_VISIBLE_CHANGED, widthChangedListener);
            this.childColumnsDestroyFuncs.push( ()=> {
                column.removeEventListener(Column.EVENT_WIDTH_CHANGED, widthChangedListener);
                column.removeEventListener(Column.EVENT_VISIBLE_CHANGED, widthChangedListener);
            });
        });
    }

    private destroyListenersOnChildrenColumns(): void {
        this.childColumnsDestroyFuncs.forEach( func => func() );
        this.childColumnsDestroyFuncs = [];
    }

    private onWidthChanged(): void {
        this.getGui().style.width = this.columnGroup.getActualWidth() + 'px';
    }

    private setupResize(): void {
        this.eHeaderCellResize = this.getRefElement('agResize');

        if (!this.columnGroup.isResizable()) {
            _.removeFromParent(this.eHeaderCellResize);
            return;
        }

        this.dragService.addDragHandling({
            eDraggableElement: this.eHeaderCellResize,
            eBody: this.eRoot,
            cursor: 'col-resize',
            startAfterPixels: 0,
            onDragStart: this.onDragStart.bind(this),
            onDragging: this.onDragging.bind(this)
        });

        if (!this.gridOptionsWrapper.isSuppressAutoSize()) {
            this.eHeaderCellResize.addEventListener('dblclick', (event:MouseEvent) => {
                // get list of all the column keys we are responsible for
                let keys: string[] = [];
                this.columnGroup.getDisplayedLeafColumns().forEach( (column: Column)=>{
                    // not all cols in the group may be participating with auto-resize
                    if (!column.getColDef().suppressAutoSize) {
                        keys.push(column.getColId());
                    }
                });
                if (keys.length>0) {
                    this.columnController.autoSizeColumns(keys);
                }
            });
        }
    }

    public onDragStart(): void {
        this.groupWidthStart = this.columnGroup.getActualWidth();
        this.childrenWidthStarts = [];
        this.columnGroup.getDisplayedLeafColumns().forEach( (column: Column) => {
            this.childrenWidthStarts.push(column.getActualWidth());
        });
    }

    public onDragging(dragChange: any, finished: boolean): void {

        // this will be the width we have to distribute to the resizable columns
        let widthForResizableCols: number;
        // this is all the displayed cols in the group less those that we cannot resize
        let resizableCols: Column[];

        // a lot of variables defined for the first set of maths, but putting
        // braces in, we localise the variables to this bit of the method
        {
            let dragChangeNormalised = this.normaliseDragChange(dragChange);
            let totalGroupWidth = this.groupWidthStart + dragChangeNormalised;

            let displayedColumns = this.columnGroup.getDisplayedLeafColumns();
            resizableCols = _.filter(displayedColumns, col => col.isResizable());
            let nonResizableCols = _.filter(displayedColumns, col => !col.isResizable());

            let nonResizableColsWidth = 0;
            nonResizableCols.forEach( col => nonResizableColsWidth += col.getActualWidth() );

            widthForResizableCols = totalGroupWidth - nonResizableColsWidth;

            let minWidth = 0;
            resizableCols.forEach( col => minWidth += col.getMinWidth() );

            if (widthForResizableCols < minWidth) {
                widthForResizableCols = minWidth;
            }
        }

        // distribute the new width to the child headers
        let changeRatio = widthForResizableCols / this.groupWidthStart;
        // keep track of pixels used, and last column gets the remaining,
        // to cater for rounding errors, and min width adjustments
        let pixelsToDistribute = widthForResizableCols;

        resizableCols.forEach( (column: Column, index: any) => {
            let notLastCol = index !== (resizableCols.length - 1);
            let newChildSize: any;
            if (notLastCol) {
                // if not the last col, calculate the column width as normal
                let startChildSize = this.childrenWidthStarts[index];
                newChildSize = startChildSize * changeRatio;
                if (newChildSize < column.getMinWidth()) {
                    newChildSize = column.getMinWidth();
                }
                pixelsToDistribute -= newChildSize;
            } else {
                // if last col, give it the remaining pixels
                newChildSize = pixelsToDistribute;
            }
            this.columnController.setColumnWidth(column, newChildSize, finished);
        });
    }

    // optionally inverts the drag, depending on pinned and RTL
    // note - this method is duplicated in RenderedHeaderCell - should refactor out?
    private normaliseDragChange(dragChange: number): number {
        let result = dragChange;
        if (this.gridOptionsWrapper.isEnableRtl()) {
            // for RTL, dragging left makes the col bigger, except when pinning left
            if (this.pinned !== Column.PINNED_LEFT) {
                result *= -1;
            }
        } else {
            // for LTR (ie normal), dragging left makes the col smaller, except when pinning right
            if (this.pinned === Column.PINNED_RIGHT) {
                result *= -1;
            }
        }
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Timer Extension Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          CNLFoundationTools Docs

         (99% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

      CNLFoundationTools Reference

      Timer Extension Reference

            Guides

                README

            Classes

                CNLAssociated

                CNLURLCache

            Enums

                CNLLogLevel

            Extensions

                Array

                CLLocation

                CLLocationCoordinate2D

                Data

                Date

                Dictionary

                Int

                NSAttributedString

                String

                TimeZone

                Timer

            Functions

                -->(_:_:)

                -->(_:_:)

                -->(_:_:)

                -->(_:_:)

                <=(_:_:)

                >=(_:_:)

                CNLLog(_:level:)

                CNLLog(_:level:separator:)

                asyncGlobal(_:)

                asyncGlobal(_:_:)

                asyncGlobal(_:_:)

                asyncMain(_:)

                asyncMain(_:_:)

                asyncMain(_:_:)

                syncCritical(_:_:)

                syncMain(_:)

            Protocols

                CNLDictionaryKey

                CNLDictionaryValue

            Structs

                CNLDeepLink

                CNLDeepLinkComponents

                CNLDeepLinkParameters

                CNLLocationCoordinate2DRect

                CNLLogger

            Typealiases

                CNLArray

                CNLDictionary

Timer

Undocumented

                    schedule(delay:handler:)

Creates disposable timer and schedule it to invoke handler after delay

Declaration

Swift

public class func schedule(delay: TimeInterval, handler: @escaping (Timer?) -> Void) -> Timer?

Parameters

                                delay

Delay (seconds)

                                handler

Closure to be invoked

Return Value

Timer instance

                    schedule(delay:repeatInterval:handler:)

Creates timer and schedule it to invoke handler after delay, repeating with specified interval

Declaration

Swift

public class func schedule(delay: TimeInterval = 0.0, repeatInterval interval: TimeInterval, handler: @escaping (Timer?) -> Void) -> Timer?

Parameters

                                interval

Repeating interval

                                handler

Closure to be invoked

Return Value

Timer instance

© 2017 Complex Numbers. All rights reserved. (Last updated: 2017-07-07)

Generated by jazzy ♪♫ v0.8.2, a Realm project.


text:
Welcome to Instruction Follower's documentation!
================================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   main.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package im.actor.crypto.primitives.streebog;

import im.actor.crypto.primitives.Digest;

public class Streebog256 implements Digest {

    private static final int DIGEST_SIZE = 32;

    private StreebogDigest streebogDigest = new StreebogDigest(DIGEST_SIZE);

    @Override
    public void reset() {
        streebogDigest.reset();
    }

    @Override
    public void update(byte[] src, int offset, int length) {
        streebogDigest.update(src, offset, length);
    }

    @Override
    public void doFinal(byte[] dest, int destOffset) {
        streebogDigest.doFinal(dest, destOffset);
    }

    @Override
    public int getDigestSize() {
        return DIGEST_SIZE;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Melanospora fayodi Vuill.

### Remarks
null


text:
int main(int, char const **)
{
    std::cout << "Hello World!" << std::endl;
    seqan::CharString mySeqanString = "Hello SeqAn!";
    std::cout << mySeqanString << std::endl;
    return 1;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "The Final Countdown"</title>
		<link>http://bvs.wikidot.com/forum/t-126819/the-final-countdown</link>
		<description>Posts in the discussion thread "The Final Countdown"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:44:40 +0000</lastBuildDate>

				</channel>
</rss>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.define('sisprod.view.Reports.ChemicalTreatmentReports', {
    extend: 'sisprod.view.base.TabPanelItem',
    closable: true,
    height: 300,
    messages: {
        reportTitle: 'Chemical Treatment',
        labels: {
            year: 'Year',
            month: 'Month',
            print: 'Print',
            resetForm: 'Clear'
        },
        message: 'Message',
        selectFirst: 'Select a year first...'
    },
    layout: {
        type: 'vbox',
        align: 'center'
    },
    padding: '20 0 0 0',
    initComponent: function() {
        var me = this;
        me.items = new Array();
        var form = Ext.create('Ext.form.Panel', {
            title: me.messages.reportTitle,
            frame: true,
            defaults: {
                labelWidth: 120
            },
            layout: {
                type: 'anchor'
            },
            items: [{
                    xtype: 'combobox',
                    name: 'idYear',
                    id: 'idYear',
                    store: Ext.create('sisprod.store.ChemicalTreatmentYearsAll'),
                    fieldLabel: me.messages.labels.year,
                    displayField: 'year',
                    valueField: 'year',
                    forceSelection: true,
                    allowBlank: false
                },
                {
                    xtype: 'combobox',
                    name: 'idMonth',
                    id: 'idMonth',
                    store: Ext.create('sisprod.store.ChemicalTreatmentMonthsStore', {
                        listeners: {
                            beforeload: function(store, operation, options) {
                                var idYear= me.down('#idYear').getValue();
                                if(Ext.isDefined(idYear) && idYear !== null) {
                                    if(Ext.isDefined(operation.params) && operation.params !== null)
                                        operation.params.idYear = idYear;
                                    else
                                        operation.params = {query: '', idYear: idYear};

                                } else {
                                    Ext.Msg.alert(me.messages.message, me.messages.selectFirst);
                                    return false;
                                }
                            }
                        }
                    }),
                    fieldLabel: me.messages.labels.month,
                    displayField: 'monthName',
                    valueField: 'idMonth',
                    forceSelection: true,
                    allowBlank: false
                }
            ],
            buttons: [
                {
                    id: 'btnPrintChemicalTreatmentReport',
                    iconCls: 'print',
                    text: me.messages.labels.print,
                    handler: function() {
                        if (form.getForm().isValid) {
                            var values = form.getValues();
                            var dias = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                            var repoLink = Ext.String.format("reports.htm?reportName=chemical_treatment.rptdesign&rp_start_date={0}" +
                                    "&rp_end_date={1}&rp_Title={2}", values['idYear'] + '-' + values['idMonth'] + '-01',
                                    values['idYear'] + '-' + values['idMonth'] + '-' + dias[values['idMonth']], 'REPORTE TRATAMIENTO QUÍMICO ' + form.down("#idMonth").getRawValue() + ' - ' + values['idYear']);
                            var printWindow = Ext.create('sisprod.view.base.BasePrintWindow', {
                                controller: me.controller,
                                forPrintingList: false,
                                formData: {
                                    url: repoLink,
                                    defaultFormat: sisprod.BasePrintWindow.XLS,
                                    selectableFormat: false,
                                    hiddenTitle: true
                                }
                            });
                            printWindow.show();
                        }
                    }
                },
                {
                    id: 'btnClearChemicalTreatmentReports',
                    text: me.messages.labels.resetForm,
                    iconCls: 'clear',
                    handler: function() {
                        form.getForm().reset();
                    }
                }
            ]
        });
        me.items.push(form);
        me.callParent(arguments);
    }
});


text:
using namespace engine;

Level* LevelParser::parseLevel(const char *levelFile){
	// create a TinyXML document and load the map XML
	TiXmlDocument levelDocument;
	levelDocument.LoadFile(levelFile);

	// create the level object
	Level* pLevel = new Level();

	// get the root node
	TiXmlElement* pRoot = levelDocument.RootElement();

	pRoot->Attribute("tilewidth", &m_tileSize);
	pRoot->Attribute("width", &m_width);
	pRoot->Attribute("height", &m_height);

	TiXmlElement* pProperties = 0;

	// parse the tilesets
	for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){
		if(e->Value() == std::string("tileset")){
			parseTilesets(e, pLevel->getTilesets());
		} else if(e->Value() == std::string("properties")){
			pProperties = e;
		}
	}

	for(TiXmlElement* e = pProperties->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){
		if(e->Value() == std::string("property")){
			parseTextures(e);
		}
	}

	// parse any object layers
	for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){
		if(e->Value() == std::string("layer") || e->Value() == std::string("objectgroup")){
			if(e->FirstChildElement()->Value() == std::string("object")){
				parseObjectLayer(e, pLevel->getLayers(), pLevel);
			} else if(e->FirstChildElement()->Value() == std::string("data")){
				parseTileLayer(e, pLevel->getLayers(), pLevel->getTilesets());
			}
		}
	}
	return pLevel;
}

void LevelParser::parseTilesets(TiXmlElement* pTilesetRoot, std::vector<Tileset>* pTilesets){
	std::string s = pTilesetRoot->FirstChildElement()->Attribute("source");
	s = "assets/" + s;

	// first add the tileset to texture manager
	TextureManager::Instance().load(
			s,
			pTilesetRoot->Attribute("name"),
			Game::Instance().getRenderer());

	// create tileset object
	Tileset tileset;
	pTilesetRoot->FirstChildElement()->Attribute("width", &tileset.width);
	pTilesetRoot->FirstChildElement()->Attribute("height", &tileset.height);
	pTilesetRoot->Attribute("firstgid", &tileset.firstGridID);
	pTilesetRoot->Attribute("tilewidth", &tileset.tileWidth);
	pTilesetRoot->Attribute("tileheight", &tileset.tileHeight);
	pTilesetRoot->Attribute("spacing", &tileset.spacing);
	pTilesetRoot->Attribute("margin", &tileset.margin);
	tileset.name = pTilesetRoot->Attribute("name");

	tileset.numColumns = tileset.width / (tileset.tileWidth + tileset.spacing);

	pTilesets->push_back(tileset);
}

void LevelParser::parseTileLayer(TiXmlElement* pTileElement, std::vector<Layer*> *pLayers, const std::vector<Tileset>* pTilesets){
	TileLayer* pTileLayer = new TileLayer(m_tileSize, *pTilesets);

	//tile data
	std::vector<std::vector<int> > data;

	std::string decodedIDs;
	TiXmlElement* pDataNode;

	for(auto e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){
		if(e->Value() == std::string("data")){
			pDataNode = e;
		}
	}

	for(auto e = pDataNode->FirstChild(); e != NULL; e = e->NextSiblingElement()){
		auto text = e->ToText();
		auto t = text->Value();
		decodedIDs = base64_decode(t);
	}

	// uncompress zlib compression
	uLongf numGids = m_width * m_height * sizeof(int);
	std::vector<unsigned> gids(numGids);
	uncompress((Bytef*)&gids[0], &numGids,(const Bytef*)decodedIDs.c_str(), decodedIDs.size());

	std::vector<int> layerRow(m_width);

	for(int j = 0; j < m_height; j++){
		data.push_back(layerRow);
	}

	for(int rows = 0; rows < m_height; rows++){
		for(int cols = 0; cols < m_width; cols++){
			data[rows][cols] = gids[rows * m_width + cols];
		}
	}

	pTileLayer->setTileIDs(data);

	pLayers->push_back(pTileLayer);
}

void LevelParser::parseTextures(TiXmlElement* root){
	TextureManager::Instance().load(root->Attribute("value"), root->Attribute("name"), Game::Instance().getRenderer());
}

void LevelParser::parseObjectLayer(TiXmlElement* pObjectElement, std::vector<Layer*> *pLayers, Level* pLevel){
	ObjectLayer* pObjectLayer = new ObjectLayer();
	for(TiXmlElement* e = pObjectElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement()){
		if(e->Value() == std::string("object")){
			int x, y, width, height, numFrames, callbackID, animSpeed, colliderWidth, colliderHeight;
			std::string textureID;
			// get the initial node values type, x and y
			e->Attribute("x", &x);
			e->Attribute("y", &y);
			GameObject* pGameObject = GameObjectFactory::Instance().create(e->Attribute("type"));
			// get the property values
			for(TiXmlElement* properties = e->FirstChildElement(); properties != NULL; properties = properties->NextSiblingElement()){
				if(properties->Value() == std::string("properties")){
					for(TiXmlElement* property = properties->FirstChildElement(); property != NULL; property = property->NextSiblingElement()){
							if(property->Value() == std::string("property")){
								std::cout << property->Attribute("name") << std::endl;

								if(property->Attribute("name") == std::string("colliderHeight")){
									property->Attribute("value", &colliderHeight);
								} else if(property->Attribute("name") == std::string("colliderWidth")){
									property->Attribute("value", &colliderWidth);
								} else if(property->Attribute("name") == std::string("numFrames")){
									property->Attribute("value", &numFrames);
								} else if(property->Attribute("name") == std::string("textureHeight")){
									property->Attribute("value", &height);
								} else if(property->Attribute("name") == std::string("textureID")){
									textureID = property->Attribute("value");
								} else if(property->Attribute("name") == std::string("textureWidth")){
									property->Attribute("value", &width);
								} else if(property->Attribute("name") == std::string("callbackID")){
									property->Attribute("value", &callbackID);
								} else if(e->Attribute("name") == std::string("animSpeed")){
									property->Attribute("value", &animSpeed);
								}
							}
						}
					}
				}

			if(strcmp(e->Attribute("type"), "XuxaBoss") == 0){
				pLevel->setXuxa(dynamic_cast<XuxaBoss*>(pGameObject));
			}

			if(strcmp(e->Attribute("type"), "Player") == 0){
				pLevel->setPlayer(dynamic_cast<Player*>(pGameObject));
			}

			pGameObject->load(new
			LoaderParams(x, y, width, height, textureID, numFrames, callbackID, animSpeed, 0, colliderWidth, colliderHeight));
			pObjectLayer->getGameObjects()->push_back(pGameObject);
		}
	}
	pLayers->push_back(pObjectLayer);
}


text:
#ifndef ALIANALYSISTASKDIJETS_H
#define ALIANALYSISTASKDIJETS_H

#include "AliAnalysisTaskSE.h"
#include <TList.h>
#include <TH1F.h>
#include <TH2F.h>

class AliAnalysisTaskDiJets : public AliAnalysisTaskSE
{
 public:
    AliAnalysisTaskDiJets();
    AliAnalysisTaskDiJets(const char* name);
    virtual ~AliAnalysisTaskDiJets() {;}

    // Implementation of interface methods
    virtual void UserCreateOutputObjects();
    virtual void Init();
    virtual void LocalInit() {Init();}
    virtual void UserExec(Option_t *option);
    virtual void Terminate(Option_t *option);

    void SetAODInput(Bool_t b)   {fUseAODInput = b;}
    void SetFillAOD(Bool_t fill) { fFillAOD=fill; }
    void SetJetBranch(const Char_t *br){ fJetBranch=br; }

 private:
  AliAnalysisTaskDiJets(const AliAnalysisTaskDiJets &det);
  AliAnalysisTaskDiJets &operator=(const AliAnalysisTaskDiJets &det);

 private:
  TClonesArray* fDiJets;    // Array of dijets
  TClonesArray* fDiJetsIn;  // Array of dijets

  Bool_t        fUseAODInput; // read jets from input AOD
  Bool_t        fFillAOD;   // option to fill AOD branch
  TString       fJetBranch; // jet branch to read

  AliAODEvent  *fAOD;       // AOD event
  TList        *fHistList;  // Output list

  TH1F         *fH1DeltaPt;  // Pt difference
  TH1F         *fH1DeltaPhi; // delta phi plot in (0,pi)
  TH1F         *fH1PhiImbal; // phi imbalance (-pi,pi)
  TH1F         *fH1Asym;     // asymmetry of the dijet
  TH2F         *fH2Pt2vsPt1; // scatter plot with the two jets' Pt
  TH2F         *fH2DifvsSum; // Pt difference vs Pt sum

  ClassDef(AliAnalysisTaskDiJets, 2) // Analysis task for standard dijet analysis
};

#endif


text:
package me.id.webverifylib.listener;

import me.id.webverifylib.IDmeProfile;

/**
 * Listener to get the user profile information
 */
public interface IDmeGetProfileListener {
  void onSuccess(IDmeProfile profile);
  void onError(Throwable throwable);
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Beih. Sydowia 4: 104 (1961)

#### Original name
Cyphella conglobata Burt, 1914

### Remarks
null


text:
NSString* const NIStylesheetDidChangeNotification = @"NIStylesheetDidChangeNotification";

@interface NIStylesheet()
@property (nonatomic, readonly, copy) NSDictionary* rawRulesets;
@property (nonatomic, readonly, copy) NSDictionary* significantScopeToScopes;
@end

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation NIStylesheet

@synthesize rawRulesets = _rawRulesets;
@synthesize significantScopeToScopes = _significantScopeToScopes;

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init {
  if ((self = [super init])) {
    _ruleSets = [[NSMutableDictionary alloc] init];

    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc addObserver: self
           selector: @selector(didReceiveMemoryWarning:)
               name: UIApplicationDidReceiveMemoryWarningNotification
             object: nil];
  }

  return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Rule Sets

///////////////////////////////////////////////////////////////////////////////////////////////////
// Builds a map of significant scopes to full scopes.
//
// For example, consider the following rulesets:
//
// .root UIButton {
// }
// .apple UIButton {
// }
// UIButton UIView {
// }
// UIView {
// }
//
// The generated scope map will look like:
//
// UIButton => (.root UIButton, .apple UIButton)
// UIView => (UIButton UIView, UIView)
//
- (void)rebuildSignificantScopeToScopes {
  NSMutableDictionary* significantScopeToScopes =
  [[NSMutableDictionary alloc] initWithCapacity:[_rawRulesets count]];

  for (NSString* scope in _rawRulesets) {
    NSArray* parts = [scope componentsSeparatedByString:@" "];
    NSString* mostSignificantScopePart = [parts lastObject];

    // TODO (jverkoey Oct 6, 2011): We should respect CSS specificity. Right now this will
    // give higher precedance to newer styles. Instead, we should prefer styles that have more
    // selectors.
    NSMutableArray* scopes = [significantScopeToScopes objectForKey:mostSignificantScopePart];
    if (nil == scopes) {
      scopes = [[NSMutableArray alloc] initWithObjects:scope, nil];
      [significantScopeToScopes setObject:scopes forKey:mostSignificantScopePart];

    } else {
      [scopes addObject:scope];
    }
  }

  _significantScopeToScopes = [significantScopeToScopes copy];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)ruleSetsDidChange {
  [self rebuildSignificantScopeToScopes];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - NSNotifications

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)reduceMemory {
  _ruleSets = [[NSMutableDictionary alloc] init];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didReceiveMemoryWarning:(void*)object {
  [self reduceMemory];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Public Methods

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)loadFromPath:(NSString *)path {
  return [self loadFromPath:path pathPrefix:nil delegate:nil];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)loadFromPath:(NSString *)path pathPrefix:(NSString *)pathPrefix {
  return [self loadFromPath:path pathPrefix:pathPrefix delegate:nil];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)loadFromPath:(NSString *)path
          pathPrefix:(NSString *)pathPrefix
            delegate:(id<NICSSParserDelegate>)delegate {
  BOOL loadDidSucceed = NO;

  @synchronized(self) {
    _rawRulesets = nil;
    _significantScopeToScopes = nil;

    _ruleSets = [[NSMutableDictionary alloc] init];

    NICSSParser* parser = [[NICSSParser alloc] init];

    NSDictionary* results = [parser dictionaryForPath:path
                                           pathPrefix:pathPrefix
                                             delegate:delegate];
    if (nil != results && ![parser didFailToParse]) {
      _rawRulesets = results;
      loadDidSucceed = YES;
    }

    if (loadDidSucceed) {
      [self ruleSetsDidChange];
    }
  }

  return loadDidSucceed;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)addStylesheet:(NIStylesheet *)stylesheet {
  NIDASSERT(nil != stylesheet);
  if (nil == stylesheet) {
    return;
  }

  @synchronized(self) {
    NSMutableDictionary* compositeRuleSets = [self.rawRulesets mutableCopy];

    BOOL ruleSetsDidChange = NO;

    for (NSString* selector in stylesheet.rawRulesets) {
      NSDictionary* incomingRuleSet   = [stylesheet.rawRulesets objectForKey:selector];
      NSDictionary* existingRuleSet = [self.rawRulesets objectForKey:selector];

      // Don't bother adding empty rulesets.
      if ([incomingRuleSet count] > 0) {
        ruleSetsDidChange = YES;

        if (nil == existingRuleSet) {
          // There is no rule set of this selector - simply add the new one.
          [compositeRuleSets setObject:incomingRuleSet forKey:selector];
          continue;
        }

        NSMutableDictionary* compositeRuleSet = [existingRuleSet mutableCopy];
        // Add the incoming rule set entries, overwriting any existing ones.
        [compositeRuleSet addEntriesFromDictionary:incomingRuleSet];

        [compositeRuleSets setObject:compositeRuleSet forKey:selector];
      }
    }

    _rawRulesets = [compositeRuleSets copy];

    if (ruleSetsDidChange) {
      [self ruleSetsDidChange];
    }
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Applying Styles to Views

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applyRuleSet:(NICSSRuleset *)ruleSet toView:(UIView *)view {
  if ([view respondsToSelector:@selector(applyStyleWithRuleSet:)]) {
    [(id<NIStyleable>)view applyStyleWithRuleSet:ruleSet];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applyStyleToView:(UIView *)view withClassName:(NSString *)className {
  NICSSRuleset *ruleset = [self rulesetForClassName:className];
  if (nil != ruleset) {
    [self applyRuleSet:ruleset toView:view];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (NICSSRuleset *)rulesetForClassName:(NSString *)className {
  NICSSRuleset* ruleSet = nil;

  NSArray* selectors = [_significantScopeToScopes objectForKey:className];
  if ([selectors count] > 0) {
    // Gather all of the rule sets for this view into a composite rule set.
    ruleSet = [_ruleSets objectForKey:className];

    if (nil == ruleSet) {
      ruleSet = [[NICSSRuleset alloc] init];

      // Composite the rule sets into one.
      for (NSString* selector in selectors) {
        [ruleSet addEntriesFromDictionary:[_rawRulesets objectForKey:selector]];
      }

      NIDASSERT(nil != _ruleSets);
      [_ruleSets setObject:ruleSet forKey:className];
    }
  }

  return ruleSet;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSSet *)dependencies {
  return [_rawRulesets objectForKey:kDependenciesSelectorKey];
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Öst. Z. Pilzk. 5: 190 (1996)

#### Original name
Conocybe leporina var. parvispora Hauskn.

### Remarks
null


text:
<?php

/**
 * Este archivo es parte de llstarscreamll\Crud, aquí se muestran todas las opciones
 * de configuración del paquete.
 *
 * @license MIT
 * @package llstarscreamll\Crud
 */

return $uimap = [
    // sección de título
    'module-title-selector' => 'h2',
    'module-title-small-selector' => 'h2 small',

    'index-table-selector' => '.table.table-hover',

    // notificaciones de alerta
    'alert-success-selector' => '.alert.alert-success',
    'alert-warning-selector' => '.alert.alert-warning',
    'alert-danger-selector' => '.alert.alert-danger',

    // botones, links
    'create-form-button-selector' => 'button.btn.btn-primary',
    'edit-link-access-selector' => 'a.btn.btn-warning',
];


text:
require 'uri'

module Spectrum
  module Config
    class Z3988RftValFmt
      attr_accessor :id, :namespace

      JOURNAL = "info:ofi/fmt:kev:mtx:journal"
      BOOK = "info:ofi/fmt:kev:mtx:book"
      JOURNAL_FORMATS = ['Journal', 'Serial']

      def initialize(args)
        self.id = args['id'] || 'rft_val_fmt' if args
        self.namespace = args['namespace'] || '' if args
      end

      def value(data)
        val = if id && data && data[:value]
          formats = [data[:value]].flatten
          if JOURNAL_FORMATS.any? { |fmt| formats.include?(fmt) }
            JOURNAL
          else
            BOOK
          end
        else
          BOOK
        end
        ["#{URI::encode_www_form_component(id)}=#{URI::encode_www_form_component(namespace.to_s + val.to_s)}"]
      end
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Tidsskr. 29: 19 (1908)

#### Original name
Phyllachora conspicua Ferd. & Winge, 1908

### Remarks
null


text:
"""
Module containing functions and classes to produce posterior predictive
distribution.
"""
from math import pi
# import warnings
import numpy as np

class Predictor(object):
    """
    Global class implementing predictors.

    Predictors using different distribution functions should be subclassed
    from this one.
    """

    def __init__(self, posterior, model, extramodelargs=()):
        """

        :param np.array posterior: posterior sample with dimensions (n, k),
        where n is the sample size and k is the dimension of space.

        :param callable model: function taking posterior sample as first
        argument and a time as second element and producing the model that will
        be used as location array for the likelihood function.

        :param list extramodelargs: additional arguments passed to model
        function.
        """

        self.posterior = np.atleast_2d(posterior)

        # Define model and its extra arguments
        self.model = model
        self.modelargs = extramodelargs

        # Initialise time for prediction.
        self._times = None
        self.newtimes = None

        # Initialise
        self.predictives = np.zeros((0, 0))
        self.x = np.zeros((0, 0))

    def reset(self):
        """Deletes previous predictions done with the Predictor."""
        self.times = None
        self.predictives = np.zeros((0, 0))
        self.x = np.zeros((0, 0))

    @property
    def times(self):
        return self._times

    @times.setter
    def times(self, timepred=None):
        """Set new times for prediction. Concatenates if already exist."""
        if timepred is None and self._times is None:
            raise TypeError('Prediction time(s) must be given.')

        elif self._times is None:
            self.newtimes = np.atleast_1d(timepred)
            self._times = self.newtimes

        elif timepred is None:
            self.newtimes = self.times

        else:
            self.newtimes = np.atleast_1d(timepred)
            self._times = np.concatenate((self.times, self.newtimes))

    @staticmethod
    def likefunc(v, loc, **kwargs):
        """
        Abstract method for likelihood functions
        """
        raise NotImplementedError('To be implemented on a sub-class basis.')

    @staticmethod
    def likedraw(loc, **kwargs):
        """
        Abstract method to draw samples from likelihood function.
        """
        raise NotImplementedError('To be implemented on a sub-class basis.')

    def make_prediction(self, timepred=None, npoints=500, **kwargs):
        """
        Estimate posterior predictive distribution for a single future datum.

        This method estimates the posterior predictive distribution for a
        future datum at time tpred, based on a posterior sample.

        The algorithm uses the fact that the posterior predictive can be written
        as the expectation value over the posterior distribution of the
        probability distribution for a new observation (likelihood).

        First, it computes the value of the model at time tpred for each
        posterior sample element. Then uses this array
        as the location parameter for the likelihood of the new datum at time t.

        :param iterable or float timepred: times on which posterior predictive
        distributions are computed. If None, it default to current times
        attribute, if not None.

        :param int npoints: number of points used to evaluate likelihood.

        :keyword bool verbose: if True will print number of steps performed and
        remaing.

        Remaining keywords parameters are passed to likefunc method.

        :return x, predictives: the x values where predictive distributions are
         evaluated and the distributions.
        """
        verbose = kwargs.pop('verbose', False)

        # Sets new prediction times. Note that this concatenates if previous
        # prediction times were defined.
        self.times = timepred

        # Prepare output arrays
        predictives = np.zeros((len(self.newtimes), npoints))
        x = np.zeros_like(predictives)

        # Compute location parameter at all newtimes at the same time.
        # Up to x10 faster than doing it for each time, but need to be sure
        # memory is not overflown.

        loc = np.zeros((len(self.newtimes), len(self.posterior)))
        # loc = self.model(self.posterior, self.newtimes, *self.modelargs)

        for i, t in enumerate(self.newtimes):
            if verbose:
                print('Step {} of {}'.format(i+1, len(self.newtimes)))
            loc[i], x[i], predictives[i] = self.single_prediction(t, npoints,
                                                                  **kwargs)

        # Update predictives and x attributes.
        if len(self.predictives) == 0:
            self.predictives = predictives
            self.x = x
        else:
            self.predictives = np.vstack((self.predictives, predictives))
            self.x = np.vstack((self.x, x))

        return x, predictives

    def single_prediction(self, time, npoints=500, **kwargs):
        """
        Basic prediction action. Used by higher level make_prediction method.
        :param float time: time at which prediction is done.
        :param int npoints: number of elements in array used to evaluate
        posterior predictive.
        :return: location array, auxiliary evaluation array,
        posterior predictive.
        """
        loc = self.model(self.posterior, time, *self.modelargs)

        # Create auxiliary array where to evaluate posterior predictive
        deltax = loc.max() - loc.min()
        # TODO check if this vector limits is always enough. Results change a lot
        v = np.linspace(loc.min() - deltax * 2,
                        loc.max() + deltax * 2, npoints)

        # If scale is an array, it should have the same length than
        # posterior.
        like = self.likefunc(v, loc, **kwargs)

        return loc, v, like.mean(axis=1)

    def samplepredictive(self, timesample, samplesize=None, **kwargs):
        """
        Produce samples from the posterior predictive distribution.

        """
        # Set new times for prediction. Note that this concatenates previous
        # prediction times.
        t = np.atleast_1d(timesample)

        # The predicted data value for each posterior sample is simply
        # y = m(theta) + N(0, sigma**2).
        if samplesize != self.posterior.shape[0]:
            post = self.posterior.copy()
            np.random.shuffle(post)
            psample = post[:samplesize]
        else:
            psample = self.posterior.copy()

        loc = self.model(psample, t, *self.modelargs)

        return self.likedraw(loc, **kwargs)

class GaussPredictor(Predictor):
    """
    Class implementing predictor with Gaussian likelihood.
    """

    def __init__(self, posterior, model, extramodelargs=(),
                 likescale=1):
        """
        :param np.array posterior: posterior sample with dimensions (n, k),
        where n is the sample size and k is the dimension of space.

        :param callable model: function taking posterior sample as first
        argument and a time as second element and producing the model that will
        be used as location array for the likelihood function.

        :param float likescale: scale of the likelihood function of the future
        datum.

        """

        super(GaussPredictor, self).__init__(posterior, model,
                                             extramodelargs=extramodelargs)
        self.scale = likescale  # TODO: where should like scale be defined?

    # TODO change this to class method to include self.likescale as default
    # scale.
    @staticmethod
    def likefunc(v, loc, scale=None):
        """
        Gaussian likelihood function.

        The Gaussian is located in the position loc and has with variance
        scale**2.

        :param float or np.array v: new datum value.

        :param float or np.array loc: location parameter of Gaussian function.

        :param float or np.array scale: scale parameter for Gaussian function.

        :return np.array: value of likelihood function for different values
        of the future datum value and for all location and scales values. The
        shape is (nv, nloc).
        """
        if scale is None:
            raise TypeError('Scale not set for likelihood function of '
                            'predictor.')

        v, loc, scale = np.atleast_1d(v, loc, scale)

        # Preparing to broadcast
        v = v[:, np.newaxis]

        return np.exp(-0.5 * (v - loc) ** 2 / scale ** 2) / \
            np.sqrt(2 * pi * scale ** 2)

    @staticmethod
    def likedraw(loc, scale=None):
        """
        Draw sample from normal distribution

        :param float or np.array loc: location parameter of Gaussian function.

        :param float or np.array scale: scale parameter for Gaussian function.
        """
        if scale is None:
            raise TypeError('Scale not set for likelihood function of '
                            'predictor.')

        return loc + np.random.randn(len(loc), 1) * scale

"""
:param class or instance likefun: a Class or an instance, containing the
method pdf that evaluates the likelihood at a given point x.

:param float or np.array scale: scale of the probability distribution for
new datum. If an array is passed, it must have same length than posterior
sample (n). This is used to allow for jitter terms and similar.
"""


text:
<!--
  ~ Copyright (C) 2013-2014  Irian Solutions  (http://www.irian.at)
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>at.irian.ankorsamples</groupId>
        <artifactId>animals-sample</artifactId>
        <version>0.5-SNAPSHOT</version>
    </parent>

    <artifactId>animals-spring-websocket-server</artifactId>
    <packaging>jar</packaging>
    <name>Animals Sample - WebSocket Spring Boot Server</name>

    <dependencies>

        <dependency>
            <groupId>at.irian.ankor</groupId>
            <artifactId>ankor-bundle-websocket-springboot-server</artifactId>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>at.irian.ankorsamples</groupId>
            <artifactId>animals-application</artifactId>
            <scope>compile</scope>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <!--
                Define additional resources folder for inherited static web resources from:
                  ankor-js          ... basic Ankor Javascript support
                  animals-js-client ... Animals Javascript client resources
                These resources are getting including by means of the maven-dependency-plugin (see below)
                -->
                <directory>${project.build.directory}/inherited-resources</directory>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <!-- copy Ankor Javascript Support resources -->
                                    <groupId>at.irian.ankor</groupId>
                                    <artifactId>ankor-js</artifactId>
                                    <!-- Ankor version is defined via BOM in parent pom.xml -->
                                    <type>war</type>
                                    <outputDirectory>${project.build.directory}/inherited-resources/static</outputDirectory>
                                    <excludes>WEB-INF/**,META-INF/**</excludes>
                                </artifactItem>
                                <artifactItem>
                                    <!-- copy Animals Javascript Client resources -->
                                    <groupId>at.irian.ankorsamples</groupId>
                                    <artifactId>animals-js-client</artifactId>
                                    <version>${project.version}</version>
                                    <type>war</type>
                                    <outputDirectory>${project.build.directory}/inherited-resources/static</outputDirectory>
                                    <excludes>WEB-INF/**,META-INF/**</excludes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>

</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
SimpleIndexSchema
</TITLE>

<META NAME="date" CONTENT="2009-05-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

ch.ethz.mxquery.opt.index

Class SimpleIndexSchema

java.lang.Object
  ch.ethz.mxquery.opt.index.IndexSchema
      ch.ethz.mxquery.opt.index.SimpleIndexSchema

All Implemented Interfaces:
Traversable

public class SimpleIndexSchema
extends IndexSchema

Constructor Summary

SimpleIndexSchema(int indexNb)

Method Summary

 java.lang.String
getColumnName(int position)

 int
getComparator(int position)

 int
getCompareType(int position)

 void
registerValue(int comparator,
              int compareType,
              java.lang.String columnName)

 int
size()

 KXmlSerializer
traverse(KXmlSerializer serializer)

Methods inherited from class ch.ethz.mxquery.opt.index.IndexSchema

getId, isGroupByIndex, isSimpleValueIndex, setGroupByIndex, setId, setSimpleValueIndex

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SimpleIndexSchema

public SimpleIndexSchema(int indexNb)

Method Detail

registerValue

public void registerValue(int comparator,
                          int compareType,
                          java.lang.String columnName)

size

public int size()

Specified by:
size in class IndexSchema

getColumnName

public java.lang.String getColumnName(int position)

Specified by:
getColumnName in class IndexSchema

getComparator

public int getComparator(int position)

Specified by:
getComparator in class IndexSchema

getCompareType

public int getCompareType(int position)

Specified by:
getCompareType in class IndexSchema

traverse

public KXmlSerializer traverse(KXmlSerializer serializer)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich


text:
namespace blink {

class ExceptionState;
class PushSubscriptionOptions;
class ScriptPromise;
class ScriptState;
class ServiceWorkerRegistration;
struct WebPushSubscriptionOptions;

class MODULES_EXPORT PushManager final : public GarbageCollected<PushManager>, public ScriptWrappable {
    DEFINE_WRAPPERTYPEINFO();
public:
    static PushManager* create(ServiceWorkerRegistration* registration)
    {
        return new PushManager(registration);
    }

    ScriptPromise subscribe(ScriptState*, const PushSubscriptionOptions&,
        ExceptionState&);
    ScriptPromise getSubscription(ScriptState*);
    ScriptPromise permissionState(ScriptState*, const PushSubscriptionOptions&,
        ExceptionState&);

    DECLARE_TRACE();

    static WebPushSubscriptionOptions toWebPushSubscriptionOptions(
        const PushSubscriptionOptions&, ExceptionState&);

private:
    explicit PushManager(ServiceWorkerRegistration*);

    Member<ServiceWorkerRegistration> m_registration;
};

} // namespace blink

#endif // PushManager_h


text:
package org.apache.beam.sdk.io.gcp.pubsub;

import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.apache.beam.sdk.coders.CoderFactories;
import org.apache.beam.sdk.coders.CoderFactory;
import org.apache.beam.sdk.coders.CoderRegistrar;

/** A {@link CoderRegistrar} for standard types used with {@link PubsubIO}. */
@AutoService(CoderRegistrar.class)
public class PubsubCoderRegistrar implements CoderRegistrar {
  @Override
  public Map<Class<?>, CoderFactory> getCoderFactoriesToUseForClasses() {
    return ImmutableMap.<Class<?>, CoderFactory>of(
        PubsubMessage.class, CoderFactories.forCoder(PubsubMessageWithAttributesCoder.of()));
  }
}


text:
package com.thinkbiganalytics.nifi.rest;

import com.thinkbiganalytics.nifi.feedmgr.TemplateCreationHelper;
import com.thinkbiganalytics.nifi.rest.client.LegacyNifiRestClient;
import com.thinkbiganalytics.nifi.rest.support.NifiConnectionUtil;

import org.apache.nifi.web.api.dto.ConnectionDTO;
import org.apache.nifi.web.api.dto.PortDTO;
import org.apache.nifi.web.api.dto.ProcessGroupDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import javax.inject.Inject;

/**
 * Cache used to help speed up creating the feed.
 *
 */
public class NiFiObjectCache {

    private static final Logger log = LoggerFactory.getLogger(NiFiObjectCache.class);

    @Inject
    private LegacyNifiRestClient restClient;

    @Value("${nifi.cache.connections:true}")
    private boolean cacheConnections;

    @Value("${nifi.cache.categoryGroups:true}")
    private boolean cacheCategoryGroups;

    private ProcessGroupDTO rootProcessGroup;

    private ProcessGroupDTO reusableTemplateCategory;

    private Map<String,ProcessGroupDTO> categoryProcessGroup = new ConcurrentHashMap<>();

    private ProcessGroupDTO temporaryTemplateInspectionGroup;
    private String reusableTemplateCategoryName = TemplateCreationHelper.REUSABLE_TEMPLATES_PROCESS_GROUP_NAME;

    private String temporaryInspectionGroupName = TemplateCreationHelper.TEMPORARY_TEMPLATE_INSPECTION_GROUP_NAME;

    private Map<String, PortDTO> reusableTemplateCategoryInputPortsByName = new ConcurrentHashMap<>();

    //Make a evictingQueue  to reduce size??
    private Map<String, Map<String, PortDTO>> categoryProcessGroupIdToOutputPortByName = new ConcurrentHashMap<>();

    //Make a evictingQueue  to reduce size??
    private Map<String, Set<ConnectionDTO>> processGroupConnections = new ConcurrentHashMap<>();

    private String reusableTemplateProcessGroupId;

    public NiFiObjectCache() {
    }

    /**
     * Returns the root process group (non recursive call)
     */
    public ProcessGroupDTO getRootProcessGroup() {
        if (rootProcessGroup == null) {
            rootProcessGroup = restClient.getNiFiRestClient().processGroups().findById("root", false, false).orElseThrow(IllegalStateException::new);
        }
        return rootProcessGroup;
    }

    /**
     * returns the 'reusable_templates' process group
     */
    public ProcessGroupDTO getReusableTemplateCategoryProcessGroup() {
        if (reusableTemplateCategory == null) {
            if(reusableTemplateProcessGroupId != null) {
                reusableTemplateCategory =  restClient.getNiFiRestClient().processGroups().findById(reusableTemplateProcessGroupId, false, false).orElse(null);
            }
            if(reusableTemplateCategory == null) {
                reusableTemplateCategory = restClient.getProcessGroupByName("root", reusableTemplateCategoryName);
                if(reusableTemplateCategory != null) {
                    reusableTemplateProcessGroupId = reusableTemplateCategory.getId();
                }
            }
        }

        if(reusableTemplateCategory == null){
            //create it
            reusableTemplateCategory = restClient.createProcessGroup("root", reusableTemplateCategoryName);
        }

        if(reusableTemplateCategory != null && reusableTemplateProcessGroupId == null) {
            reusableTemplateProcessGroupId = reusableTemplateCategory.getId();
        }
        return reusableTemplateCategory;
    }

    /**
     * returns the 'reusable_templates' process group
     */
    public ProcessGroupDTO getOrCreateTemporaryTemplateInspectionGroup() {
        if(temporaryTemplateInspectionGroup == null) {

            Optional<ProcessGroupDTO> group = restClient.getNiFiRestClient().processGroups().findByName("root", temporaryInspectionGroupName, false, false);
            if (!group.isPresent()) {
                temporaryTemplateInspectionGroup = restClient.getNiFiRestClient().processGroups().create("root", temporaryInspectionGroupName);
            } else {
                temporaryTemplateInspectionGroup = group.get();
            }
        }
        return temporaryTemplateInspectionGroup;
    }

    public void setRestClient(LegacyNifiRestClient restClient) {
        this.restClient = restClient;
    }

    /**
     * return the matching inputport in the 'reusable_templates' process group
     */
    public PortDTO getReusableTemplateInputPort(String inputPortName) {
        if (reusableTemplateCategoryInputPortsByName.containsKey(inputPortName)) {
            return reusableTemplateCategoryInputPortsByName.get(inputPortName);
        } else {
            ProcessGroupDTO reusableTemplateCategoryGroupId = getReusableTemplateCategoryProcessGroup();
            Set<PortDTO> inputPortsEntity = restClient.getNiFiRestClient().processGroups().getInputPorts(reusableTemplateCategoryGroupId.getId());
            if (inputPortsEntity != null) {
                inputPortsEntity.stream().forEach(inputPort -> reusableTemplateCategoryInputPortsByName.put(inputPort.getName(),inputPort)
                );
                PortDTO inputPort = NifiConnectionUtil.findPortMatchingName(inputPortsEntity, inputPortName);
                return inputPort;
            }
        }
        return null;

    }

    /**
     * finds the matching outputport for the category looking by the port name
     */
    public PortDTO getCategoryOutputPort(String categoryProcessGroupId, String outputPortName) {

        if (!categoryProcessGroupIdToOutputPortByName.containsKey(categoryProcessGroupId)) {
            categoryProcessGroupIdToOutputPortByName.put(categoryProcessGroupId, new ConcurrentHashMap<>());
        }

        PortDTO outputPort = categoryProcessGroupIdToOutputPortByName.get(categoryProcessGroupId).get(outputPortName);
        if (outputPort == null) {
            Set<PortDTO> outputPorts = restClient.getNiFiRestClient().processGroups().getOutputPorts(categoryProcessGroupId);
            if (outputPorts != null) {
                outputPorts.stream().forEach(port -> categoryProcessGroupIdToOutputPortByName.get(categoryProcessGroupId).put(port.getName(), port));
                outputPort =
                    NifiConnectionUtil.findPortMatchingName(outputPorts, outputPortName);
            }
        }
        return outputPort;
    }

    public void addCategoryOutputPort(String categoryProcessGroupId, PortDTO portDTO) {
        if(!categoryProcessGroupIdToOutputPortByName.containsKey(categoryProcessGroupId)) {
            categoryProcessGroupIdToOutputPortByName.put(categoryProcessGroupId, new ConcurrentHashMap<>());
        }
        categoryProcessGroupIdToOutputPortByName.get(categoryProcessGroupId).put(portDTO.getName(), portDTO);
    }

    public Set<ConnectionDTO> getConnections(String processGroupId){
        return processGroupConnections.get(processGroupId);
    }

    public void removeConnections(String processGroupId, Set<String> connectionIds){
        Set<ConnectionDTO> connections = getConnections(processGroupId);
        if(connections != null && connectionIds != null && !connectionIds.isEmpty()){
            connections.removeIf(c ->connectionIds.contains(c.getId()));
        }
    }

    /**
     * @param processGroupId    (i.e. category process group)
     * @param sourcePortId      (feed output port)
     * @param destinationPortId (category output port)
     */
    public ConnectionDTO getConnection(String processGroupId, String sourcePortId, String destinationPortId) {

        ConnectionDTO
            connection = null;

        Set<ConnectionDTO> connectionDTOS = processGroupConnections.get(processGroupId);

        if (connectionDTOS == null || !cacheConnections) {
            //find all connections in the category
            Set<ConnectionDTO> connectionsEntity = restClient.getNiFiRestClient().processGroups().getConnections(processGroupId);
            if (connectionsEntity != null) {
                if(cacheConnections) {
                    processGroupConnections.put(processGroupId, connectionsEntity);
                }
                connectionDTOS = connectionsEntity;
            }
        }

        if (connectionDTOS != null) {

            connection =
                NifiConnectionUtil.findConnection(connectionDTOS, sourcePortId,
                                                  destinationPortId);

        }
        return connection;
    }

    public void addConnection(String processGroupId, ConnectionDTO connectionDTO) {
        if(!processGroupConnections.containsKey(processGroupId)){
            processGroupConnections.put(processGroupId, new HashSet<>());
        }
            processGroupConnections.get(processGroupId).add(connectionDTO);

    }

    public void addProcessGroupConnections(Set<ConnectionDTO> connections) {
        connections.stream().forEach(c -> addConnection(c.getParentGroupId(), c));
    }

    public boolean isCacheConnections() {
        return cacheConnections;
    }

    public ProcessGroupDTO getCategoryProcessGroup(String name){
        if(!cacheCategoryGroups){
           return restClient.getProcessGroupByName("root", name);
        }else {
            if (categoryProcessGroup.containsKey(name)) {
                return categoryProcessGroup.get(name);
            } else {
                Set<ProcessGroupDTO> categoryGroups = restClient.getNiFiRestClient().processGroups().findAll("root");
                Map<String, ProcessGroupDTO> groups = categoryGroups.stream().collect(Collectors.toMap(c -> c.getName(), c -> c));
                categoryProcessGroup.putAll(groups);
                return categoryProcessGroup.get(name);
            }
        }
    }

    public void addCategoryProcessGroup(ProcessGroupDTO processGroupDTO){
        if(cacheCategoryGroups){
           categoryProcessGroup.put(processGroupDTO.getName(),processGroupDTO);
        }
    }

    public String getReusableTemplateProcessGroupId() {
        if(reusableTemplateProcessGroupId == null){
            getReusableTemplateCategoryProcessGroup();
        }
        return reusableTemplateProcessGroupId;
    }

    public void setReusableTemplateProcessGroupId(String reusableTemplateProcessGroupId) {
        this.reusableTemplateProcessGroupId = reusableTemplateProcessGroupId;
    }
}


text:
package org.eclipse.draw2d;

import org.eclipse.swt.graphics.Image;

import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Insets;
import org.eclipse.draw2d.geometry.Rectangle;

/**
 * A Figure that simply contains an Image. Use this Figure, instead of a Label,
 * when displaying Images without any accompanying text. This figure is not
 * intended to have a layout mananger or children.
 *

 * Note that it is the client's responsibility to dispose the given image. There
 * is no "free" resource management in draw2d.
 *
 * @author Pratik Shah
 */
public class ImageFigure extends AbstractImageFigure {

    private Image img;
    private Dimension size = new Dimension();
    private int alignment;

    /**
     * Constructor

     * The default alignment is PositionConstants.CENTER.
     */
    public ImageFigure() {
        this(null, PositionConstants.CENTER);
    }

    /**
     * Constructor

     * The default alignment is PositionConstants.CENTER.
     *
     * @param image
     *            The Image to be displayed
     */
    public ImageFigure(Image image) {
        this(image, PositionConstants.CENTER);
    }

    /**
     * Constructor
     *
     * @param image
     *            The Image to be displayed
     * @param alignment
     *            A PositionConstant indicating the alignment
     *
     * @see ImageFigure#setImage(Image)
     * @see ImageFigure#setAlignment(int)
     */
    public ImageFigure(Image image, int alignment) {
        setImage(image);
        setAlignment(alignment);
    }

    /**
     * @return The Image that this Figure displays
     */
    @Override
    public Image getImage() {
        return img;
    }

    /**
     * Calculates the necessary size to display the Image within the figure's
     * client area.
     *
     * @see org.eclipse.draw2d.Figure#getPreferredSize(int, int)
     */
    @Override
    public Dimension getPreferredSize(int wHint, int hHint) {
        if (getInsets() == NO_INSETS)
            return size;
        Insets i = getInsets();
        return size.getExpanded(i.getWidth(), i.getHeight());
    }

    /**
     * @see org.eclipse.draw2d.Figure#paintFigure(Graphics)
     */
    @Override
    protected void paintFigure(Graphics graphics) {
        super.paintFigure(graphics);

        if (getImage() == null)
            return;

        int x, y;
        Rectangle area = getBounds().getShrinked(getInsets());
        switch (alignment & PositionConstants.NORTH_SOUTH) {
        case PositionConstants.NORTH:
            y = area.y;
            break;
        case PositionConstants.SOUTH:
            y = area.y + area.height - size.height;
            break;
        default:
            y = (area.height - size.height) / 2 + area.y;
            break;
        }
        switch (alignment & PositionConstants.EAST_WEST) {
        case PositionConstants.EAST:
            x = area.x + area.width - size.width;
            break;
        case PositionConstants.WEST:
            x = area.x;
            break;
        default:
            x = (area.width - size.width) / 2 + area.x;
            break;
        }
        graphics.drawImage(getImage(), x, y);
    }

    /**
     * Sets the alignment of the Image within this Figure. The alignment comes
     * into play when the ImageFigure is larger than the Image. The alignment
     * could be any valid combination of the following:
     *
     *

     *
PositionConstants.NORTH

     *
PositionConstants.SOUTH

     *
PositionConstants.EAST

     *
PositionConstants.WEST

     *
PositionConstants.CENTER or PositionConstants.NONE

     *

     *
     * @param flag
     *            A constant indicating the alignment
     */
    public void setAlignment(int flag) {
        alignment = flag;
    }

    /**
     * Sets the Image that this ImageFigure displays.
     *

     * IMPORTANT: Note that it is the client's responsibility to dispose the
     * given image.
     *
     * @param image
     *            The Image to be displayed. It can be null.
     */
    public void setImage(Image image) {
        if (img == image)
            return;
        img = image;
        if (img != null)
            size = new Rectangle(image.getBounds()).getSize();
        else
            size = new Dimension();
        revalidate();
        notifyImageChanged();
        repaint();
    }

}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>Reveal.js 3 Slide Demo</title>
	<link rel="stylesheet" href="css/reveal.min.css">
	<link rel="stylesheet" href="css/theme/default.css" id="theme">

About My Product

My product discussed here

Show a live link

Slide 2 discussed here

See HTMLCheats.com

Slide 3

How does one revisit an arbitrary slide in code?

Visit internal slide 2


text:
:warning: The Spark On HBase project in Cloudera Labs got merged into the upstream HBase project in 2015 and a backport of that has shipped with CDH since CDH 5.7

https://blog.cloudera.com/blog/2015/08/apache-spark-comes-to-apache-hbase-with-hbase-spark-module/
---

# SparkOnHBase
## Overview
This is a simple reusable lib for working with HBase with Spark

## Functionality
Current functionality supports the following functions

* bulkPut
* bulkDelete
* bulkIncrement
* bulkGet
* bulkCheckAndPut
* bulkCheckAndDelete
* foreachPartition (with HConnection)
* mapPartition (with HConnection)
* hbaseRDD (HBaseInputFormat)
* Java APIs
* Java Examples
* Java Unit Tests

## Near Future
* More unit test
* More Examples
* Python APIs
* Python Examples
* Python Unit Test

## Far Future

* Partitioned Bulk Put/Mutation
* Sorted Partitioned Bulk Get
* Spark implementation of HBase bulkLoad
* Spark implementation of HBase copyTable

## Build
mvn clean package

## CDH setup
Testing was done on CDH 5.0.2

Just put hbase-protocol-*.jar in /opt/cloudera/parcels/CDH/lib/spark/assembly/lib/ and bunced

/opt/cloudera/parcels/CDH/lib/spark/assembly/lib

## Examples
SparkOnHBase comes with a number of examples.  Here is the CLI commands to try them out.  These work with a table named 't1' and columnfmaily 'c'

create 't1', 'c'

export HADOOP_CLASSPATH=/opt/cloudera/parcels/CDH/lib/hbase/lib/*:/opt/cloudera/parcels/CDH/lib/hbase/lib/hbase-protocol-0.98.6-cdh5.3.0.jar:/etc/hbase/conf

### Bulk Put Timestamp: works on kerberos and non-kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkPutExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkPutExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Bulk Put Timestamp: works on kerberos and non-kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkPutTimestampExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Bulk Get: works on kerberos and non-kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkGetExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Bulk Increment: works on kerberos and non-kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkIncrementExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Bulk Delete: works on kerberos and non-kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseBulkDeleteExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Scan that works on Kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseScanRDDExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

### Old Scan that doesn't work on Kerberos

spark-submit --jars /opt/cloudera/parcels/CDH/lib/zookeeper/zookeeper-3.4.5-cdh5.3.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/guava-12.0.1.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/protobuf-java-2.5.0.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop-compat.jar,/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar,/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar --class com.cloudera.spark.hbase.example.HBaseDistributedScanExample --master yarn --deploy-mode client --executor-memory 512M --num-executors 4 --driver-java-options -Dspark.executor.extraClassPath=/opt/cloudera/parcels/CDH/lib/hbase/lib/* SparkHBase.jar t1 c

sbt/sbt assembly 'test-only org.apache.spark.hbase*'


text:
module EOL
  module Solr
    module SolrSearchDataObjects
      def self.tasks_for_worklist(query, options = {})
        options[:fields] = 'data_object_id'
        result = EOL::Solr.query_lucene($SOLR_SERVER + $SOLR_DATA_OBJECTS_CORE, query, options);
        data_object_ids = []
        result['response']['docs'].each{|h| data_object_ids << h['data_object_id']}
        return data_object_ids
      end
    end
  end
end


text:
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var config		= require("../../config");

var Objectid = mongoose.Schema.Types.ObjectId;

var APIKeySchema   = new Schema({
	user_id: Objectid,
	apikey: String,
	created: { type: Date, default: Date.now, expires: config.apikey_lifespan },
});

APIKeySchema.set("_perms", {
	//We can never change or view this directly
});

module.exports = mongoose.model('APIKey', APIKeySchema);


text:
// WARNING: this assumes you have already included ilib-*.js into your html

var ilib = require("./ilib.js");

var top = ilib._top();

var exportClassesPublic = [
    "DateRngFmt",
    "IDate",
    "DateFactory",
    "HebrewDate",
    "HebrewCal",
    "IslamicCal",
    "IslamicDate",
    "JulianCal",
    "JulianDate",
    "GregorianCal",
    "GregorianDate",
    "ThaiSolarCal",
    "ThaiSolarDate",
    "PersianCal",
    "PersianDate",
    "PersianAlgoCal",
    "PersianAlgoDate",
    "HanCal",
    "HanDate",
    "EthiopicCal",
    "EthiopicDate",
    "CopticCal",
    "CopticDate",
    "INumber",
    "NumFmt",
    "JulianDay",
    "DateFmt",
    "Calendar",
    "CalendarFactory",
    "Utils",
    "Locale",
    "IString",
    "DurationFmt",
    "ResBundle",
    "CType",
    "LocaleInfo",
    "DateRngFmt",
    "isAlnum",
    "isAlpha",
    "isAscii",
    "isBlank",
    "isCntrl",
    "isDigit",
    "isGraph",
    "isIdeo",
    "isLower",
    "isPrint",
    "isPunct",
    "isSpace",
    "isUpper",
    "isXdigit",
    "isScript",
    "ScriptInfo",
    "Name",
    "NameFmt",
    "Address",
    "AddressFmt",
    "Collator",
    "LocaleMatcher",
    "NormString",
    "CaseMapper",
    "GlyphString",
    "PhoneFmt",
    "PhoneGeoLocator",
    "PhoneNumber",
    "Measurement",
    "MeasurementFactory",
    "UnitFmt",
    "LengthUnit",
    "VelocityUnit",
    "DigitalStorageUnit",
    "TemperatureUnit",
    "UnknownUnit",
    "TimeUnit",
    "MassUnit",
    "AreaUnit",
    "FuelConsumptionUnit",
    "VolumeUnit",
    "EnergyUnit",
    "ForceUnit",
    "PowerUnit",
    "PressureUnit",
    "Charset",
    "Charmap",
    "CharmapFactory",
    "CharmapTable",
    "UTF8",
    "UTF16BE",
    "UTF16LE",
    "Country",
    "ListFmt",
    "AlphabeticIndex",
    "TimeZone",
    "Currency",
    "DigitalSpeedUnit"
];

if (top) {
    // these are the private classes that the unit tests may need
    var exportClasses = exportClassesPublic.concat([
        "ISet",
        "SearchUtils",
        "MathUtils",
        "JSUtils",
        "Path",
        "Astro",
        "Utils",
        "CodePointSource",
        "CopticRataDie",
        "ElementIterator",
        "EthiopicRataDie",
        "GregRataDie",
        "HanRataDie",
        "NumberingPlan",
        "PersAlgoRataDie",
        "PersRataDie",
        "PhoneHandlerFactory",
        "PhoneLocale",
        "RataDie"
    ]);

    exportClasses.forEach(function(className) {
        // console.log("Defining " + className);
        if (typeof(ilib[className]) !== 'undefined') {
            top[className] = ilib[className];
        }
    });
} else {
    throw "No global scope on this platform. You cannot use ilib-unpack here to unpack ilib into the global scope because it does not exist.";
}

module.exports = exportClassesPublic;


text:
.class public Lcom/android/internal/telephony/IccCardConstants;
.super Ljava/lang/Object;
.source "IccCardConstants.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/internal/telephony/IccCardConstants$State;
    }
.end annotation

# static fields
.field public static final INTENT_KEY_ICC_STATE:Ljava/lang/String; = "ss"

.field public static final INTENT_KEY_LOCKED_REASON:Ljava/lang/String; = "reason"

.field public static final INTENT_VALUE_ABSENT_ON_PERM_DISABLED:Ljava/lang/String; = "PERM_DISABLED"

.field public static final INTENT_VALUE_ICC_ABSENT:Ljava/lang/String; = "ABSENT"

.field public static final INTENT_VALUE_ICC_IMSI:Ljava/lang/String; = "IMSI"

.field public static final INTENT_VALUE_ICC_LOADED:Ljava/lang/String; = "LOADED"

.field public static final INTENT_VALUE_ICC_LOCKED:Ljava/lang/String; = "LOCKED"

.field public static final INTENT_VALUE_ICC_NOT_READY:Ljava/lang/String; = "NOT_READY"

.field public static final INTENT_VALUE_ICC_READY:Ljava/lang/String; = "READY"

.field public static final INTENT_VALUE_ICC_UNKNOWN:Ljava/lang/String; = "UNKNOWN"

.field public static final INTENT_VALUE_LOCKED_CORPORATE:Ljava/lang/String; = "CORPORATE"

.field public static final INTENT_VALUE_LOCKED_NETWORK:Ljava/lang/String; = "NETWORK"

.field public static final INTENT_VALUE_LOCKED_NETWORK_SUBSET:Ljava/lang/String; = "NETWORK_SUBSET"

.field public static final INTENT_VALUE_LOCKED_ON_PIN:Ljava/lang/String; = "PIN"

.field public static final INTENT_VALUE_LOCKED_ON_PUK:Ljava/lang/String; = "PUK"

.field public static final INTENT_VALUE_LOCKED_SERVICE_PROVIDER:Ljava/lang/String; = "SERVICE_PROVIDER"

.field public static final INTENT_VALUE_LOCKED_SIM:Ljava/lang/String; = "SIM"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 21
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 68
    return-void
.end method