text:
function Util() {
}

Util.formatDate = function (col) {
    var value = this.getDataValue(col);
    if (value) {
        var date = new Date(value);
        var month = date.getMonth();
        var day = date.getDate();
        var year = date.getFullYear();
        return day + '/' + month + '/' + year;
    } else {
        return null;
    }
};

Util.getTimestamp = function (model, col) {
    var value = model.getDataValue(col);
    if (value) {
        var date = new Date(value);
        return date.getTime();
    } else {
        return null;
    }
};

Util.setDateOnly = function (value, model, col) {
    //var value = model.getDataValue(col);
    if (value) {
        var pattern = /(\d{2})\/(\d{2})\/(\d{4})/;
        var dt = new Date(value.replace(pattern,'$3-$2-$1'));
        return model.setDataValue(col, dt);
    } else {
        return null;
    }
};

Util.groupLatestBySubcategory = function (array) {
    console.log('debug', "groupLatestBySubcategory: " + array)
    if (array && array.length > 1) {
        var group = [];
        group.push(array[0]);

        for (i = 1; i < array.length; i++) {
            var hasSubcategory = false;
            for (j = 0; j < group.length; j++) {
                if (group[j].subcategory_id === array[i].subcategory_id) {
                    hasSubcategory = true;
                    if (group[j].created_at < array[i].created_at) {
                        group[j] = array[i];
                    }
                }
            }
            if (!hasSubcategory) {
                group.push(array[i]);
            }
        }
        return group;
    } else {
        return array;
    }
};

Util.cleanJson = function (obj){
    var isArray = obj instanceof Array;
    for (var k in obj){
        if (obj[k]===null || (obj[k] instanceof Array && obj[k].length == 0)) {
            isArray ? obj.splice(k,1) : delete obj[k];
        }
        else if (typeof obj[k]=="object") {
            this.cleanJson(obj[k]);
        }
    }
};

module.exports = Util;


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>高阶函数</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Wu, Shanliang" />

<link rel="stylesheet" type="text/css" href="../css/main.css" />

  UP
 |
  HOME

高阶函数

Erlang 作为函数式编程语言自然拥有 高阶函数 。在 shell 中,可以这样使用:

12> Xf=fun(X) -> X * 2 end.
#Fun<erl_eval.6.128620087>

13> Xf(5).
10

这里定义了一个数值翻倍的函数,并将这个函数赋给了一个变量

所以,Xf(5) 返回值为 10

Erlang 有两个非常有用的操作列表的函数 foreach 与 map , 定义如下:

foreach(Fun, [First|Rest]) ->
    Fun(First),
    foreach(Fun, Rest);
foreach(Fun, []) ->
    ok.

map(Fun, [First|Rest]) ->
    [Fun(First)|map(Fun,Rest)];
map(Fun, []) ->
    [].

这两个函数是由标准模块 lists 提供的:

foreach: 将一个函数作用于列表中的每一个元素

map: 通过将一个函数作用于列表中的每个元素生成一个新的列表

使用 map 的 Add_3 函数生成一个新的列表:

14> Add_3 = fun(X) -> X + 3 end.
#Fun<erl_eval.6.128620087>

15> lists:map(Add_3, [1,2,3]).
[4,5,6]

再次输出一组城市的温度值:

16> Print_City = fun({City, {X, Temp}}) -> io:format("~-15w ~w ~w~n",
16> [City, X, Temp]) end.
#Fun<erl_eval.6.128620087>

17> lists:foreach(Print_City, [{moscow, {c, -10}}, {cape_town, {f, 70}},
17> {stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).
moscow          c -10
cape_town       f 70
stockholm       c -4
paris           f 28
london          f 36
ok

重新定义一个函数,这个函数用于遍历城市温度列表并将每个温度值都转换为摄氏温度表示。如下所示:

-module(high_order).

-export([convert_list_to_c/1]).

convert_to_c({Name, {f, Temp}}) ->
    {Name, {c, trunc((Temp - 32) * 5 / 9)}};
convert_to_c({Name, {c, Temp}}) ->
    {Name, {c, Temp}}.

convert_list_to_c(List) ->
    lists:map(fun convert_to_c/1, List).

convert_to_c 函数和之前的一样,但是它现在被用作高阶函数:

convert_list_to_c(List) ->
    lists:map(fun convert_to_c/1, List).

当一个在别处定义的函数被用作高阶函数时,可以通过 Function/Arity 的方式来引用它:

Function 为函数名

Arity 为函数的参数个数

所以在调用 map 函数时,才会是 lists:map(fun convert_to_c/1, List) 这样的形式

如上所示,convert_list_to_c 变得更加的简洁易懂

测试如下:

2> high_order:convert_list_to_c([{moscow, {c, -10}}, {cape_town, {f, 70}},
2> {stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).
[{moscow,{c,-10}},
 {cape_town,{c,21}},
 {stockholm,{c,-4}},
 {paris,{c,-2}},
 {london,{c,2}}]

lists 标准库中还包括排序函数 sort(Fun,List) ,其中:

Fun 接受两个输入参数,如果第一个元素比第二个元素小则函数返回真,否则返回假

把排序添加到 convert_list_to_c 中:

convert_list_to_c(List) ->
    New_list = lists:map(fun convert_to_c/1, List),
    lists:sort(fun({_, {c, Temp1}}, {_, {c, Temp2}}) ->
                       Temp1 < Temp2 end, New_list).

在 sort 中用到了下面这个函数:

fun({_, {c, Temp1}}, {_, {c, Temp2}}) -> Temp1 < Temp2 end,

这儿用到了 匿名变量 "_" 的概念。匿名变量常用于忽略一个获得的变量值的场景下

当然,它也可以用到其它的场景中,而不仅仅是在高阶函数这儿

Temp1 < Temp2 说明如果 Temp1 比 Temp2 小,则返回 true

最后测试下:

4> high_order:convert_list_to_c([{moscow, {c, -10}}, {cape_town, {f, 70}},
4> {stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).
[{moscow,{c,-10}},
 {stockholm,{c,-4}},
 {paris,{c,-2}},
 {london,{c,2}},
 {cape_town,{c,21}}]

Next:并发编程

Previous:内置函数

Home:顺序编程

redpajama_set_name: RedPajamaGithub


text:
package com.haulmont.cuba.web.gui.components;

import com.google.common.collect.ImmutableList;
import com.haulmont.bali.events.Subscription;
import com.haulmont.bali.util.Preconditions;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.app.security.role.edit.UiPermissionDescriptor;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.data.ValueSourceProvider;
import com.haulmont.cuba.gui.components.form.ComponentArea;
import com.haulmont.cuba.gui.components.form.ComponentPosition;
import com.haulmont.cuba.gui.components.security.ActionsPermissions;
import com.haulmont.cuba.gui.sys.TestIdManager;
import com.haulmont.cuba.security.entity.ScreenComponentPermission;
import com.haulmont.cuba.web.AppUI;
import com.haulmont.cuba.web.widgets.CubaFieldGroupLayout;
import com.vaadin.ui.GridLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static com.google.common.base.Preconditions.checkArgument;
import static com.haulmont.bali.util.Preconditions.checkNotNullArgument;

public class WebForm extends WebAbstractComponent<CubaFieldGroupLayout> implements Form, UiPermissionAware {

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

    protected List<List<ComponentPosition>> columnComponentMapping = new ArrayList<>();

    protected ValueSourceProvider valueSourceProvider;

    public WebForm() {
        // add first column
        columnComponentMapping.add(new ArrayList<>());

        component = createComponent();
    }

    protected CubaFieldGroupLayout createComponent() {
        return new CubaFieldGroupLayout();
    }

    protected boolean editable = true;

    @Override
    public void setDebugId(String id) {
        super.setDebugId(id);

        AppUI ui = AppUI.getCurrent();
        if (ui != null && id != null) {
            for (final Component component : getOwnComponents()) {
                com.vaadin.ui.Component composition = WebComponentsHelper.getComposition(component);
                if (composition != null) {
                    composition.setId(ui.getTestIdManager().getTestId(id + "_" + component.getId()));
                }
            }
        }
    }

    @Override
    public boolean isEditable() {
        return this.editable;
    }

    @Override
    public void setEditable(boolean editable) {
        if (editable != isEditable()) {
            this.editable = editable;

            EditableChangeEvent event = new EditableChangeEvent(this);
            publish(EditableChangeEvent.class, event);
        }
    }

    @Override
    public Subscription addEditableChangeListener(Consumer<EditableChangeEvent> listener) {
        return getEventHub().subscribe(EditableChangeEvent.class, listener);
    }

    @Override
    public void removeEditableChangeListener(Consumer<EditableChangeEvent> listener) {
        unsubscribe(EditableChangeEvent.class, listener);
    }

    @Override
    public void add(Component childComponent) {
        add(childComponent, 0);
    }

    @Override
    public void add(Component childComponent, int column) {
        int rowIndex = detectStartRowIndex(column);
        add(childComponent, column, rowIndex);
    }

    @Override
    public void add(Component childComponent, int column, int colSpan, int rowSpan) {
        int rowIndex = detectStartRowIndex(column);
        add(childComponent, column, rowIndex, colSpan, rowSpan);
    }

    @Override
    public void add(Component childComponent, int column, int row) {
        add(childComponent, column, row, 1, 1);
    }

    @Override
    public void add(Component childComponent, int column, int row, int colSpan, int rowSpan) {
        checkArgument(column >= 0 && column < this.component.getColumns(),
                "Illegal column number %s, must be between [0; %s]", column, this.component.getColumns());

        checkArgument((column + colSpan) <= this.component.getColumns(),
                "Illegal colSpan number %s, available amount of columns is %s, column number is %s",
                colSpan, this.component.getColumns(), column);

        int rowsCount = detectRowsCount(column);
        checkArgument(row >= 0 && row <= rowsCount,
                "Illegal row number %s, available amount of rows in column %s is %s", row, column, rowsCount);

        checkExistingOverlaps(column, row, colSpan, rowSpan);

        addComponentInternal(childComponent, column, row, colSpan, rowSpan);
    }

    protected void checkExistingOverlaps(int startColumn, int startRow, int colSpan, int rowSpan) {
        int endColumn = startColumn + colSpan - 1;
        int endRow = startRow + rowSpan - 1;
        List<ComponentArea> componentAreas = calculateComponentAreas();
        for (ComponentArea area : componentAreas) {
            // Check that a component isn't inserted to the existing component area excluding top left point.
            if (area.getStartColumn() < startColumn && startColumn <= area.getEndColumn()
                    && area.getStartRow() <= startRow && startRow <= area.getEndRow()
                    || area.getStartRow() < startRow && startRow <= area.getEndRow()
                    && area.getStartColumn() <= startColumn && startColumn <= area.getEndColumn()) {
                throw new IllegalArgumentException(String.format(
                        "Given coordinates [%s, %s] - [%s, %s] overlap existing component: [%s, %s] - [%s, %s]",
                        startColumn, startRow, endColumn, endRow,
                        area.getStartColumn(), area.getStartRow(), area.getEndColumn(), area.getEndRow()));
            }
        }
    }

    protected void addComponentInternal(Component childComponent,
                                        int column, int row, int colSpan, int rowSpan) {
        List<ComponentPosition> componentPositions = columnComponentMapping.get(column);
        int insertIndex = calculateInsertIndex(column, row, componentPositions);

        componentPositions.add(insertIndex, new ComponentPosition(childComponent, colSpan, rowSpan));

        managedComponentAssigned(childComponent);
    }

    protected int calculateInsertIndex(int column, int row, List<ComponentPosition> componentPositions) {
        // Convert grid row index to column components array index:
        // Remove all components row spans of this column
        int insertIndex = row;
        for (int i = 0; i < componentPositions.size() && i < row; i++) {
            ComponentPosition position = componentPositions.get(i);
            if (position.getRowSpan() > 1) {
                insertIndex -= (position.getRowSpan() - 1);
            }
        }

        // Remove all components row spans from previous columns, only if a components overlaps this column
        for (int colIndex = 0; colIndex < column; colIndex++) {
            List<ComponentPosition> positions = columnComponentMapping.get(colIndex);
            for (int rowIndex = 0; rowIndex < row && rowIndex < positions.size(); rowIndex++) {
                ComponentPosition position = positions.get(rowIndex);
                if (colIndex + position.getColSpan() > column) {
                    insertIndex -= position.getRowSpan();
                }
            }
        }
        return Math.min(insertIndex, componentPositions.size());
    }

    protected void managedComponentAssigned(Component childComponent) {
        com.vaadin.ui.Component vComponent = WebComponentsHelper.getComposition(childComponent);
        assignTypicalAttributes(childComponent);
        assignDebugId(vComponent, childComponent.getId());
        applyDefaults(childComponent);

        this.component.setRows(detectRowsCount());

        reattachColumnFields();
    }

    protected void applyDefaults(Component childComponent) {
        if (childComponent instanceof HasCaption
                && ((HasCaption) childComponent).getCaption() == null) {
            ((HasCaption) childComponent).setCaption(" "); // Set an empty caption for proper positioning
        }
    }

    protected void assignTypicalAttributes(Component component) {
        if (getFrame() != null && component instanceof BelongToFrame) {
            BelongToFrame belongToFrame = (BelongToFrame) component;
            if (belongToFrame.getFrame() == null) {
                belongToFrame.setFrame(getFrame());
            }
        }

        component.setParent(this);
    }

    protected void assignDebugId(com.vaadin.ui.Component composition, String id) {
        AppUI ui = AppUI.getCurrent();
        if (ui == null) {
            return;
        }

        String debugId = getDebugId();
        if (ui.isPerformanceTestMode()) {
            if (composition != null && debugId != null) {
                TestIdManager testIdManager = ui.getTestIdManager();
                composition.setId(testIdManager.getTestId(debugId + "_" + id));
            }
        }
    }

    /**
     * @param column a column index
     * @return rows count for the given column index
     */
    protected int detectRowsCount(int column) {
        return detectRowsCount(column, false);
    }

    /**
     * @param column a column index
     * @return start row index for the given column index
     */
    protected int detectStartRowIndex(int column) {
        return detectRowsCount(column, column > 0);
    }

    protected int detectRowsCount(int column, boolean isCheckAreas) {
        List<ComponentPosition> componentPositions = columnComponentMapping.get(column);

        // Calculate rows count considering row spans
        int rowsCount = componentPositions.stream()
                .map(ComponentPosition::getRowSpan)
                .reduce(Integer::sum)
                .orElse(0);

        List<ComponentArea> componentAreas = isCheckAreas
                ? calculateComponentAreas()
                : Collections.emptyList();

        // If a component from a previous column overlaps current column,
        // then increase rows count by its row span value
        for (int i = 0; i < column; i++) {
            List<ComponentPosition> positions = columnComponentMapping.get(i);
            for (ComponentPosition position : positions) {
                if (i + position.getColSpan() > column) {
                    // Even though a component from a previous column overlaps current column
                    // it still can be above a current component
                    ComponentArea area = findComponentArea(componentAreas, position);
                    if (area == null || rowsCount >= area.getStartRow()) {
                        rowsCount += position.getRowSpan();
                    }
                }
            }
        }

        return rowsCount;
    }

    @Nullable
    protected ComponentArea findComponentArea(List<ComponentArea> componentAreas, ComponentPosition position) {
        for (ComponentArea componentArea : componentAreas) {
            if (componentArea.getComponent().equals(position.getComponent())) {
                return componentArea;
            }
        }

        return null;
    }

    /**
     * @return max rows count among all columns
     */
    protected int detectRowsCount() {
        int lastRowIndex = IntStream.range(0, columnComponentMapping.size())
                .map(this::detectRowsCount)
                .max().orElse(0);

        return Math.max(lastRowIndex, 1);
    }

    protected void reattachColumnFields() {
        List<ComponentArea> componentAreas = calculateComponentAreas();

        this.component.removeAllComponents();

        for (ComponentArea componentArea : componentAreas) {
            com.vaadin.ui.Component composition = WebComponentsHelper.getComposition(componentArea.getComponent());
            this.component.addComponent(composition,
                    componentArea.getStartColumn(), componentArea.getStartRow(),
                    componentArea.getEndColumn(), componentArea.getEndRow());
        }
    }

    protected List<ComponentArea> calculateComponentAreas() {
        List<ComponentArea> componentAreas = new ArrayList<>();
        // Inspired by GridLayoutLoader logic
        boolean[][] spanMatrix = new boolean[this.component.getColumns()][this.component.getRows()];

        for (int col = 0; col < columnComponentMapping.size(); col++) {
            int row = 0;
            List<ComponentPosition> columnFields = columnComponentMapping.get(col);
            for (ComponentPosition componentPosition : columnFields) {

                while (spanMatrix[col][row]) {
                    row++;
                }

                Component component = componentPosition.getComponent();
                int colSpan = componentPosition.getColSpan();
                int rowSpan = componentPosition.getRowSpan();

                if (colSpan == 1 && rowSpan == 1) {
                    componentAreas.add(new ComponentArea(component, col, row, col, row));
                } else {
                    fillSpanMatrix(spanMatrix, col, row, colSpan, rowSpan);

                    int endColumn = col + colSpan - 1;
                    int endRow = row + rowSpan - 1;

                    componentAreas.add(new ComponentArea(component, col, row, endColumn, endRow));
                }

                row++;
            }

        }

        return componentAreas;
    }

    protected void fillSpanMatrix(boolean[][] spanMatrix, int col, int row, int colspan, int rowspan) {
        for (int i = col; i < (col + colspan); i++) {
            for (int j = row; j < (row + rowspan); j++) {
                if (spanMatrix[i][j]) {
                    throw new IllegalStateException(String.format("Can't insert a component to the given location: " +
                                    "col - %s, row - %s, colspan - %s, rowspan - %s, " +
                                    "because it overlaps another component",
                            col, row, colspan, rowspan));
                }

                spanMatrix[i][j] = true;
            }
        }
    }

    @Override
    public void remove(Component childComponent) {
        for (List<ComponentPosition> components : columnComponentMapping) {
            ComponentPosition toRemove = findComponentPosition(components, childComponent);
            if (toRemove != null) {
                components.remove(toRemove);
                reattachColumnFields();
                component.setRows(detectRowsCount());
                childComponent.setParent(null);
                break;
            }
        }
    }

    @Nullable
    protected ComponentPosition findComponentPosition(List<ComponentPosition> components, Component component) {
        for (ComponentPosition componentPosition : components) {
            if (componentPosition.getComponent().equals(component)) {
                return componentPosition;
            }
        }
        return null;
    }

    @Override
    public void removeAll() {
        component.removeAllComponents();

        List<Component> components = new ArrayList<>(getOwnComponents());

        columnComponentMapping.clear();
        columnComponentMapping.add(new ArrayList<>());
        component.setColumns(1);

        for (Component component : components) {
            component.setParent(null);
        }
    }

    @Nullable
    @Override
    public Component getOwnComponent(String id) {
        Preconditions.checkNotNullArgument(id);

        return getOwnComponents().stream()
                .filter(component -> Objects.equals(id, component.getId()))
                .findFirst()
                .orElse(null);
    }

    @Nullable
    @Override
    public Component getComponent(String id) {
        return ComponentsHelper.getComponent(this, id);
    }

    @Override
    public Collection<Component> getOwnComponents() {
        return columnComponentMapping.stream()
                .flatMap(List::stream)
                .map(ComponentPosition::getComponent)
                .collect(Collectors.toList());
    }

    @Override
    public Stream<Component> getOwnComponentsStream() {
        return columnComponentMapping.stream()
                .flatMap(List::stream)
                .map(ComponentPosition::getComponent);
    }

    @Override
    public Collection<Component> getComponents() {
        return ComponentsHelper.getComponents(this);
    }

    @Override
    public Collection<Component> getComponents(int column) {
        return columnComponentMapping.get(column).stream()
                .map(ComponentPosition::getComponent)
                .collect(ImmutableList.toImmutableList());
    }

    @Override
    public Component getComponent(int column, int row) {
        checkArgument(column >= 0 && column < component.getColumns()
                        && row >= 0 && row < component.getRows(),
                "Illegal coordinates for the component: [%s, %s]. Must be between [0, 0] - [%s, %s]",
                column, row, component.getColumns() - 1, component.getRows() - 1);

        List<ComponentArea> componentAreas = calculateComponentAreas();
        for (ComponentArea area : componentAreas) {
            if (area.getStartColumn() <= column && column <= area.getEndColumn()
                    && area.getStartRow() <= row && row <= area.getEndRow()) {
                return area.getComponent();
            }
        }

        throw new IllegalStateException(
                String.format("Can't find a component for the given coordinates: [%s, %s]", column, row));
    }

    @Override
    public CaptionPosition getCaptionPosition() {
        return component.isUseInlineCaption()
                ? CaptionPosition.LEFT
                : CaptionPosition.TOP;
    }

    @Override
    public void setCaptionPosition(CaptionPosition captionAlignment) {
        component.setUseInlineCaption(CaptionPosition.LEFT.equals(captionAlignment));
    }

    @Override
    public int getChildrenCaptionWidth() {
        return component.getFixedCaptionWidth();
    }

    @Override
    public void setChildrenCaptionWidth(int width) {
        component.setFixedCaptionWidth(width);
    }

    @Override
    public int getChildrenCaptionWidth(int column) {
        return component.getFieldCaptionWidth(column);
    }

    @Override
    public void setChildrenCaptionWidth(int column, int width) {
        component.setFieldCaptionWidth(column, width);
    }

    @Override
    public CaptionAlignment getChildrenCaptionAlignment() {
        return WebWrapperUtils.fromVaadinFieldGroupCaptionAlignment(
                component.getColumnCaptionAlignment());
    }

    @Override
    public void setChildrenCaptionAlignment(CaptionAlignment alignment) {
        component.setColumnCaptionAlignment(
                WebWrapperUtils.toVaadinFieldGroupCaptionAlignment(alignment));
    }

    @Override
    public CaptionAlignment getChildrenCaptionAlignment(int column) {
        return WebWrapperUtils.fromVaadinFieldGroupCaptionAlignment(
                component.getColumnCaptionAlignment(column));
    }

    @Override
    public void setChildrenCaptionAlignment(int column, CaptionAlignment alignment) {
        component.setColumnCaptionAlignment(column,
                WebWrapperUtils.toVaadinFieldGroupCaptionAlignment(alignment));
    }

    @Override
    public int getColumns() {
        return component.getColumns();
    }

    @Override
    public void setColumns(int columns) {
        if (component.getColumns() != columns) {
            try {
                component.setColumns(columns);
            } catch (GridLayout.OutOfBoundsException e) {
                // Replace the default exception with something more meaningful
                throw new IllegalStateException("Can't shrink columns with components within them");
            }

            List<List<ComponentPosition>> oldColumnComponents = columnComponentMapping;
            columnComponentMapping = new ArrayList<>();
            for (int i = 0; i < columns; i++) {
                if (i < oldColumnComponents.size()) {
                    columnComponentMapping.add(oldColumnComponents.get(i));
                } else {
                    columnComponentMapping.add(new ArrayList<>());
                }
            }
        }
    }

    @Override
    public ValueSourceProvider getValueSourceProvider() {
        return valueSourceProvider;
    }

    @Override
    public void setValueSourceProvider(ValueSourceProvider provider) {
        if (this.valueSourceProvider != null) {
            throw new UnsupportedOperationException("Changing value source provider is not supported " +
                    "by the Form component");
        }

        this.valueSourceProvider = provider;
    }

    @Override
    public void applyPermission(UiPermissionDescriptor permissionDescriptor) {
        checkNotNullArgument(permissionDescriptor);

        String subComponentId = permissionDescriptor.getSubComponentId();
        ScreenComponentPermission permissionValue = permissionDescriptor.getPermissionValue();
        String screenId = permissionDescriptor.getScreenId();

        if (subComponentId != null) {
            Component component = getComponent(subComponentId);
            if (component != null) {
                if (permissionValue == ScreenComponentPermission.DENY) {
                    component.setVisible(false);
                } else if (permissionValue == ScreenComponentPermission.VIEW
                        && this.component instanceof Editable) {
                    ((Editable) component).setEditable(false);
                }
            } else {
                log.info("Couldn't find suitable component {} in window {} for UI security rule",
                        subComponentId, screenId);
            }
        } else {
            String actionHolderComponentId = permissionDescriptor.getActionHolderComponentId();
            Component component = getComponent(actionHolderComponentId);
            if (!(component instanceof SecuredActionsHolder)) {
                log.info("Couldn't find suitable component {} in window {} for UI security rule",
                        actionHolderComponentId, screenId);
                return;
            }

            String actionId = permissionDescriptor.getActionId();
            ActionsPermissions permissions = ((SecuredActionsHolder) component).getActionsPermissions();
            if (permissionValue == ScreenComponentPermission.DENY) {
                permissions.addHiddenActionPermission(actionId);
            } else if (permissionValue == ScreenComponentPermission.VIEW) {
                permissions.addDisabledActionPermission(actionId);
            }
        }
    }

    @Override
    public void attached() {
        super.attached();

        getOwnComponentsStream().forEach(component ->
                ((AttachNotifier) component).attached());
    }

    @Override
    public void detached() {
        super.detached();

        getOwnComponentsStream().forEach(component ->
                ((AttachNotifier) component).detached());
    }

    @Override
    public void setColumnFlex(int column, float flex) {
        component.setColumnExpandRatio(column, flex);
    }

    @Override
    public float getColumnFlex(int column) {
        return component.getColumnExpandRatio(column);
    }
}


text:
package com.navercorp.pinpoint.rpc.packet;

import com.navercorp.pinpoint.rpc.util.ClassUtils;

import java.util.List;
import java.util.Map;

/**
 * @author Taejin Koo
 */
public enum HandshakePropertyType {

    SUPPORT_SERVER("supportServer", Boolean.class, false),
    SUPPORT_COMMAND_LIST("supportCommandList", List.class, false),

    HOSTNAME("hostName", String.class),
    IP("ip", String.class),
    AGENT_ID("agentId", String.class),
    APPLICATION_NAME("applicationName", String.class),
    SERVICE_TYPE("serviceType", Integer.class),
    PID("pid", Integer.class),
    VERSION("version", String.class),
    START_TIMESTAMP("startTimestamp", Long.class);

    private final String name;
    private final Class clazzType;
    private final boolean isRequired;

    HandshakePropertyType(String name, Class clazzType) {
        this(name, clazzType, true);
    }

    HandshakePropertyType(String name, Class clazzType, boolean isRequired) {
        this.name = name;
        this.clazzType = clazzType;
        this.isRequired = isRequired;
    }

    public String getName() {
        return name;
    }

    public Class getClazzType() {
        return clazzType;
    }

    public static boolean hasRequiredKeys(Map properties) {
        for (HandshakePropertyType type : HandshakePropertyType.values()) {
            if (!type.isRequired) {
                continue;
            }

            Object value = properties.get(type.getName());

            if (value == null) {
                return false;
            }

            if (!ClassUtils.isAssignable(value.getClass(), type.getClazzType())) {
                return false;
            }
        }

        return true;
    }

}


text:
namespace Abstraction.Models
{
    using System;
    using Contracts;

    public class Rectangle : IFigure
    {
        private double width;
        private double height;

        public Rectangle(double width, double height)
        {
            this.Width = width;
            this.Height = height;
        }

        public double Width
        {
            get
            {
                return this.width;
            }

            private set
            {
                if (value <= 0)
                {
                    throw new ArgumentException($"Incorrect value for width: {value}");
                }

                this.width = value;
            }
        }

        public double Height
        {
            get
            {
                return this.height;
            }

            private set
            {
                if (value <= 0)
                {
                    throw new ArgumentException($"Incorrect value for height: {value}");
                }

                this.height = value;
            }
        }

        public double CalcPerimeter()
        {
            double perimeter = 2 * (this.Width + this.Height);
            return perimeter;
        }

        public double CalcSurface()
        {
            double surface = this.Width * this.Height;
            return surface;
        }
    }
}


text:
<!DOCTYPE html>

		<title>Web accessibility demo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

		<link type="image/ico" rel="shortcut icon" href="//resources.esri.com/favicon.ico">
		<link type="image/ico" rel="icon"  href="//resources.esri.com/favicon.ico">

Web accessibility demo

Capturing navigation in JavaScript

Web accessibility refers to the inclusive practice of removing barriers that prevent access to websites by people with disabilities. When sites are correctly designed, developed and edited, all users have equal access to information and functionality.

				The needs that Web accessibility aims to address include:

Visual

Motor/Mobility

Auditory

Seizures

Cognitive/Intellectual

Content from Wikipedia: Web accessibility


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Polymer element for displaying material design management
 * transition screen.
 */

import '//resources/cr_elements/cr_shared_vars.css.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import '//resources/polymer/v3_0/paper-progress/paper-progress.js';
import '../../components/buttons/oobe_text_button.m.js';
import '../../components/common_styles/common_styles.m.js';
import '../../components/common_styles/oobe_dialog_host_styles.m.js';
import '../../components/dialogs/oobe_adaptive_dialog.m.js';

import {html, mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {LoginScreenBehavior, LoginScreenBehaviorInterface} from '../../components/behaviors/login_screen_behavior.m.js';
import {MultiStepBehavior, MultiStepBehaviorInterface} from '../../components/behaviors/multi_step_behavior.m.js';
import {OobeI18nBehavior, OobeI18nBehaviorInterface} from '../../components/behaviors/oobe_i18n_behavior.m.js';

const ManagementTransitionUIState = {
  PROGRESS: 'progress',
  ERROR: 'error',
};

/**
 * Possible transition types. Must be in the same order as
 * ArcSupervisionTransition enum values.
 * @enum {number}
 */
const ARC_SUPERVISION_TRANSITION = {
  NO_TRANSITION: 0,
  CHILD_TO_REGULAR: 1,
  REGULAR_TO_CHILD: 2,
  UNMANAGED_TO_MANAGED: 3,
};

/**
 * @constructor
 * @extends {PolymerElement}
 * @implements {LoginScreenBehaviorInterface}
 * @implements {OobeI18nBehaviorInterface}
 * @implements {MultiStepBehaviorInterface}
 */
const ManagementTransitionScreenBase = mixinBehaviors(
    [OobeI18nBehavior, LoginScreenBehavior, MultiStepBehavior], PolymerElement);

class ManagementTransitionScreen extends ManagementTransitionScreenBase {
  static get is() {
    return 'management-transition-element';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      /**
       * Property that determines transition direction.
       */
      arcTransition_: Number,
      /**
       * String that represents management entity for the user. Can be domain or
       * admin name.
       */
      managementEntity_: String,
    };
  }

  constructor() {
    super();
    this.managementEntity_ = '';
    this.arcTransition_ = ARC_SUPERVISION_TRANSITION.NO_TRANSITION;
  }

  defaultUIStep() {
    return ManagementTransitionUIState.PROGRESS;
  }

  get UI_STEPS() {
    return ManagementTransitionUIState;
  }

  /** Overridden from LoginScreenBehavior. */
  // clang-format off
  get EXTERNAL_API() {
    return ['showStep'];
  }
  // clang-format on

  ready() {
    super.ready();
    this.initializeLoginScreen('ManagementTransitionScreen');
  }

  onBeforeShow(data) {
    this.setArcTransition(data['arcTransition']);
    this.setManagementEntity(data['managementEntity']);
  }

  /**
   * Switches between different steps.
   * @param {string} step the steps to show
   */
  showStep(step) {
    this.setUIStep(step);
  }

  /**
   * Sets arc transition type.
   * @param {number} arc_transition enum element indicating transition type
   */
  setArcTransition(arc_transition) {
    switch (arc_transition) {
      case ARC_SUPERVISION_TRANSITION.CHILD_TO_REGULAR:
      case ARC_SUPERVISION_TRANSITION.REGULAR_TO_CHILD:
      case ARC_SUPERVISION_TRANSITION.UNMANAGED_TO_MANAGED:
        this.arcTransition_ = arc_transition;
        break;
      case ARC_SUPERVISION_TRANSITION.NO_TRANSITION:
        console.error(
            'Screen should not appear for ARC_SUPERIVISION_TRANSITION.NO_TRANSITION');
        break;
      default:
        console.error('Not handled transition type: ' + arc_transition);
    }
  }

  setManagementEntity(management_entity) {
    this.managementEntity_ = management_entity;
  }

  /** @private */
  getDialogTitle_(locale, arcTransition, managementEntity) {
    switch (arcTransition) {
      case ARC_SUPERVISION_TRANSITION.CHILD_TO_REGULAR:
        return this.i18n('removingSupervisionTitle');
      case ARC_SUPERVISION_TRANSITION.REGULAR_TO_CHILD:
        return this.i18n('addingSupervisionTitle');
      case ARC_SUPERVISION_TRANSITION.UNMANAGED_TO_MANAGED:
        if (managementEntity) {
          return this.i18n('addingManagementTitle', managementEntity);
        } else {
          return this.i18n('addingManagementTitleUnknownAdmin');
        }
    }
  }

  /** @private */
  isChildTransition_(arcTransition) {
    return arcTransition != ARC_SUPERVISION_TRANSITION.UNMANAGED_TO_MANAGED;
  }

  /**
   * On-tap event handler for OK button.
   *
   * @private
   */
  onAcceptAndContinue_() {
    this.userActed(['finish-management-transition']);
  }
}

customElements.define(
    ManagementTransitionScreen.is, ManagementTransitionScreen);


text:
<?php
namespace Rxnet\Contract;

use Rxnet\Event\Event;

interface MapperInterface
{
    /**
     * @param EventInterface $event
     * @return Event
     */
    public function __invoke(EventInterface $event);
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Light And Material</title>

A WebGL Example with Light and Material

This page requires Javascript and a web browser that supports WebGL

Drag your mouse on the canvas to rotate the scene.

   <input type="checkbox" id="anim" onchange="setAnimating(this.checked)"> Animate
   <button onclick="rotator.setView( [0,0,16], [0,1,0] ); frameNumber = 0; render()" style="margin-left:2cm">Reset View</button>
   Lights:
      <input type=checkbox id="l0" onchange="gl.uniform1f(uLight[0].enabled,this.checked); render()"> 0
      <input type=checkbox id="l1" onchange="gl.uniform1f(uLight[1].enabled,this.checked); render()"> 1
      <input type=checkbox id="l2" onchange="gl.uniform1f(uLight[2].enabled,this.checked); render()"> 2
      <input type=checkbox id="l3" onchange="gl.uniform1f(uLight[3].enabled,this.checked); render()"> 3

    <canvas width=600 height=600 id="glcanvas" style="background-color:blue"></canvas>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /home/tcrider/projects/dyn.timcrider.com/ipl4.dyn.timcrider.com/src/IPLocker/AdminStore</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/home/tcrider/projects/dyn.timcrider.com/ipl4.dyn.timcrider.com/src/IPLocker /

AdminStore

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

100.00%

54 / 54

100.00%

13 / 13

100.00%

1 / 1

       Json.php

100.00%

54 / 54

100.00%

13 / 13

100.00%

1 / 1

       StorageInterface.php

Legend

     Low: 0% to 35%
     Medium: 35% to 70%
     High: 70% to 100%

     Generated by PHP_CodeCoverage 1.2.0 using PHP 5.4.7 and PHPUnit 3.7.0 at Wed Sep 19 16:48:17 EDT 2012.


text:
asset.configure = function () {
    return {
        table: {
            overview: {
                fields: {
                    thumbnail: {
                        type: 'file'
                    }
                }
            },
            setupGuide: {
                fields: {
                    guideImage: {
                        type: 'file'
                    }
                }
            }
        },
        meta: {
            lifecycle: {
                name: 'DeviceLifeCycle',
                defaultAction: 'Create',
                defaultLifecycleEnabled: true
            },
            thumbnail: 'overview_thumbnail',
            banner: 'overview_thumbnail'
            //setupGuide_guideImage: 'setupGuide_guideImage'
        }
    };
};


text:
Puppet::Functions.create_function(:dns_aaaa) do
  dispatch :dns_aaaa do
    param 'String', :record
  end

  dispatch :dns_aaaa_with_default do
    param 'String', :record
    block_param
  end

  def dns_aaaa(record)
    Resolv::DNS.new.getresources(
      record, Resolv::DNS::Resource::IN::AAAA
    ).collect do |res|
      res.address.to_s
    end
  end

  def dns_aaaa_with_default(record)
    ret = dns_aaaa(record)
    if ret.empty?
      yield
    else
      ret
    end
  rescue Resolv::ResolvError
    yield
  end
end


text:
#

file (GLOB PLATFORM RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
    Mac/[^.]*.cpp
    Mac/[^.]*.mm
    Mac/[^.]*.h
    Mac/[^.]*.cmake
    )

# use this to add preprocessor definitions
add_definitions(
)

SOURCE_GROUP(Mac FILES ${PLATFORM})

set (SOURCES
    ${SOURCES}
    ${PLATFORM}
    )

include_directories(${JAVASCRIPTCORE}/Versions/A/Headers)

message("Adding library WebView")
add_library(WebView STATIC ${SOURCES})

add_subdirectory(${FB_WEBKITCORE_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/WebKitCore)

find_library(WEBKIT WebKit)
find_library(JAVASCRIPTCORE JavaScriptCore)

append_firebreath_include_dir(${JAVASCRIPTCORE}/Versions/A/Headers)
append_firebreath_include_dir(${FB_ROOT_DIR}/src/WebKitCore)
append_firebreath_link_library(${WEBKIT})
append_firebreath_link_library(${JAVASCRIPTCORE})
append_firebreath_link_library(WebKitCore)


text:
'''
contours_write_image.py

Experiment with OpenCV for FITS files.

http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html

Author: S.T. Castle
Created: 20150226
'''

import numpy as np
import cv2
import os.path

def contours(name, orig_img, blockSize, c):
    '''
    name: original filename of the image
    orig_img: The image to be processed.
    blockSize: size of the pixel neighborhood for adaptive thresholding.
    c: Correction to apply before thresholding.
    '''
    img = np.ndarray.copy(orig_img)    # Copy of original for smoothing.
    #cnt_imgcopy = np.ndarray.copy(img) # for contours without thresholding.
    am_imgcopy = np.ndarray.copy(img)  # for adaptive mean thresholding.
    ag_imgcopy = np.ndarray.copy(img)  # for adaptive Gaussian thresholding.
    ot_imgcopy = np.ndarray.copy(img)  # for Otsu's thresholding.
    ca_imgcopy = np.ndarray.copy(img)  # for canny edge detection.

    cnt_width = 25  # Thickness of the drawn contours. No algorithmic influence.

    # Split filename and extension.
    spl = os.path.splitext(name)
    name_pref = spl[0]  # Name prefix.

    # Apply a smoothing filter.
    img = cv2.bilateralFilter(img,9,75,75)
    name_pref = name_pref + '_smooth=bilat'

    # Just contours, no thresholding.
    #cnt_name = name_pref + '_contours' + spl[1]
    #contours, hierarchy = cv2.findContours(cnt_imgcopy,cv2.RETR_TREE,\
    #                                       cv2.CHAIN_APPROX_SIMPLE)
    #cv2.drawContours(cnt_imgcopy, contours, -1, (0,255,0), cnt_width)
    #cv2.imwrite(cnt_name, cnt_imgcopy)

    # Adaptive mean thresholding and contours.
    am_name = name_pref + '_adapt-mean-thr_contours' + spl[1]
    am_thr = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                                   cv2.THRESH_BINARY,blockSize,c)
    am_contours, am_hierarchy = cv2.findContours(am_thr,cv2.RETR_TREE,\
                                                 cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(am_imgcopy, am_contours, -1, (0,255,0), cnt_width)
    cv2.imwrite(am_name, am_imgcopy)

    # Adaptive Gaussian thresholding and contours.
    ag_name = name_pref + '_adapt-gauss-thr_contours' + spl[1]
    ag_thr = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                   cv2.THRESH_BINARY,blockSize,c)
    ag_contours, ag_hierarchy = cv2.findContours(ag_thr,cv2.RETR_TREE,\
                                                 cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(ag_imgcopy, ag_contours, -1, (0,255,0), cnt_width)
    cv2.imwrite(ag_name, ag_imgcopy)

    # Otsu's thresholding and contours.
    ot_name = name_pref + '_otsu-thr_contours' + spl[1]
    ret, ot_thr = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    ot_contours, ot_hierarchy = cv2.findContours(ot_thr,cv2.RETR_TREE,\
                                                 cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(ot_imgcopy, ot_contours, -1, (0,255,0), cnt_width)
    cv2.imwrite(ot_name, ot_imgcopy)

    # Canny edge detection and contours.
    ca_name = name_pref + '_canny_contours' + spl[1]
    canny = cv2.Canny(img,100,200)
    ca_contours, ca_hierarchy = cv2.findContours(canny,cv2.RETR_TREE,\
                                                 cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(ca_imgcopy, ca_contours, -1, (0,255,0), cnt_width)
    cv2.imwrite(ca_name, ca_imgcopy)


text:
package math

func Expm1(x float64) float64


text:
{% load static %}
const CACHE_NAME = 'apostello-cache-v1';
const OFFLINE_URL = '/offline/?_';
const urlsToCache = [
  OFFLINE_URL,
  "{% static 'js/app.js' %}",
  "{% static 'css/apostello.min.css' %}",
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
    .then(function(cache) {
      return cache.addAll(urlsToCache)
    })
  );
});

self.addEventListener('fetch', function(event) {
  if (event.request.mode === 'navigate' ||
    (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
    event.respondWith(
      fetch(event.request).catch(error => {
        return caches.match(OFFLINE_URL);
      }))
  } else {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
  }
});

self.addEventListener('activate', function(event) {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});


text:
package org.zaproxy.zap.extension.bugtracker;

import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.view.StandardFieldsDialog;

public class RaiseSemiAutoIssueDialog extends StandardFieldsDialog {

    private static final long serialVersionUID = -3223449799557586758L;

    private ExtensionBugTracker extension = null;
    private List<BugTracker> bugTrackers = null;

    private Set<Alert> alerts = null;
    private String FIELD_TRACKER_LIST = "bugtracker.trackers.list";

    public RaiseSemiAutoIssueDialog(ExtensionBugTracker ext, Frame owner, Dimension dim) {
        super(owner, "bugtracker.dialog.semi.title", dim);
        this.extension = ext;
        bugTrackers = extension.getBugTrackers();
    }

    public void setAlert(Set<Alert> alerts) {
        this.alerts = alerts;
        initialize();
    }

    /** This method initializes this */
    private void initialize() {
        this.removeAllFields();
        this.setTitle(Constant.messages.getString("bugtracker.popup.issue.semi"));
        addTrackerList(bugTrackers.get(0).getName());
        updateTrackerFields();
    }

    public void addTrackerList(String value) {
        List<String> trackerNames = new ArrayList<>();
        for (BugTracker bugTracker : bugTrackers) {
            trackerNames.add(bugTracker.getName());
        }
        this.addComboField(FIELD_TRACKER_LIST, trackerNames, value);
        for (BugTracker bugTracker : bugTrackers) {
            bugTracker.setDialog(this);
            bugTracker.setDetails(alerts);
        }
        this.addFieldListener(FIELD_TRACKER_LIST, e -> updateTrackerFields());
    }

    public void updateTrackerFields() {
        String currentItem = this.getStringValue(FIELD_TRACKER_LIST);
        for (BugTracker bugTracker : bugTrackers) {
            if (bugTracker.getName().equals(currentItem)) {
                this.removeAllFields();
                addTrackerList(bugTracker.getName());
                bugTracker.createDialogs();
                revalidate();
                repaint();
            }
        }
    }

    @Override
    public String validateFields() {
        String currentItem = this.getStringValue(FIELD_TRACKER_LIST);
        for (BugTracker bugTracker : bugTrackers) {
            if (bugTracker.getName().equals(currentItem)) {
                String response = bugTracker.raise(this);
                if (response != null) {
                    return response;
                }
                break;
            }
        }
        View.getSingleton().showMessageDialog(Constant.messages.getString("bugtracker.msg.raised"));
        return null;
    }

    @Override
    public void save() {}
}


text:
Pattern: Use of `next/script` `beforeInteractive` strategy outside `next/_document`

Issue: -

## Description

You can't use the `next/script` component with the `beforeInteractive` strategy outside the `_document.js` page. That's because `beforeInteractive` strategy only works inside `_document.js` and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).

### Possible Ways to Fix It

If you want a global script, move the script inside `_document.js` page.

```jsx
// In _document.js
import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
        <Script
          src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
          strategy="beforeInteractive"
        ></Script>
      </body>
    </Html>
  )
}

```

## Further Reading

* [next.js - beforeInteractive Script component outside _document.js](https://nextjs.org/docs/messages/no-before-interactive-script-outside-document)


text:
@interface TravelController : NSObject

- (id)initWithStartValue:(float)startValueInput andEndValue:(float)endValueInput andDurationInSec:(float)durationInput;
- (float) calcDisplacement;
- (float) resetDisplacementFast;

@property(retain) DAnimateFloat * travelTimeAnimation;
@property(assign) float displacement;
@property(assign) float durationInSeconds;
@property(assign) float startValue;
@property(assign) float endValue;
@property(assign) float realTimeSpeed;
@property(assign) BOOL stopDisplacement;

@property(assign) BOOL travelDidStart;
@property(assign) BOOL travelDidFinish;

@end


text:
inject_into_class 'config/application.rb', 'Application' do
  <<-CODE
    config.generators do |g|
      g.scaffold_stylesheet false
      g.assets false
      g.helper false
      g.stylesheets false
      g.jbuilder false
    end
  CODE
end

FileUtils.rm 'app/assets/stylesheets/application.css'
FileUtils.touch 'app/assets/stylesheets/application.scss'


text:
* retry starting httplistener on failure (better support for asp.net hosting where app pools are recycled)

###0.2.15 / 2015-03-03
* fix disposal of httplistener (@nkot)
* Added Process CPU usage into app counters (@o-mdr)
* resharper cleanup
* update dependencies

###0.2.14 / 2014-12-15
* fix possible issue when metrics are disabled and timer returns null TimerContext

###0.2.13 / 2014-12-14
* fix error when trying to globally disable metrics
* first elasticsearch bits

###0.2.11 / 2014-11-16
* graphite adapter (early bits, might have issues)
* refactor & cleanup reporting infra

###0.2.10 / 2014-11-06
* fix error logging for not found performance counters

###0.2.9 / 2014-11-05
* record active sessions for timers

###0.2.8 / 2014-10-29
* handle access issues for perf counters

###0.2.7 / 2014-10-28
* preparations for out-of-process metrics

###0.2.6 / 2014-10-17
* fix http listener prefix handling

###0.2.5 / 2014-10-12
* JSON metrics refactor
* remote metrics

###0.2.4 / 2014-10-07
* JSON version
* added environment
* various fixes

###0.2.3 / 2014-10-01
* add support for set counter & set meters [details](https://github.com/etishor/Metrics.NET/issues/21)
* cleanup owin adapter
* better & more resilient error handling

###0.2.2 / 2014-09-27
* add support for tagging metrics (not yet used in reports or visualization)
* add support for suppling a string user value to histograms & timers for tracking min / max / last values
* tests cleanup, some refactoring

###0.2.1 / 2014-09-25
* port latest changes from original metrics lib
* port optimization from ExponentiallyDecayingReservoir (https://github.com/etishor/Metrics.NET/commit/1caa9d01c16ff63504612d64771d52e9d7d9de5e)
* other minor optimizations
* add gauges for thread pool stats

###0.2.0 / 2014-09-20
* implement metrics contexts (and child contexts)
* make config more friendly
* most used condig options are now set by default
* add logging based on liblog (no fixed dependency - automaticaly wire into existing logging framework)
* update nancy & owin adapters to use contexts
* add some app.config settings to ease configuration

###0.1.11 / 2014-08-18
* update to latest visualization app (fixes checkboxes being outside dropdown)
* fix json caching in IE
* allow defining custom names for metric registry

###0.1.10 / 2014-07-30
* fix json formating (thanks to Evgeniy Kucheruk @kpoxa)

###0.1.9 / 2014-07-04
* make reporting more extensible

###0.1.8
* remove support for .NET 4.0

###0.1.6
* for histograms also store last value
* refactor configuration ( use Metric.Config.With...() )
* add option to completely disable metrics Metric.Config.CompletelyDisableMetrics() (useful for measuring metrics impact)
* simplify health checks


text:
create table public.nsl_union_avg (
  gid integer NOT NULL DEFAULT nextval('nsl_union_avg_gid_seq'::regclass),
  mronde character varying(6),
  rekenjaar character varying(4),
  spmi_avg numeric NOT NULL,
  geom geometry,
  creation_date timestamp with time zone,
  CONSTRAINT nsl_union_avg_pkey PRIMARY KEY (gid)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.nsl_union_avg
  OWNER TO postgres;
CREATE INDEX nsl_union_avg_rekenjaar_idx
  ON public.nsl_union_avg
  USING btree
  (rekenjaar);
CREATE INDEX nsl_union_avg_geom_gist
  ON public.nsl_union_avg
  USING gist
  (geom);


text:
#ifndef RENDER_SCRIPT_H
#define RENDER_SCRIPT_H

#include <stdint.h>
#include <sys/types.h>

#include "rsDefines.h"

// Legacy graphics functions
// Not extern C because not used from C++ API
RsObjectBase rsaFileA3DGetEntryByIndex(RsContext, uint32_t idx, RsFile);
RsFile rsaFileA3DCreateFromMemory(RsContext, const void *data, uint32_t len);
RsFile rsaFileA3DCreateFromAsset(RsContext, void *asset);
RsFile rsaFileA3DCreateFromFile(RsContext, const char *path);
void rsaFileA3DGetNumIndexEntries(RsContext, int32_t *numEntries, RsFile);
void rsaFileA3DGetIndexEntries(RsContext, RsFileIndexEntry *fileEntries,
                               uint32_t numEntries, RsFile);
// Mesh update functions
void rsaMeshGetVertexBufferCount(RsContext, RsMesh, int32_t *vtxCount);
void rsaMeshGetIndexCount(RsContext, RsMesh, int32_t *idxCount);
void rsaMeshGetVertices(RsContext, RsMesh, RsAllocation *vtxData, uint32_t vtxDataCount);
void rsaMeshGetIndices(RsContext, RsMesh, RsAllocation *va,
                       uint32_t *primType, uint32_t idxDataCount);
RsContext rsContextCreateGL(RsDevice dev, uint32_t version, uint32_t sdkVersion,
                            RsSurfaceConfig sc, uint32_t dpi);

extern "C" {
    void rsaGetName(RsContext, void * obj, const char **name);
    // Allocation update
    const void* rsaAllocationGetType(RsContext con, RsAllocation va);
    // Type update
    void rsaTypeGetNativeData(RsContext, RsType, uint32_t *typeData, uint32_t typeDataSize);
    // Element update
    void rsaElementGetNativeData(RsContext, RsElement, uint32_t *elemData, uint32_t elemDataSize);
    void rsaElementGetSubElements(RsContext, RsElement, uint32_t *ids, const char **names,
                                  uint32_t *arraySizes, uint32_t dataSize);

    RsDevice rsDeviceCreate();
    void rsDeviceDestroy(RsDevice dev);
    void rsDeviceSetConfig(RsDevice dev, RsDeviceParam p, int32_t value);
    RsContext rsContextCreate(RsDevice dev, uint32_t version, uint32_t sdkVersion,
                              RsContextType ct, uint32_t flags);
}
#include "rsgApiFuncDecl.h"

#endif // RENDER_SCRIPT_H


text:
System.register(["angular2/core", "./book-welcome.component", "./book-item.component", "./book-special.component", "../services/book-item.service", "../services/book-special.service", "../pipes/search.pipe", "../pipes/keys.pipe", "../pipes/array-of-book-items.pipe"], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var core_1, core_2, book_welcome_component_1, book_item_component_1, book_special_component_1, book_item_service_1, book_special_service_1, search_pipe_1, keys_pipe_1, array_of_book_items_pipe_1;
    var AppComponent;
    return {
        setters:[
            function (core_1_1) {
                core_1 = core_1_1;
                core_2 = core_1_1;
            },
            function (book_welcome_component_1_1) {
                book_welcome_component_1 = book_welcome_component_1_1;
            },
            function (book_item_component_1_1) {
                book_item_component_1 = book_item_component_1_1;
            },
            function (book_special_component_1_1) {
                book_special_component_1 = book_special_component_1_1;
            },
            function (book_item_service_1_1) {
                book_item_service_1 = book_item_service_1_1;
            },
            function (book_special_service_1_1) {
                book_special_service_1 = book_special_service_1_1;
            },
            function (search_pipe_1_1) {
                search_pipe_1 = search_pipe_1_1;
            },
            function (keys_pipe_1_1) {
                keys_pipe_1 = keys_pipe_1_1;
            },
            function (array_of_book_items_pipe_1_1) {
                array_of_book_items_pipe_1 = array_of_book_items_pipe_1_1;
            }],
        execute: function() {
            AppComponent = (function () {
                // Constructor/Initialiser function to auto setup instance value of Component
                function AppComponent(bookItemService, bookSpecialService) {
                    this.bookItemService = bookItemService;
                    this.bookSpecialService = bookSpecialService;
                    // Declare with default value
                    this.selectedBookSort = "NAME";
                }
                AppComponent.prototype.ngOnInit = function () {
                    this.bookItems = this.bookItemService.get();
                    this.bookSpecials = this.bookSpecialService.get();
                };
                AppComponent.prototype.onUpdateRating = function (value, bookItem) {
                    console.log("Receiving Emitted Event to Update Rating: " + value + ".. for Book Item: " + bookItem);
                    this.bookItemService.updateRating(value, bookItem);
                };
                AppComponent.prototype.onBookItemDeleted = function (bookItem) {
                    console.log("Receiving Emitted Event to Delete: " + bookItem);
                    this.bookItemService.remove(bookItem);
                };
                // Triggered when user changes drop-down to sort book items by "name" or "author"
                AppComponent.prototype.onBookSortChange = function (newValue) {
                    this.selectedBookSort = newValue;
                    // console.log(newValue);
                };
                AppComponent = __decorate([
                    core_1.Component({
                        // Emulated is for all styles in and no styles out of component (default)
                        encapsulation: core_2.ViewEncapsulation.Emulated,
                        selector: "my-app",
                        templateUrl: "partials/app.html",
                        directives: [book_welcome_component_1.BookWelcomeComponent, book_item_component_1.BookItemComponent, book_special_component_1.BookSpecialComponent],
                        pipes: [search_pipe_1.SearchPipe, keys_pipe_1.KeysPipe, array_of_book_items_pipe_1.ArrayOfBookItemsPipe],
                        // CSS Styles in External Stylesheet
                        styleUrls: [
                            "css/app.css"
                        ]
                    }),
                    __metadata('design:paramtypes', [book_item_service_1.BookItemService, book_special_service_1.BookSpecialService])
                ], AppComponent);
                return AppComponent;
            }());
            exports_1("AppComponent", AppComponent); // end export
        }
    }
});

//# sourceMappingURL=app.component.js.map


text:
class Kitten < ActiveRecord::Base
end


text:
export interface Reference {
  name : string;
  number : string;
}


text:
require 'test_helper'

class KeywordReplyTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package iso20022

// Reason for a pending status.
type PendingStatusReason14 struct {

	// Reason for the pending account status.
	Code *PendingStatusReason2Choice `xml:"Cd"`

	// Additional information about the reason for the pending account status.
	AdditionalInformation *Max350Text `xml:"AddtlInf,omitempty"`
}

func (p *PendingStatusReason14) AddCode() *PendingStatusReason2Choice {
	p.Code = new(PendingStatusReason2Choice)
	return p.Code
}

func (p *PendingStatusReason14) SetAdditionalInformation(value string) {
	p.AdditionalInformation = (*Max350Text)(&value)
}


text:
import React from 'react';
import Modal from 'antd/lib/modal/Modal';

interface FileProps {
  show: boolean;
  onCancel: () => void;
  title: string;
  okText: string;
}

const defaultProps = { title: 'Choose a file', okText: 'Select' };

const FileChooserModal: React.FC<FileProps> = ({ show, onCancel, title, okText }) => {
  const handleOk = () => {
    //temporary until the file is selected through the file chooser compoent
    onCancel();
  };

  const handleCancel = () => {
    onCancel();
  };

  return (
    <Modal
      title={title}
      open={show}
      onOk={handleOk}
      onCancel={handleCancel}
      okText={okText}
    ></Modal>
  );
};

FileChooserModal.defaultProps = defaultProps;

export default FileChooserModal;


text:
<title>Phing API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/jquery-ui.css" type="text/css"></link><link rel="stylesheet" href="css/docblox/jquery-ui-1.8.16.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

tasks/ext/PearPackageTask.php

              Show:
              inherited

                          Classes

\PearPackageTask

\PearPkgMapping

\PearPkgMappingElement

\PearPkgOption

\PearPkgRole

              Table of Contents

\PearPackageTask
jump to top

Package: phing\tasks\ext
A task to create PEAR package.xml file.

This class uses the PEAR_PackageFileMaintainer class to perform the work.

This class is designed to be very flexible -- i.e. account for changes to the package.xml w/o
requiring changes to this class.  We've accomplished this by having generic <option> and <mapping>
nested elements.  All options are set using PEAR_PackageFileMaintainer::setOptions().

The <option> tag is used to set a simple option value.

<option name="option_name" value="option_value"/>
or <option name="option_name">option_value</option>

The <mapping> tag represents a complex data type.  You can use nested <element> (and nested <element> with
<element> tags) to represent the full complexity of the structure.  Bear in mind that what you are creating
will be mapped to an associative array that will be passed in via PEAR_PackageFileMaintainer::setOptions().

<mapping name="option_name">
 <element key="key_name" value="key_val"/>
 <element key="key_name" value="key_val"/>
</mapping>

Here's an over-simple example of how this could be used:

<pearpkg name="phing" dir="${build.src.dir}" destFile="${build.base.dir}/package.xml">
 <fileset>
  <include name="**"/>
 </fileset>
 <option name="notes">Sample release notes here.</option>
 <option name="description">Package description</option>
 <option name="summary">Short description</option>
 <option name="version" value="2.0.0b1"/>
 <option name="state" value="beta"/>
 <mapping name="maintainers">
  <element>
   <element key="handle" value="hlellelid"/>
   <element key="name" value="Hans"/>
   <element key="email" value="hans@xmpl.org"/>
   <element key="role" value="lead"/>
  </element>
 </mapping>
</pearpkg>

Look at the build.xml in the Phing base directory (assuming you have the full distro / CVS version of Phing) to
see a more complete example of how to call this script.

Parent(s)

\MatchingTask
            <
            \Task
            <
            \ProjectComponent

Children

\PearPackage2Task

Author

Hans Lellelid

Version

$Id: PearPackageTask.php 1162 2011-06-17 21:24:01Z mrook $

Properties

                 $dir= ''

Base directory for reading files.

Details

Type

n/a

array
                 $filesets= 'array()'

FileSet[]

Default valuearray()Details

Type

array

                 $mappings= 'array()'

Nested <mapping> (complex options) types.

Default valuearray()Details

Type

n/a

array
                 $options= 'array()'

PearPkgOption[]

Default valuearray()Details

Type

array

                 $package= ''

Details

Type

n/a

                 $packageFile= ''

Package file

Details

Type

n/a

\PEAR_PackageFileManager
                 $pkg= ''

Details

Type

\PEAR_PackageFileManager

                 $preparedOptions= 'array()'

Default valuearray()Details

Type

n/a

\PearPkgRole[]
                 $roles= 'array()'

Nested <role> elements

Default valuearray()Details

Type

\PearPkgRole[]

Methods

__construct(

          )

        :
          void

appendSelector(

          )

        :
          void

createAnd(

          )

        :
          void

createContains(

          )

        :
          void

createCustom(

          )

        :
          void

createDate(

          )

        :
          void

createDepend(

          )

        :
          void

createDepth(

          )

        :
          void

createExclude(

          )

        :
          void

createExcludesFile(

          )

        :
          void

createFileSet(

          )

        :
          \FileSet

Nested creator, creates a FileSet for this task

Returns

Type
Description

\FileSet
The created fileset object

createFilename(

          )

        :
          void

createInclude(

          )

        :
          void

createIncludesFile(

          )

        :
          void

createMajority(

          )

        :
          void

createMapping(

          )

        :
          void

Handles nested generic <option> elements.

createNone(

          )

        :
          void

createNot(

          )

        :
          void

createOption(

          )

        :
          void

Handles nested generic <option> elements.

createOr(

          )

        :
          void

createPatternSet(

          )

        :
          void

createPresent(

          )

        :
          void

createRole(

          )

        :
          \PearPkgRole

Handles nested <role> elements

Returns

Type
Description

\PearPkgRole

createSelector(

          )

        :
          void

createSize(

          )

        :
          void

fixDeps(
           $deps
          )

        :
          void

Fixes the boolean in optional dependencies

Parameters

Name
Type
Description

$deps

getDescription(

          )

        :
          void

getDirectoryScanner(

          )

        :
          void

getFileSets(

          )

        :
          array

Used by the PEAR_PackageFileManager_PhingFileSet lister.

Returns

Type
Description

array
FileSet[]

getImplicitFileSet(

          )

        :
          void

final

getLocation(

          )

        :
          void

getOwningTarget(

          )

        :
          void

getProject(

          )

        :
          void

getRegisterSlot(

          )

        :
          void

getRuntimeConfigurableWrapper(

          )

        :
          void

getSelectors(

          )

        :
          void

getTaskName(

          )

        :
          void

getTaskType(

          )

        :
          void

hasSelectors(

          )

        :
          void

init(

          )

        :
          void

log(

          )

        :
          void

main(

          )

        :
          void

Main entry point.

maybeConfigure(

          )

        :
          void

perform(

          )

        :
          void

populateOptions(

          )

        :
          void

Adds the options that are set via attributes and the nested tags to the options array.

selectorCount(

          )

        :
          void

selectorElements(

          )

        :
          void

setCaseSensitive(

          )

        :
          void

setDefaultexcludes(

          )

        :
          void

setDescription(

          )

        :
          void

setDestFile(
           $f
          )

        :
          void

Sets the file to use for generated package.xml

Parameters

Name
Type
Description

$f

setDir(
          \PhingFile $f
          )

        :
          void

Sets "dir" property from XML.

Parameters

Name
Type
Description

$f
\PhingFile

setExcludes(

          )

        :
          void

setExcludesfile(

          )

        :
          void

setFollowSymlinks(

          )

        :
          void

setIncludes(

          )

        :
          void

setIncludesfile(

          )

        :
          void

setLocation(

          )

        :
          void

setName(
          string $v
          )

        :
          void

Sets "name" property from XML.

Parameters

Name
Type
Description

$v
string

setOptions(

          )

        :
          void

Sets PEAR package.xml options, based on class properties.

setOwningTarget(

          )

        :
          void

setPackage(
          string $v
          )

        :
          void

Set "package" property from XML.

Parameters

Name
Type
Description

$v
string

Details

See

\setName()

setProject(

          )

        :
          void

setRuntimeConfigurableWrapper(

          )

        :
          void

setTaskName(

          )

        :
          void

setTaskType(

          )

        :
          void

\PearPkgMapping
jump to top

Package: phing\tasks\ext
Handles complex options <mapping> elements which are hashes (assoc arrays).

Properties

                 $elements= 'array()'

Default valuearray()Details

Type

n/a

                 $name= ''

Details

Type

n/a

Methods

createElement(

          )

        :
          void

getElements(

          )

        :
          void

getName(

          )

        :
          void

getValue(

          )

        :
          array

Returns the PHP hash or array of hashes (etc.) that this mapping represents.

Returns

Type
Description

array

setName(
           $v
          )

        :
          void

Parameters

Name
Type
Description

$v

\PearPkgMappingElement
jump to top

Package: phing\tasks\ext
Sub-element of <mapping>.

Properties

                 $elements= 'array()'

Default valuearray()Details

Type

n/a

                 $key= ''

Details

Type

n/a

                 $value= ''

Details

Type

n/a

Methods

createElement(

          )

        :
          void

Handles nested <element> tags.

getKey(

          )

        :
          void

getValue(

          )

        :
          mixed

Returns either the simple value or
the calculated value (array) of nested elements.

Returns

Type
Description

mixed

setKey(
           $v
          )

        :
          void

Parameters

Name
Type
Description

$v

setValue(
           $v
          )

        :
          void

Parameters

Name
Type
Description

$v

\PearPkgOption
jump to top

Package: phing\tasks\ext
Generic option class is used for non-complex options.

Properties

                 $name= ''

Details

Type

n/a

                 $value= ''

Details

Type

n/a

Methods

addText(
           $txt
          )

        :
          void

Parameters

Name
Type
Description

$txt

getName(

          )

        :
          void

getValue(

          )

        :
          void

setName(
           $v
          )

        :
          void

Parameters

Name
Type
Description

$v

setValue(
           $v
          )

        :
          void

Parameters

Name
Type
Description

$v

\PearPkgRole
jump to top

Package: phing\tasks\ext
Encapsulates file roles

Properties

string
                 $extension= ''

Details

Type

string

string
                 $role= ''

Details

Type

string

Methods

getExtension(

          )

        :
          string

Retrieves the file extension

Returns

Type
Description

string

getRole(

          )

        :
          string

Retrieves the role

Returns

Type
Description

string

setExtension(
          string $extension
          )

        :
          void

Sets the file extension

Parameters

Name
Type
Description

$extension
string

setRole(
          string $role
          )

        :
          void

Sets the role

Parameters

Name
Type
Description

$role
string

Documentation was generated by DocBlox 0.17.1.


text:
@implementation AccessFactory

- (IUser *)createUser {
    return [[AccessUser alloc]init];
}

- (IDepartment *)creatDepartment {
    return [[AccessDepartment alloc]init];
}

@end