text:
package com.izforge.izpack.panels.userinput.console.custom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.handler.Prompt;
import com.izforge.izpack.panels.userinput.FieldCommand;
import com.izforge.izpack.panels.userinput.console.ConsoleField;
import com.izforge.izpack.panels.userinput.field.Field;
import com.izforge.izpack.panels.userinput.field.UserInputPanelSpec;
import com.izforge.izpack.panels.userinput.field.ValidationStatus;
import com.izforge.izpack.panels.userinput.field.custom.Column;
import com.izforge.izpack.panels.userinput.field.custom.CustomField;
import com.izforge.izpack.panels.userinput.field.custom.CustomFieldType;
import com.izforge.izpack.util.Console;

public class ConsoleCustomField extends ConsoleField implements CustomFieldType
{
    private final UserInputPanelSpec userInputPanelSpec;

    private final IXMLElement spec;

    private final FieldCommand createField;

    private int numberOfRows = 0;

    private int numberOfColumns = 0;

    private final CustomField customInfoField;

    private final int maxRow;
    private final int minRow;

    private final static int CONTINUE = 1;
    private final static int REDISPLAY = 2;

    Map<Integer, List<ConsoleField>> consoleFields;

    /**
     * Constructs a {@code ConsoleField}.
     *
     * @param customField the field
     * @param console     the console
     * @param prompt      the prompt
     */
    public ConsoleCustomField(CustomField customField, Console console, Prompt prompt,
                              FieldCommand createField, UserInputPanelSpec userInputPanelSpec, IXMLElement spec)
    {
        super(customField, console, prompt);
        this.spec = spec;
        this.userInputPanelSpec = userInputPanelSpec;
        this.createField = createField;
        this.customInfoField = customField;
        this.maxRow = customField.getMaxRow();
        this.minRow = customField.getMinRow();
        this.numberOfColumns = customField.getFields().size();
    }

    /**
     * Returns the field.
     *
     * @return the field
     */
    @Override
    public CustomField getField()
    {
        return (CustomField) super.getField();
    }

    /**
     * Ensure to display the minimum amount of rows required.
     */
    private void addInitialRows()
    {
        for (int count = minRow; count >= 1; count--)
        {
            addRow();
        }
    }

    private void showInitialRows()
    {
        for (int i = 1; i <= numberOfRows; i++)
        {
            editRow(i, true);
        }
    }

    private boolean editRow(int rowNumber, boolean initial)
    {
        List<ConsoleField> fields = consoleFields.get(Integer.valueOf(rowNumber));
        print("--> Row " + rowNumber + ": ");
        for (ConsoleField field : fields)
        {
            field.setDisplayed(true);
            final boolean ro = field.isReadonly();
            if (initial)
            {
                // Switch display mode temporarily
                field.setReadonly(true);
                // Avoid initial null values after initializing the first row
                field.getField().setValue(field.getField().getInitialValue());
            }
            while (!field.display())
            {
                // loop unless we have a valid value
            }
            if (initial)
            {
                field.setReadonly(ro);
            }
        }

        return true;
    }

    private boolean canAddRow()
    {
        return numberOfRows < maxRow;
    }

    /**
     * Add a new row to the panel.
     *
     * @return true if the row could be added
     */
    private boolean addRow()
    {
        if (!canAddRow())
        {
            return false;
        }
        numberOfRows++;
        List<ConsoleField> fields = new ArrayList<ConsoleField>();

        for (Field field : createCustomField(userInputPanelSpec, spec).getFields())
        {
            field.setVariable(field.getVariable() + "." + numberOfRows);
            ConsoleField consoleField = createField.createConsoleField(field);
            consoleField.setReadonly(isReadonly());
            fields.add(consoleField);
        }

        consoleFields.put(Integer.valueOf(numberOfRows), fields);

        return true;
    }

    private boolean canRemoveRow()
    {
        return numberOfRows > minRow;
    }

    private boolean removeRow()
    {
        if (!canRemoveRow())
        {
            return false;
        }
        consoleFields.remove(Integer.valueOf(numberOfRows));
        numberOfRows--;
        return true;
    }

    /**
     * Display the custom field.
     *
     * @return
     */
    @Override
    public boolean display()
    {
        numberOfRows = 0;
        consoleFields = new HashMap<Integer, List<ConsoleField>>();

        addInitialRows();

        int value = REDISPLAY;
        do
        {
            int userValue;
            showInitialRows();
            if (isReadonly())
            {
                userValue = getConsole().prompt("Enter 1 to continue, 2 to redisplay", 1, 2, 2, -1);
                switch (userValue)
                {
                    case 1:
                        value = CONTINUE;
                        break;
                    default:
                        value = REDISPLAY;
                        break;
                }
            }
            else
            {
                userValue = getConsole().prompt("Enter the row number (" + 1 + ".." + numberOfRows + ") to edit, "
                        + Integer.toString(numberOfRows+1) + " to accept all, "
                        + Integer.toString(numberOfRows+2) + " to redisplay"
                        + (canAddRow()?", " + Integer.toString(numberOfRows+3) + " to add a row":"")
                        + (canRemoveRow()?", " + Integer.toString(numberOfRows+4) + " to remove the last row":""),
                        1, numberOfRows+4, numberOfRows+4, -1);
                if (userValue <= numberOfRows)
                {
                    editRow(userValue, false);
                    value = REDISPLAY;
                }
                else if (userValue == numberOfRows+1)
                {
                    value = CONTINUE;
                }
                else if (userValue == numberOfRows+3)
                {
                    if (addRow())
                    {
                        editRow(numberOfRows, false);
                    }
                    value = REDISPLAY;
                }
                else if (userValue == numberOfRows+4)
                {
                    removeRow();
                    value = REDISPLAY;
                }
                else
                {
                    value = REDISPLAY;
                }
            }

        } while (value != CONTINUE);

        customInfoField.setValue(Integer.toString(numberOfRows));

        if (!columnsAreValid())
        {
            this.display();
        }

        return true;
    }

    private boolean columnsAreValid()
    {
        List<Column> columns = customInfoField.getColumns();
        String[] columnVariables = getVariablesByColumn();
        for (int i = 0; i < columnVariables.length; i++)
        {
            ValidationStatus status = columns.get(i).validate(columnVariables[i]);
            if (!status.isValid())
            {
                System.out.println(status.getMessage());
                return false;
            }
        }
        return true;
    }

    //TODO: Refactor duplicated code form CustomInputRows
    private String[] getVariablesByColumn()
    {
        String[] columnVariables = new String[numberOfColumns];

        for (int col = 0; col < numberOfColumns; col++)
        {
            columnVariables[col] = "";
            for (int row = 1; row <= numberOfRows; row++)
            {
                ConsoleField consoleField = consoleFields.get(Integer.valueOf(row)).get(col);
                if (consoleField.isDisplayed())
                {
                    columnVariables[col] += getField().getInstallData().getVariable(consoleField.getVariable()) + ",";
                }
            }
        }
        for (int i = 0; i < columnVariables.length; i++)
        {
            String v = columnVariables[i];
            columnVariables[i] = v.substring(0, v.length() - 1);
        }
        return columnVariables;
    }

    /**
     * Get the variables associated with this custom field.
     * @return
     */
    @Override
    public List<String> getVariables()
    {
        List<String> countedVariables = new ArrayList<String>();

        for (int i = 1; i <= numberOfRows; i++)
        {
            for(ConsoleField consoleField : consoleFields.get(Integer.valueOf(i)))
            {
                if (consoleField.isDisplayed())
                {
                    countedVariables.add(consoleField.getVariable());
                }
            }
        }
        return countedVariables;
    }

    /**
     * Generate a new custom field.
     * @return
     */
    private CustomField createCustomField(UserInputPanelSpec userInputPanelSpec, IXMLElement spec)
    {
        List<Field> fields = userInputPanelSpec.createFields(spec);
        for (Field field : fields)
        {
            if (field instanceof CustomField)
            {
                return (CustomField) field;
            }
        }
        return  null;
    }
}


text: DNS-based PHP client for Consul services

redpajama_set_name: RedPajamaGithub


text:
package com.ssm.common.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.Set;

/**
 * jedis manager
 *
 * @author vincent
 */
public class JedisManager {

    private JedisPool jedisPool;

    public Jedis getJedis() {
        Jedis jedis = null;
        try {
            jedis = getJedisPool().getResource();
        } catch (Exception e) {
            throw new JedisConnectionException(e);
        }
        return jedis;
    }

    public void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
        if (isBroken)
            getJedisPool().close();
        else
            getJedisPool().close();
    }

    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        byte[] result = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return result;
    }

    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.del(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }

    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)
            throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public Set<byte[]> getKeysByKeysPattern(byte[] serialize) {
        Set<byte[]> keys = null;
        Jedis jedis = jedisPool.getResource();
        try{
            keys = jedis.keys(serialize);
        }finally{
            jedisPool.close();
        }
        return keys;
    }
}


text: raise NotImplementedError("locale is not yet implemented in Skulpt")


text:
package org.dashbuilder.client.widgets.dataset.editor.widgets;

import com.github.gwtbootstrap.client.ui.*;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.github.gwtbootstrap.client.ui.event.ShowEvent;
import com.github.gwtbootstrap.client.ui.event.ShowHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import org.dashbuilder.client.widgets.dataset.editor.widgets.events.EditDataSetEvent;
import org.dashbuilder.client.widgets.dataset.editor.widgets.events.EditDataSetEventHandler;
import org.dashbuilder.client.widgets.resources.i18n.DataSetExplorerConstants;
import org.dashbuilder.common.client.error.ClientRuntimeError;
import org.dashbuilder.dataset.DataSetMetadata;
import org.dashbuilder.dataset.client.DataSetMetadataCallback;
import org.dashbuilder.dataset.client.resources.bundles.DataSetClientImages;
import org.dashbuilder.dataset.client.resources.bundles.DataSetClientResources;
import org.dashbuilder.dataset.def.DataSetDef;

import javax.enterprise.context.Dependent;
import java.util.*;

/**
 *
Default view for DataSetExplorer presenter.

 * @since 0.3.0
 */
@Dependent
public class DataSetExplorerView extends Composite implements DataSetExplorer.View {

    private final static String WHITESPACE = " ";
    private final static String ICONS_SIZE = "16px";
    private final static String ESTIMATIONS_FORMAT = "#,###.0";

    private final static NumberFormat rowsFormat = NumberFormat.getFormat("##0");

    interface DataSetExplorerViewBinder extends UiBinder<Widget, DataSetExplorerView> {}
    private static DataSetExplorerViewBinder uiBinder = GWT.create(DataSetExplorerViewBinder.class);

    interface DataSetExplorerViewStyle extends CssResource {
        String columnsPanel();
        String statusPanel();
        String statusIcon();
        String statusText();
        String statusTextTitle();
        String estimationsPanel();
        String buttonsPanel();
        String button();
        String slidingPanel();
        String deleteText();
    }

    @UiField
    DataSetExplorerViewStyle style;

    @UiField
    Modal errorPanel;

    @UiField
    Button errorPanelButton;

    @UiField
    HTML errorType;

    @UiField
    HTML errorMessage;

    @UiField
    HTML errorCause;

    @UiField
    Row errorTypeRow;

    @UiField
    Row errorMessageRow;

    @UiField
    Row errorCauseRow;

    @UiField
    Accordion dataSetsAccordion;

    @UiField
    Label label;

    private Set<DataSetDef> dataSets;

    private final ClickHandler errorPanelButtonHandler = new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            hideError();
        }
    };

    public DataSetExplorerView() {
        initWidget(uiBinder.createAndBindUi(this));
        dataSets = new LinkedHashSet<DataSetDef>();
        errorPanelButton.addClickHandler(errorPanelButtonHandler);
    }

    @Override
    public void set(Collection<DataSetDef> dataSetDefs) {
        this.dataSets = new LinkedHashSet<DataSetDef>(dataSetDefs);
    }

    @Override
    public boolean add(DataSetDef dataSetDef) {
        return dataSets.add(dataSetDef);
    }

    @Override
    public void remove(DataSetDef dataSetDef) {
        if (dataSets != null && dataSetDef != null && dataSetDef.getUUID() != null) {
            remove(dataSetDef.getUUID());
        }
    }

    @Override
    public boolean update(final DataSetDef oldDataSetDef, final DataSetDef newDataSetDef) {
        remove(oldDataSetDef.getUUID());
        return dataSets.add(newDataSetDef);
    }

    private void remove(final String uuid) {
        if (dataSets != null )
        {
            final Iterator<DataSetDef> it = dataSets.iterator();
            while (it.hasNext())
            {
                DataSetDef def = it.next();
                if (def.getUUID().equals(uuid)) it.remove();
            }
        }
    }

    @Override
    public void clear() {
        dataSets.clear();
        clearView();
    }

    private void clearView() {
        label.setText("");
        label.setVisible(false);
        dataSetsAccordion.clear();
    }

    @Override
    public void show(final DataSetExplorer.ShowDataSetDefCallback callback) {
        clearView();

        if (!dataSets.isEmpty()) {
            label.setVisible(false);
            for (DataSetDef dataSetDef : dataSets) {
                final AccordionGroup accordionGroup = buildDataSetAccordionGroup(dataSetDef, callback);
                dataSetsAccordion.add(accordionGroup);
            }

        } else {
            label.setText(DataSetExplorerConstants.INSTANCE.noDataSets());
            label.setVisible(true);
        }
        dataSetsAccordion.setVisible(true);
    }

    private AccordionGroup buildDataSetAccordionGroup(final DataSetDef dataSetDef, final DataSetExplorer.ShowDataSetDefCallback callback) {
        final AccordionGroup accordionGroup = new AccordionGroup();

        // Heading.
        accordionGroup.setHeading(dataSetDef.getName());
        // CollapseTrigger collapseTrigger = new CollapseTrigger();

        // Icon for provider type.
        final Image typeIcon = buildTypeIcon(dataSetDef);
        if (typeIcon != null) accordionGroup.addCustomTrigger(typeIcon);

        accordionGroup.addShowHandler(new ShowHandler() {
            @Override
            public void onShow(ShowEvent showEvent) {
                buildDescription(dataSetDef, accordionGroup, callback);
            }
        });

        return accordionGroup;
    }

    private Image buildTypeIcon(final DataSetDef dataSetDef) {
        Image typeIcon = null;
        switch (dataSetDef.getProvider()) {
            case BEAN:
                typeIcon = new Image(DataSetClientResources.INSTANCE.images().javaIcon32().getSafeUri());
                typeIcon.setAltText(DataSetExplorerConstants.INSTANCE.bean());
                typeIcon.setTitle(DataSetExplorerConstants.INSTANCE.bean());
                break;
            case CSV:
                typeIcon = new Image(DataSetClientResources.INSTANCE.images().csvIcon32().getSafeUri());
                typeIcon.setAltText(DataSetExplorerConstants.INSTANCE.csv());
                typeIcon.setTitle(DataSetExplorerConstants.INSTANCE.csv());
                break;
            case SQL:
                typeIcon = new Image(DataSetClientResources.INSTANCE.images().sqlIcon32().getSafeUri());
                typeIcon.setAltText(DataSetExplorerConstants.INSTANCE.sql());
                typeIcon.setTitle(DataSetExplorerConstants.INSTANCE.sql());
                break;
            case ELASTICSEARCH:
                typeIcon = new Image(DataSetClientResources.INSTANCE.images().elIcon32().getSafeUri());
                typeIcon.setAltText(DataSetExplorerConstants.INSTANCE.el());
                typeIcon.setTitle(DataSetExplorerConstants.INSTANCE.el());
                break;
        }
        typeIcon.setSize(ICONS_SIZE, ICONS_SIZE);
        return typeIcon;

    }

    private void buildDescription(final DataSetDef dataSetDef, final Panel parent, final DataSetExplorer.ShowDataSetDefCallback callback) {
        if (parent != null) {
            // Clear current details.
            parent.clear();

            final DataSetClientImages images = DataSetClientResources.INSTANCE.images();

            final HTML statusText = new HTML(DataSetExplorerConstants.INSTANCE.currentStatus());
            statusText.addStyleName(style.statusTextTitle());

            // Caches and refresh.

            final boolean isCacheEnabled = dataSetDef.isCacheEnabled();
            FlowPanel cachePanel = null;

            if (callback.isShowBackendCache(dataSetDef)) {
                cachePanel = new FlowPanel();
                final com.github.gwtbootstrap.client.ui.Image cacheEnabled = new com.github.gwtbootstrap.client.ui.Image(
                        isCacheEnabled ? images.okIconSmall() : images.cancelIconSmall());
                final String _cache = isCacheEnabled ? DataSetExplorerConstants.INSTANCE.enabled() : DataSetExplorerConstants.INSTANCE.disabled();
                cacheEnabled.setTitle(_cache);
                cacheEnabled.setAltText(_cache);
                cacheEnabled.addStyleName(style.statusIcon());
                final HTML cacheText = new HTML(DataSetExplorerConstants.INSTANCE.cache());
                cacheText.addStyleName(style.statusText());
                cachePanel.add(cacheEnabled);
                cachePanel.add(cacheText);
            }

            final boolean isPushEnabled = dataSetDef.isPushEnabled();
            final FlowPanel pushPanel = new FlowPanel();
            final com.github.gwtbootstrap.client.ui.Image pushEnabled = new com.github.gwtbootstrap.client.ui.Image(
                    isPushEnabled ? images.okIconSmall() : images.cancelIconSmall());
            final String _push = isPushEnabled ? DataSetExplorerConstants.INSTANCE.enabled() : DataSetExplorerConstants.INSTANCE.disabled();
            pushEnabled.setTitle(_push);
            pushEnabled.setAltText(_push);
            pushEnabled.addStyleName(style.statusIcon());
            final HTML pushText = new HTML(DataSetExplorerConstants.INSTANCE.push());
            pushText.addStyleName(style.statusText());
            pushPanel.add(pushEnabled);
            pushPanel.add(pushText);

            final boolean isRefreshEnabled = dataSetDef.getRefreshTime() != null;
            final FlowPanel refreshPanel = new FlowPanel();
            final com.github.gwtbootstrap.client.ui.Image refreshEnabled = new com.github.gwtbootstrap.client.ui.Image(
                    isRefreshEnabled ? images.okIconSmall() : images.cancelIconSmall());
            final String _refresh = isRefreshEnabled ? DataSetExplorerConstants.INSTANCE.enabled() : DataSetExplorerConstants.INSTANCE.disabled();
            refreshEnabled.setTitle(_refresh);
            refreshEnabled.setAltText(_refresh);
            refreshEnabled.addStyleName(style.statusIcon());
            final HTML refreshText = new HTML(DataSetExplorerConstants.INSTANCE.refresh());
            refreshText.addStyleName(style.statusText());
            refreshPanel.add(refreshEnabled);
            refreshPanel.add(refreshText);

            final FlowPanel statusPanel = new FlowPanel();
            statusPanel.addStyleName(style.statusPanel());
            statusPanel.add(statusText);
            if (cachePanel != null) statusPanel.add(cachePanel);
            statusPanel.add(pushPanel);
            statusPanel.add(refreshPanel);

            // Estimated rows and size.
            final FlowPanel estimationsPanel = new FlowPanel();
            estimationsPanel.addStyleName(style.estimationsPanel());

            // Add current size title.
            final HTML currentSizeText = new HTML(DataSetExplorerConstants.INSTANCE.currentSize());
            currentSizeText.addStyleName(style.statusTextTitle());
            estimationsPanel.add(currentSizeText);

            // Add the loading icon while performing the backend call to fetch metadata.
            final com.github.gwtbootstrap.client.ui.Image loadingIcon = new com.github.gwtbootstrap.client.ui.Image(DataSetClientResources.INSTANCE.images().loadingIcon().getSafeUri());
            loadingIcon.setTitle(DataSetExplorerConstants.INSTANCE.loading());
            loadingIcon.setAltText(DataSetExplorerConstants.INSTANCE.loading());
            estimationsPanel.add(loadingIcon);

            // Perform the backend call to fetch data set metadata.
            callback.getMetadata(dataSetDef, new DataSetMetadataCallback() {

                @Override
                public void callback(DataSetMetadata metadata) {
                    // Clear the loading texxt.
                    estimationsPanel.clear();

                    // Show estimations.
                    final int estimatedSize = metadata.getEstimatedSize();
                    final int rowCount = metadata.getNumberOfRows();

                    // Add current size title.
                    final HTML currentSizeText = new HTML(DataSetExplorerConstants.INSTANCE.currentSize());
                    currentSizeText.addStyleName(style.statusTextTitle());

                    // Add estimation values.
                    final HTML estimatedSizeText = new HTML(humanReadableByteCount(estimatedSize));
                    estimatedSizeText.addStyleName(style.statusText());
                    final HTML estimatedRowsText = new HTML(humanReadableRowCount(rowCount) + WHITESPACE + DataSetExplorerConstants.INSTANCE.rows());
                    estimatedRowsText.addStyleName(style.statusText());

                    // Add into parent container.
                    estimationsPanel.add(currentSizeText);
                    estimationsPanel.add(estimatedRowsText);
                    estimationsPanel.add(estimatedSizeText);
                }

                @Override
                public void notFound() {
                    error();
                    showError(DataSetExplorerConstants.INSTANCE.notFound(), null);
                }

                @Override
                public boolean onError(ClientRuntimeError error) {
                    error();
                    showError(error);
                    return false;
                }

                private void error() {
                    loadingIcon.setUrl(DataSetClientResources.INSTANCE.images().cancelIconSmall().getSafeUri());
                    loadingIcon.setTitle(DataSetExplorerConstants.INSTANCE.error());
                    loadingIcon.setAltText(DataSetExplorerConstants.INSTANCE.error());
                }
            });

            final FlowPanel columnsPanel = new FlowPanel();
            columnsPanel.addStyleName(style.columnsPanel());
            columnsPanel.add(statusPanel);
            columnsPanel.add(estimationsPanel);
            parent.add(columnsPanel);

            // Buttons
            final FlowPanel buttonsPanel = new FlowPanel();

            final com.github.gwtbootstrap.client.ui.Button editButton = new Button(DataSetExplorerConstants.INSTANCE.edit());
            final boolean isPublic = dataSetDef.isPublic();
            editButton.setEnabled(isPublic);
            editButton.addStyleName(style.button());

            editButton.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    fireEvent(new EditDataSetEvent(dataSetDef));
                }
            });

            buttonsPanel.addStyleName(style.buttonsPanel());
            buttonsPanel.add(editButton);
            parent.add(buttonsPanel);
        }
    }

    @Override
    public void showError(final ClientRuntimeError error) {
        showError(error.getMessage(), error.getCause());
    }

    public void showError(final String message, String cause) {
        if (message != null) GWT.log("Error message: " + message);
        if (cause != null) GWT.log("Error cause: " + cause);

        errorMessage.setText(message != null ? message : "");
        errorMessageRow.setVisible(message != null);
        errorCause.setText(cause != null ? cause : "");
        errorCauseRow.setVisible(cause != null);
        errorPanel.show();
    }

    private void hideError() {
        errorPanel.hide();
    }

    public String humanReadableByteCount(long bytes) {
        final String _b = " " + DataSetExplorerConstants.INSTANCE.bytes();
        int unit = 1024;
        if (bytes < unit) return Long.toString(bytes) + _b;
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = ("KMGTPE").charAt(exp-1) + _b;
        return NumberFormat.getFormat(ESTIMATIONS_FORMAT).format(bytes / Math.pow(unit, exp)) + pre;
    }

    public String humanReadableRowCount(long rows) {
        int unit = 1000;
        if (rows < unit) return Long.toString(rows);
        int exp = (int) (Math.log(rows) / Math.log(unit));
        String pre = ("KMGTPE" ).charAt(exp-1) + ("");
        return NumberFormat.getFormat(ESTIMATIONS_FORMAT).format(rows / Math.pow(unit, exp)) + pre;
    }

    // **************** EVENT HANDLER REGISTRATIONS ****************************

    public HandlerRegistration addEditDataSetEventHandler(EditDataSetEventHandler handler)
    {
        return this.addHandler(handler, EditDataSetEvent.TYPE);
    }
}


text:
layout: page
title: Molecular Cell & Dev Biology
comments: true
description: "blank"
keywords: MCDB, CU, Boulder
---

MCDB 1030: Plgue/Peopl/Plnts/Mcrorg

MCDB 1041: Fund Of Human Genetics

MCDB 1111: Biofundamentals

MCDB 1150: Intro/Cell & Molec Biol

MCDB 1151: Intro/Cell Molc Bio Lab

MCDB 1161: Phage Genomics Lab I

MCDB 1171: Drug Discovery Through Hands-On Screens I

MCDB 2150: Principles Of Genetics

MCDB 2151: Principle/Genetics Lab Gt-Sc1

MCDB 2161: Phage Genomics Lab Ii

MCDB 2171: Drug Discovery Through Hands-On Screens 2

MCDB 3010: Undergraduate Teaching In Course-Based Undergraduate Research Experiences

MCDB 3120: Cell Biology

MCDB 3135: Molecular Cell Biology I

MCDB 3140: Cell Biology Laboratory

MCDB 3145: Molecular Cell Biology Ii

MCDB 3150: Biology Of Cancer Cell

MCDB 3160: Pandemic! How The Genomics Revolution Can Save Us All

MCDB 3280: Molecular Cell Physiol

MCDB 3330: Evolution & Creationism

MCDB 3333: Biomedical Innovations And Discoveries

MCDB 3350: Fertil/Steril/Mamm Devel

MCDB 3500: Molecular Biology

MCDB 3650: Brain Thought And Action

MCDB 3651: The Brain: Dysfunction To Disease

MCDB 3700: Poisons In Cell Biology And Society

MCDB 3990: Introduction To Systems Biololgy For Biologists

MCDB 4100: Tpc-Role Sci In Medicine

MCDB 4111: Exp Design And Research

MCDB 4201: From Lab Bench To Bedsde

MCDB 4202: The Python Project

MCDB 4234: Research Methods

MCDB 4300: Immunology

MCDB 4310: Microb Genetics Physiol

MCDB 4312: Quantitative Optical Imaging

MCDB 4350: Microbial Div & Biosph

MCDB 4361: Evolution/Development

MCDB 4410: Human Molecular Genetics

MCDB 4422: Molecular Biology Of Free Radicals: Role(S) In Oxidative Stress, Signaling, Disease, Aging

MCDB 4425: Cellular Stress Response

MCDB 4426: Cell Signaling/Devel Reg

MCDB 4427: Biology Of The Visual System

MCDB 4444: Cellular Basis /Disease

MCDB 4471: Mechanisms Of Gene Regulation In Eukaryotes

MCDB 4501: Structural Methods For Biological Macromolecules

MCDB 4520: Bioinformatics/Genomics

MCDB 4521: Bioinformatics And Genomics Laboratory

MCDB 4550: Biophys Cellular Motion

MCDB 4615: Stem Cells

MCDB 4650: Developmental Biology

MCDB 4660: Developmental Biol Lab

MCDB 4680: Mechanisms Of Aging

MCDB 4750: Animal Virology

MCDB 4777: Molecular Neurobiology

MCDB 4790: Experimental Embryology

MCDB 4810: Insane In The Membrane

MCDB 4811: Teaching Learning Biol

MCDB 4970: Sem/Phys Methods In Biol

MCDB 5210: Cell Structure & Functn

MCDB 5220: Molecular Genetics

MCDB 5230: Gene Expression

MCDB 5250: Tpc-Dev Genetics

MCDB 5650: Teaching And Learning

MCDB 5776: Scientific Conduct

MCDB 6000: Intro To Lab Methods

MCDB 6440: Tpc-Faculty Res Seminar

MCDB 7840: Graduate Independent Study

MCDB 7910: Seminar Practicum


text:
//
//  WDUtilities.m
//  Brushes
//
//  This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
//  Copyright (c) 2008-2013 Steve Sprang
//

#import "NSData+Base64.h"
#import "WDBezierNode.h"
#import "UIDeviceHardware.h"
#import "WDUtilities.h"
#include <CommonCrypto/CommonHMAC.h>
#include <sys/sysctl.h>
#include <OpenGLES/ES2/gl.h>

#define kMiterLimit 10

void HSVtoRGB(float h, float s, float v, float *r, float *g, float *b)
{
    if (s == 0) {
        *r = *g = *b = v;
    } else {
        float   f,p,q,t;
        int     i;

        h *= 360;

        if (h == 360.0f) {
            h = 0.0f;
        }

        h /= 60;
        i = floor(h);

        f = h - i;
        p = v * (1.0 - s);
        q = v * (1.0 - (s*f));
        t = v * (1.0 - (s * (1.0 - f)));

        switch (i) {
            case 0: *r = v; *g = t; *b = p; break;
            case 1: *r = q; *g = v; *b = p; break;
            case 2: *r = p; *g = v; *b = t; break;
            case 3: *r = p; *g = q; *b = v; break;
            case 4: *r = t; *g = p; *b = v; break;
            case 5: *r = v; *g = p; *b = q; break;
        }
    }
}

void RGBtoHSV(float r, float g, float b, float *h, float *s, float *v)
{
    float max = MAX(r, MAX(g, b));
    float min = MIN(r, MIN(g, b));
    float delta = max - min;

    *v = max;
    *s = (max != 0.0f) ? (delta / max) : 0.0f;

    if (*s == 0.0f) {
        *h = 0.0f;
    } else {
        if (r == max) {
            *h = (g - b) / delta;
        } else if (g == max) {
            *h = 2.0f + (b - r) / delta;
        } else if (b == max) {
            *h = 4.0f + (r - g) / delta;
        }

        *h *= 60.0f;

        if (*h < 0.0f) {
            *h += 360.0f;
        }
    }

    *h /= 360.0f;
}

float WDSineCurve(float input)
{
    float result;

    input *= M_PI; // move from [0.0, 1.0] tp [0.0, Pi]
    input -= M_PI_2; // shift back onto a trough

    result = sin(input) + 1; // add 1 to put in range [0.0,2.0]
    result /= 2; // back to [0.0, 1.0];

    return result;
}

void WDDrawCheckersInRect(CGContextRef ctx, CGRect dest, int size)
{
    CGRect  square = CGRectMake(0, 0, size, size);
    float   startx = CGRectGetMinX(dest);
    float   starty = CGRectGetMinY(dest);

    CGContextSaveGState(ctx);
    CGContextClipToRect(ctx, dest);

    [[UIColor colorWithWhite:0.9f alpha:1.0f] set];
    CGContextFillRect(ctx, dest);

    [[UIColor colorWithWhite:0.78f alpha:1.0f] set];
    for (int y = 0; y * size < CGRectGetHeight(dest); y++) {
        for (int x = 0; x * size < CGRectGetWidth(dest); x++) {
            if ((y + x) % 2) {
                square.origin.x = startx + x * size;
                square.origin.y = starty + y * size;
                CGContextFillRect(ctx, square);
            }
        }
    }

    CGContextRestoreGState(ctx);
}

void WDDrawTransparencyDiamondInRect(CGContextRef ctx, CGRect dest)
{
    float   minX = CGRectGetMinX(dest);
    float   maxX = CGRectGetMaxX(dest);
    float   minY = CGRectGetMinY(dest);
    float   maxY = CGRectGetMaxY(dest);

    // preserve the existing color
    CGContextSaveGState(ctx);
        [[UIColor whiteColor] set];
        CGContextFillRect(ctx, dest);

        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, minX, minY);
        CGPathAddLineToPoint(path, NULL, maxX, minY);
        CGPathAddLineToPoint(path, NULL, minX, maxY);
        CGPathCloseSubpath(path);

        [[UIColor blackColor] set];
        CGContextAddPath(ctx, path);
        CGContextFillPath(ctx);
    CGContextRestoreGState(ctx);

    CGPathRelease(path);
}

void WDContextDrawImageToFill(CGContextRef ctx, CGRect bounds, CGImageRef imageRef)
{
    size_t  width = CGImageGetWidth(imageRef);
    size_t  height = CGImageGetHeight(imageRef);
    float   wScale = CGRectGetWidth(bounds) / width;
    float   hScale = CGRectGetHeight(bounds) / height;
    float   scale = MAX(wScale, hScale);
    float   hOffset = 0.0f, vOffset = 0.0f;

    CGRect  rect = CGRectMake(0, 0, width * scale, height * scale);

    if (CGRectGetWidth(rect) > CGRectGetWidth(bounds)) {
        hOffset = CGRectGetWidth(rect) - CGRectGetWidth(bounds);
        hOffset /= -2;
    }

    if (CGRectGetHeight(rect) > CGRectGetHeight(bounds)) {
        vOffset = CGRectGetHeight(rect) - CGRectGetHeight(bounds);
        vOffset /= -2;
    }

    rect = CGRectOffset(rect, hOffset, vOffset);

    CGContextDrawImage(ctx, rect, imageRef);
}

CGSize WDSizeOfRectWithAngle(CGRect rect, float angle, CGPoint *upperLeft, CGPoint *upperRight)
{
    CGPoint center, corners[4];

    center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    CGAffineTransform transform = CGAffineTransformMakeRotation(angle * M_PI / 180.0f);

    corners[0] = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect));
    corners[1] = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect));
    corners[2] = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect));
    corners[3] = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect));

    for (int i = 0; i < 4; i++) {
        corners[i] = CGPointApplyAffineTransform(corners[i], transform);
    }
    center = CGPointApplyAffineTransform(center, transform);

    float minx = corners[0].x;
    float maxx = corners[0].x;
    float miny = corners[0].y;
    float maxy = corners[0].y;

    for (int i = 1; i < 4; i++) {
        minx = MIN(minx, corners[i].x);
        maxx = MAX(maxx, corners[i].x);
        miny = MIN(miny, corners[i].y);
        maxy = MAX(maxy, corners[i].y);
    }

    if (upperLeft) {
        *upperLeft = WDSubtractPoints(corners[0], center);
    }

    if (upperRight) {
        *upperRight = WDSubtractPoints(corners[3], center);
    }

    return CGSizeMake(maxx - minx, maxy - miny);
}

CGPoint WDNormalizePoint(CGPoint vector)
{
    float distance = WDDistance(CGPointZero, vector);

    if (distance == 0.0f) {
        return vector;
    }

    return WDMultiplyPointScalar(vector, 1.0f / WDDistance(CGPointZero, vector));
}

float OSVersion()
{
    static NSInteger  version_ = 0;

    if (version_ == 0) {
        version_ = [[[UIDevice currentDevice] systemVersion] integerValue];
    }

    return version_;
}

BOOL WDUseModernAppearance()
{
    return OSVersion() >= 7 ? YES : NO;
}

CGRect WDGrowRectToPoint(CGRect rect, CGPoint pt)
{
    float minX, minY, maxX, maxY;

    minX = MIN(CGRectGetMinX(rect), pt.x);
    minY = MIN(CGRectGetMinY(rect), pt.y);
    maxX = MAX(CGRectGetMaxX(rect), pt.x);
    maxY = MAX(CGRectGetMaxY(rect), pt.y);

    return CGRectUnion(rect, CGRectMake(minX, minY, maxX - minX, maxY - minY));
}

NSData * WDSHA1DigestForData(NSData *data)
{
    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, NULL, 0, [data bytes], [data length], cHMAC);

    return [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
}

CGPoint WDSharpPointInContext(CGPoint pt, CGContextRef ctx)
{
    pt = CGContextConvertPointToDeviceSpace(ctx, pt);
    pt = WDFloorPoint(pt);
    pt = WDAddPoints(pt, CGPointMake(0.5f, 0.5f));
    pt = CGContextConvertPointToUserSpace(ctx, pt);

    return pt;
}

CGPoint WDConstrainPoint(CGPoint delta)
{
    float   angle = atan2(delta.y, delta.x);
    float   magnitude = WDDistance(delta, CGPointZero);

    angle = roundf(angle / M_PI_4) * M_PI_4;
    delta.x = cos(angle) * magnitude;
    delta.y = sin(angle) * magnitude;

    return delta;
}

CGRect WDRectFromPoint(CGPoint a, float width, float height)
{
    return CGRectMake(a.x - (width / 2), a.y - (height / 2), width, height);
}

void convertQuadraticPathElement(void *info, const CGPathElement *element)
{
    CGMutablePathRef    converted = (CGMutablePathRef) info;
    CGPoint             prev;

    switch (element->type) {
        case kCGPathElementMoveToPoint:
            CGPathMoveToPoint(converted, NULL, element->points[0].x, element->points[0].y);
            break;
        case kCGPathElementAddLineToPoint:
            CGPathAddLineToPoint(converted, NULL, element->points[0].x, element->points[0].y);
            break;
        case kCGPathElementAddQuadCurveToPoint:
            prev = CGPathGetCurrentPoint(converted);

            // convert quadratic to cubic: http://fontforge.sourceforge.net/bezier.html
            CGPoint outPoint = WDAddPoints(prev, WDMultiplyPointScalar(WDSubtractPoints(element->points[0], prev), 2.0f / 3));
            CGPoint inPoint = WDAddPoints(element->points[1], WDMultiplyPointScalar(WDSubtractPoints(element->points[0], element->points[1]), 2.0f / 3));

            CGPathAddCurveToPoint(converted, NULL, outPoint.x, outPoint.y, inPoint.x, inPoint.y, element->points[1].x, element->points[1].y);
            break;
        case kCGPathElementAddCurveToPoint:
            CGPathAddCurveToPoint(converted, NULL, element->points[0].x, element->points[0].y, element->points[1].x, element->points[1].y, element->points[2].x, element->points[2].y);
            break;
        case kCGPathElementCloseSubpath:
            CGPathCloseSubpath(converted);
            break;

    }
}

CGPathRef WDConvertPathQuadraticToCubic(CGPathRef pathRef)
{
    CGMutablePathRef converted = CGPathCreateMutable();

    CGPathApply(pathRef, converted, &convertQuadraticPathElement);

    return converted;
}

BOOL WDCollinear(CGPoint a, CGPoint b, CGPoint c)
{
    float distances[3];

    distances[0] = WDDistance(a, b);
    distances[1] = WDDistance(b, c);
    distances[2] = WDDistance(a, c);

    if (distances[0] > distances[1]) {
        float temp = distances[1];
        distances[1] = distances[0];
        distances[0] = temp;
    }

    if (distances[1] > distances[2]) {
        float temp = distances[2];
        distances[2] = distances[1];
        distances[1] = temp;
    }

    float difference = (fabs((distances[0] + distances[1]) - distances[2]));

    return (difference < 0.0001f) ? YES : NO;
}

BOOL WDLineInRect(CGPoint a, CGPoint b, CGRect test)
{
    int			acode = 0, bcode = 0;
    float		ymin, ymax, xmin, xmax;
    int         TOP = 0x1, BOTTOM = 0x2, RIGHT = 0x4, LEFT = 0x8;

    xmin = CGRectGetMinX(test);
    ymin = CGRectGetMinY(test);
    xmax = CGRectGetMaxX(test);
    ymax = CGRectGetMaxY(test);

    if(a.y > ymax) {
        acode |= TOP;
    } else if(a.y < ymin) {
        acode |= BOTTOM;
    }

    if(a.x > xmax) {
        acode |= RIGHT;
    } else if(a.x < xmin) {
        acode |= LEFT;
    }

    if(b.y > ymax) {
        bcode |= TOP;
    } else if(b.y < ymin) {
        bcode |= BOTTOM;
    }

    if(b.x > xmax) {
        bcode |= RIGHT;
    } else if(b.x < xmin) {
        bcode |= LEFT;
    }

    if(acode == 0 || bcode == 0) { // one or both endpoints within rect
        return YES;
    } else if(acode & bcode) { // completely outside of rectangle
        return NO;
    } else { // special case
        CGPoint		middle;
        // split line and test each half recursively
        middle.x = (a.x + b.x) / 2.0f;
        middle.y = (a.y + b.y) / 2.0f;

        if (WDLineInRect(a, middle, test)) {
            return YES;
        }

        if (WDLineInRect(middle, b, test)) {
            return YES;
        }
        return NO;
    }
}

typedef struct {
    CGMutablePathRef mutablePath;
    CGAffineTransform transform;
} WDPathAndTransform;

void transformPathElement(void *info, const CGPathElement *element)
{
    WDPathAndTransform  pathAndTransform = *((WDPathAndTransform *) info);
    CGAffineTransform   transform = pathAndTransform.transform;
    CGMutablePathRef    pathRef = pathAndTransform.mutablePath;

    switch (element->type) {
        case kCGPathElementMoveToPoint:
            CGPathMoveToPoint(pathRef, &transform, element->points[0].x, element->points[0].y);
            break;
        case kCGPathElementAddLineToPoint:
            CGPathAddLineToPoint(pathRef, &transform, element->points[0].x, element->points[0].y);
            break;
        case kCGPathElementAddQuadCurveToPoint:
            CGPathAddQuadCurveToPoint(pathRef, &transform, element->points[0].x, element->points[0].y, element->points[1].x, element->points[1].y);
            break;
        case kCGPathElementAddCurveToPoint:
            CGPathAddCurveToPoint(pathRef, &transform, element->points[0].x, element->points[0].y, element->points[1].x, element->points[1].y, element->points[2].x, element->points[2].y);
            break;
        case kCGPathElementCloseSubpath:
            CGPathCloseSubpath(pathRef);
            break;

    }
}

CGPathRef WDTransformCGPathRef(CGPathRef pathRef, CGAffineTransform transform)
{
    CGMutablePathRef    transformedPath = CGPathCreateMutable();
    WDPathAndTransform  pathAndTransform = {transformedPath, transform};

    CGPathApply(pathRef, &pathAndTransform, &transformPathElement);

    return transformedPath;
}

BOOL WDLineSegmentsIntersectWithValues(CGPoint A, CGPoint B, CGPoint C, CGPoint D, float *rV, float *sV)
{
    float denom = (B.x - A.x) * (D.y - C.y) - (B.y - A.y) * (D.x - C.x);

    if (denom == 0) {
        return NO;
    }

    float r = (A.y - C.y) * (D.x - C.x) - (A.x - C.x) * (D.y - C.y);
    r /= denom;

    float s = (A.y - C.y) * (B.x - A.x) - (A.x - C.x) * (B.y - A.y);
    s /= denom;

    if (rV) {
        *rV = r;
    }

    if (sV) {
        *sV = s;
    }

    return (r < 0 || r > 1 || s < 0 || s > 1) ? NO : YES;;
}

BOOL WDLineSegmentsIntersect(CGPoint A, CGPoint B, CGPoint C, CGPoint D)
{
    return WDLineSegmentsIntersectWithValues(A, B, C, D, NULL, NULL);
}

CGRect WDShrinkRect(CGRect rect, float percentage)
{
    float   widthInset = CGRectGetWidth(rect) * percentage;
    float   heightInset = CGRectGetHeight(rect) * percentage;

    return CGRectInset(rect, widthInset, heightInset);
}

CGAffineTransform WDTransformForOrientation(UIInterfaceOrientation orientation)
{
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (orientation) {
        case UIInterfaceOrientationUnknown:
        case UIInterfaceOrientationPortrait:
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIInterfaceOrientationLandscapeLeft:
            transform = CGAffineTransformRotate(transform, M_PI / -2);
            break;
        case UIInterfaceOrientationLandscapeRight:
            transform = CGAffineTransformRotate(transform, M_PI / 2);
            break;
    }

    return transform;
}

float WDRandomFloat()
{
    float r = random() % 10000;
    return r / 10000.0f;
}

int WDRandomIntInRange(int min, int max)
{
    return min + WDRandomFloat() * (max - min);
}

float WDRandomFloatInRange(float min, float max)
{
    return min + WDRandomFloat() * (max - min);
}

CGRect WDUnionRect(CGRect a, CGRect b)
{
    if (CGRectEqualToRect(a, CGRectZero)) {
        return b;
    } else if (CGRectEqualToRect(b, CGRectZero)) {
        return a;
    }

    return CGRectUnion(a, b);
}

/******************************
 * WDQuad
 *****************************/

WDQuad WDQuadNull()
{
    CGPoint bogusPoint = CGPointMake(INFINITY, INFINITY);
    return WDQuadMake(bogusPoint, bogusPoint, bogusPoint, bogusPoint);
}

WDQuad WDQuadMake(CGPoint a, CGPoint b, CGPoint c, CGPoint d)
{
    WDQuad quad;

    quad.corners[0] = a;
    quad.corners[1] = b;
    quad.corners[2] = c;
    quad.corners[3] = d;

    return quad;
}

WDQuad WDQuadWithRect(CGRect rect, CGAffineTransform transform)
{
    WDQuad quad;

    quad.corners[0] = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect));
    quad.corners[1] = CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect));
    quad.corners[2] = CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect));
    quad.corners[3] = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect));

    for (int i = 0; i < 4; i++) {
        quad.corners[i] = CGPointApplyAffineTransform(quad.corners[i], transform);
    }

    return quad;
}

BOOL WDQuadEqualToQuad(WDQuad a, WDQuad b)
{
    for (int i = 0; i < 4; i++) {
        if (!CGPointEqualToPoint(a.corners[i], b.corners[i])) {
            return NO;
        }
    }

    return YES;
}

BOOL WDQuadIntersectsQuad(WDQuad a, WDQuad b)
{
    WDQuad nullQuad = WDQuadNull();
    if (WDQuadEqualToQuad(a, nullQuad) || WDQuadEqualToQuad(b, nullQuad)) {
        return NO;
    }

    for (int i = 0; i < 4; i++) {
        for (int n = 0; n < 4; n++) {
            if (WDLineSegmentsIntersect(a.corners[i], a.corners[(i+1)%4], b.corners[n], b.corners[(n+1)%4])) {
                return YES;
            }
        }
    }

    return NO;
}

NSString * NSStringFromWDQuad(WDQuad quad)
{
    return [NSString stringWithFormat:@"{{%@}, {%@}, {%@}, {%@}}", NSStringFromCGPoint(quad.corners[0]), NSStringFromCGPoint(quad.corners[1]),
            NSStringFromCGPoint(quad.corners[2]), NSStringFromCGPoint(quad.corners[3])];
}

CGPathRef WDQuadCreatePathRef(WDQuad q)
{
    CGMutablePathRef pathRef = CGPathCreateMutable();

    CGPathMoveToPoint(pathRef, NULL, q.corners[0].x, q.corners[0].y);
    for (int i = 1; i < 4; i++) {
        CGPathAddLineToPoint(pathRef, NULL, q.corners[i].x, q.corners[i].y);
    }
    CGPathCloseSubpath(pathRef);

    return pathRef;
}

void WDCheckGLError_(const char* file, int line) {
    GLenum error = glGetError();
    if (error) {
        NSString *message;
        switch (error) {
            case GL_INVALID_ENUM: message = @"invalid enum"; break;
            case GL_INVALID_FRAMEBUFFER_OPERATION: message = @"invalid framebuffer operation"; break;
            case GL_INVALID_OPERATION: message = @"invalid operation"; break;
            case GL_INVALID_VALUE: message = @"invalid value"; break;
            case GL_OUT_OF_MEMORY: message = @"out of memory"; break;
            default: message = [NSString stringWithFormat:@"unknown error: 0x%x", error];
        }
        WDLog(@"ERROR: glGetError returned: %@ at %s:%d", message, file, line);
    }
}

#ifdef WD_DEBUG

static NSMutableArray *timings_ = nil;

void WDBeginTiming()
{
    if (!timings_) {
        timings_ = [[NSMutableArray alloc] init];
    }

    [timings_ addObject:[NSDate date]];
}

void WDLogTiming(NSString *message)
{
    if (!timings_ || timings_.count == 0) {
        NSLog(@"WDLogTiming() Error: unbalanced calls.");
        return;
    }

    NSDate *date = (NSDate *) [timings_ lastObject];

    if (message) {
        NSLog(@"%@ in %gs", message, -[date timeIntervalSinceNow]);
    } else {
        NSLog(@"%gs", -[date timeIntervalSinceNow]);
    }
}

void WDEndTiming(NSString *message)
{
    if (!timings_ || timings_.count == 0) {
        NSLog(@"WDEndTiming() Error: unbalanced calls.");
        return;
    }

    WDLogTiming(message);
    [timings_ removeLastObject];
}

#endif

NSString *generateUUID()
{
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
    NSData *data = [NSData dataWithBytes:&bytes length:16];
    // only 22 digits are required to encode 128 bits; the last two characters are always "=="
    // replace "/" with "-" to make it safe for filenames
    NSString *uuidString = [[[data base64EncodedString] substringToIndex:22] stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    CFRelease(uuid);
    return uuidString;
}

BOOL WDDeviceIsPhone()
{
    static BOOL isPhone;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        isPhone = [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone ? YES : NO;
    });

    return isPhone;
}

BOOL WDDeviceIs4InchPhone()
{
    return (WDDeviceIsPhone() && [UIScreen mainScreen].bounds.size.height == 568) ? YES : NO;
}

BOOL WDCanUseScissorTest()
{
    static BOOL canScissor;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSString *reqSysVer = @"6.0";
        NSString *currSysVer = [[UIDevice currentDevice] systemVersion];

        if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
            canScissor = YES;
        } else {
            // on iOS 5 we can only scissor if both screen dimensions are less than 1536
            CGSize size = WDMultiplySizeScalar([UIScreen mainScreen].bounds.size, [UIScreen mainScreen].scale);
            canScissor = (size.width > 1536 || size.height > 1536) ? NO : YES;
        }
    });

    return canScissor;
}

size_t WDGetTotalMemory()
{
    int mib[] = { CTL_HW, HW_PHYSMEM };
    size_t mem;
    size_t len = sizeof(mem);
    sysctl(mib, 2, &mem, &len, NULL, 0);
    return mem;
}

BOOL WDCanUseHDTextures()
{
#if TARGET_IPHONE_SIMULATOR
    return YES;
#else
    static BOOL canUseHDTextures_;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSString    *device = [[UIDeviceHardware platform] componentsSeparatedByString:@","][0];
        NSScanner   *scanner = [NSScanner scannerWithString:device];
        NSString    *model = nil;
        int         version = 0;

        [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&model];
        [scanner scanInt:&version];

        if ([model isEqualToString:@"iPhone"]) {
            canUseHDTextures_ = (version >= 4) ? YES : NO;
        } else if ([model isEqualToString:@"iPod"]) {
            canUseHDTextures_ = (version >= 5) ? YES : NO;
        } else if ([model isEqualToString:@"iPad"]) {
            canUseHDTextures_ = (version >= 2) ? YES : NO;
        }
    });

    return canUseHDTextures_;
#endif
}


text:
"""
This module is deprecated. Please use `airflow.providers.google.cloud.operators.cloud_sql`.
"""

import warnings

from airflow.providers.google.cloud.operators.cloud_sql import (
    CloudSQLBaseOperator, CloudSQLCreateInstanceDatabaseOperator, CloudSQLCreateInstanceOperator,
    CloudSQLDeleteInstanceDatabaseOperator, CloudSQLDeleteInstanceOperator, CloudSQLExecuteQueryOperator,
    CloudSQLExportInstanceOperator, CloudSQLImportInstanceOperator, CloudSQLInstancePatchOperator,
    CloudSQLPatchInstanceDatabaseOperator,
)

warnings.warn(
    "This module is deprecated. Please use `airflow.providers.google.cloud.operators.cloud_sql`",
    DeprecationWarning, stacklevel=2
)

class CloudSqlBaseOperator(CloudSQLBaseOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql.CloudSQLBaseOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceCreateOperator(CloudSQLCreateInstanceOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLCreateInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceDatabaseCreateOperator(CloudSQLCreateInstanceDatabaseOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLCreateInstanceDatabaseOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceDatabaseDeleteOperator(CloudSQLDeleteInstanceDatabaseOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLDeleteInstanceDatabaseOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceDatabasePatchOperator(CloudSQLPatchInstanceDatabaseOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLPatchInstanceDatabaseOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceDeleteOperator(CloudSQLDeleteInstanceOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLDeleteInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceExportOperator(CloudSQLExportInstanceOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLExportInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstanceImportOperator(CloudSQLImportInstanceOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators.sql
    .CloudSQLImportInstanceOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlInstancePatchOperator(CloudSQLInstancePatchOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators
    .sql.CloudSQLInstancePatchOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)

class CloudSqlQueryOperator(CloudSQLExecuteQueryOperator):
    """
    This class is deprecated. Please use `airflow.providers.google.cloud.operators
    .sql.CloudSQLExecuteQueryOperator`.
    """

    def __init__(self, *args, **kwargs):
        warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
        super().__init__(*args, **kwargs)


text:
from __future__ import absolute_import

import six
from rest_framework.response import Response

from sentry import eventstore
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.fields.actor import Actor
from sentry.api.serializers import serialize
from sentry.api.serializers.models.actor import ActorSerializer
from sentry.models import ProjectOwnership, Team

class EventOwnersEndpoint(ProjectEndpoint):
    def get(self, request, project, event_id):
        """
        Retrieve suggested owners information for an event
        ``````````````````````````````````````````````````

        :pparam string project_slug: the slug of the project the event
                                     belongs to.
        :pparam string event_id: the id of the event.
        :auth: required
        """
        event = eventstore.get_event_by_id(project.id, event_id)
        if event is None:
            return Response({"detail": "Event not found"}, status=404)

        owners, rules = ProjectOwnership.get_owners(project.id, event.data)

        # For sake of the API, we don't differentiate between
        # the implicit "everyone" and no owners
        if owners == ProjectOwnership.Everyone:
            owners = []

        serialized_owners = serialize(Actor.resolve_many(owners), request.user, ActorSerializer())

        # Make sure the serialized owners are in the correct order
        ordered_owners = []
        owner_by_id = {(o["id"], o["type"]): o for o in serialized_owners}
        for o in owners:
            key = (six.text_type(o.id), "team" if o.type == Team else "user")
            if owner_by_id.get(key):
                ordered_owners.append(owner_by_id[key])

        return Response(
            {
                "owners": ordered_owners,
                # TODO(mattrobenolt): We need to change the API here to return
                # all rules, just keeping this way currently for API compat
                "rule": rules[0].matcher if rules else None,
                "rules": rules or [],
            }
        )


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ 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.
  -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:theme="@style/Pointsgray"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:theme="@style/Pointsgray">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="70dp"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/Pointsgray" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="50dp" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

        <!--<LinearLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="149dp"-->
        <!--android:gravity="center_horizontal">-->
        <!--<TextView-->
        <!--android:id="@+id/point_count"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_marginTop="50dp"-->
        <!--android:text="256"-->
        <!--android:textColor="@color/points_color"-->
        <!--android:layout_gravity="center"-->
        <!--android:textSize="55dp" />-->

        <!--<TextView-->
        <!--android:id="@+id/points"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:text="points"-->
        <!--android:textColor="@color/button_grey"-->
        <!--android:layout_marginTop="57dp"-->
        <!--android:layout_marginLeft="10dp"-->
        <!--android:layout_gravity="center"-->
        <!--android:textSize="30dp" />-->

        <!--</LinearLayout>-->

        <!--<LinearLayout-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent">-->
        <!--<TextView-->
        <!--android:id="@+id/rewards"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:text="Rewards"-->

        <!--android:layout_marginLeft="18dp"-->
        <!--android:layout_marginTop="160dp"-->
        <!--android:textSize="30dp" />-->
        <!--</LinearLayout>-->

        </android.support.design.widget.CoordinatorLayout>

     <ScrollView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content">

     </ScrollView>

</android.support.v4.widget.DrawerLayout>


text:
class ComponentMaterial;

class ComponentUiButton : public Component
{
public:

	ComponentUiButton(ComponentType type, GameObject* game_object);
	~ComponentUiButton();

	void Update();
	void CleanUp();

	void OnInspector(bool debug);
	void OnFocus();
	void OnPress();
	void OnPressId(int i);
	void ChangeState();

	// Save
	void Save(Data& file)const;
	void Load(Data& conf);
	void Reset();
	void ResetId(int i);

	bool GetState() const;

public:
	ComponentMaterial* UImaterial = nullptr;
private:

	bool pressed = false;
};

#endif __COMPONENTUIBUTTON_H__


text:
package util.ma;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class YiMa {

	public static void main(String[] args) {
		login("xiaomin0322","");
		// String str = Ma60.getnum("BA4E0F33A9F5952");

		 //System.out.println(str);
		 //resleNum();

	}

	public static void execute(){
		//login();

		for(;;){
			try{
				getnum();
				getmsg();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				resleNum();
			}
		}

	}

	static String userId = "";

	static String userKey = "";

	static String telnum = "";

	static String token = "";
	//项目编号
	static String itemid = "";
    //排除号段
	static String excludeno="";

	public static boolean login(String uname,String password) {
		String url = "http://api.fxhyd.cn/UserInterface.aspx?action=login&username="+uname+"&password="+password;
		HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
		HttpResponse response = httpRequest.send();
		// response.accept("utf-8");
		// response.acceptEncoding("utf-8");
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);
        if(rc.contains( "success")) {
        	System.out.println("登陆成功>>>>>>>");
        	token = rc.split("\\|")[1];
        	return true;
        }
        return false;
	}

	/**
	 * 获取手机号码
	 *
	 * @return
	 */
	public static String getnum() {
		String url = "http://api.fxhyd.cn/UserInterface.aspx?action=getmobile&token="+token+"&itemid="+itemid+"&excludeno="+excludeno;
		HttpRequest httpRequest = HttpRequest.get(url).timeout(20000);
		HttpResponse response = httpRequest.send();
		// response.accept("utf-8");
		// response.acceptEncoding("utf-8");
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);

		 if(rc.contains( "success")) {
	        	telnum = rc.split("\\|")[1];
	        	return telnum;
	    }
		return telnum;
	}

	/**
	 * 获取手机号码
	 *
	 * @return
	 */
	public static String getnum(String docks) {
		String url = "http://sms.60ma.net/newsmssrv?cmd=gettelnum&encode=utf-8&dtype=json&docks="+docks+"&userid="
				+ userId
				+ "&userkey="
				+ userKey
				+ "&province=0&city=0&operator=0"
				+ "&telback=17";
		HttpRequest httpRequest = HttpRequest.get(url).timeout(20000);
		HttpResponse response = httpRequest.send();
		// response.accept("utf-8");
		// response.acceptEncoding("utf-8");
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);

		JSONObject jsonObject = JSON.parseObject(rc);
		jsonObject = jsonObject.getJSONObject("Return");

		String staus = jsonObject.getString("Staus");
		if ("0".equals(staus)) {
			System.out.println("获取手机号码成功");
			telnum = jsonObject.getString("Telnum");
		}else if(jsonObject.toJSONString().contains("余额不足")){
			System.out.println(jsonObject.toString()+" >>>>> 退出程序");
			System.exit(0);
		}
		return telnum;
	}

	/**
	 * 获取短信
	 *
	 * @return
	 */
	public static String getmsg() {
		String url = "http://api.fxhyd.cn/UserInterface.aspx?action=getsms&token="+token+"&itemid="+itemid+"&mobile="+telnum+"&release=1";
		HttpRequest httpRequest = HttpRequest.get(url).timeout(20000);
		HttpResponse response = httpRequest.send();
		// response.accept("utf-8");
		// response.acceptEncoding("utf-8");
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);
		 if(rc.contains( "success")) {
	        	return rc.split("\\|")[1];
	    }
		return "";
	}

	/**
	 * 获取短信
	 *
	 * @return
	 */
	public static String getmsg(String dockcode,String num) {
		String url = "http://sms.60ma.net/newsmssrv?cmd=getsms&dtype=json&encode=utf-8&userid="
				+ userId
				+ "&userkey="
				+ userKey
				+ "&dockcode="+dockcode+"&telnum="
				+ num;
		HttpRequest httpRequest = HttpRequest.get(url).timeout(20000);
		HttpResponse response = httpRequest.send();
		// response.accept("utf-8");
		// response.acceptEncoding("utf-8");
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);
		JSONObject jsonObject = JSON.parseObject(rc);
		jsonObject = jsonObject.getJSONObject("Return");

		String staus = jsonObject.getString("Staus");
		if ("0".equals(staus)) {
			System.out.println("获取短信成功");
			String SmsContent = jsonObject.getString("SmsContent");
			System.out.println(SmsContent);
			return SmsContent;
		}

		return "";
	}

	// 释放所有号码
	public static void resleNum() {
         System.out.println("释放所有号码");
		String url = "http://sms.60ma.net/newsmssrv?cmd=freetelnumall&dtype=json&encode=utf-8&userid="
				+ userId + "&userkey=" + userKey;
		HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
		HttpResponse response = httpRequest.send();
		response.charset("utf-8");
		String rc = response.bodyText();
		System.out.println(rc);

	}

	// 释号码
		public static void resleNum(String num) {
	         System.out.println("释放号码"+num);
			String url = "http://api.fxhyd.cn/UserInterface.aspx?action=release&token="+token+"&itemid="+itemid+"&mobile="+num;
			HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
			HttpResponse response = httpRequest.send();
			response.charset("utf-8");
			String rc = response.bodyText();
			System.out.println(rc);
			 if(rc.contains( "success")) {
		        	System.out.println("释放手机号码成功");
		    }

		}

		// 释号码
		public static void resleNum(String docks,String num) {
	         System.out.println("释放号码"+num);
			String url = "http://sms.60ma.net/newsmssrv?cmd=freetelnum&encode=utf-8&docks="+docks+"&userid="
					+ userId + "&userkey=" + userKey+"&telnum="+num;
			HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
			HttpResponse response = httpRequest.send();
			response.charset("utf-8");
			String rc = response.bodyText();
			System.out.println(rc);

		}

	// 释放所有号码
		public static void jiaheiNum() {
	         System.out.println("加入黑号");
			String url = "http://sms.60ma.net/newsmssrv?cmd=addblacktelnum&encode=utf-8&docks=10692408025D0DB&userid="+userId+"&userkey="+userKey+"&telnum="+telnum;
			HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
			HttpResponse response = httpRequest.send();
			response.charset("utf-8");
			String rc = response.bodyText();
			System.out.println(rc);

		}

		// 释放所有号码
				public static void jiaheiNum(String docks,String num) {
			         System.out.println("加入黑号");
					String url = "http://sms.60ma.net/newsmssrv?cmd=addblacktelnum&encode=utf-8&docks="+docks+"&userid="+userId+"&userkey="+userKey+"&telnum="+num;
					HttpRequest httpRequest = HttpRequest.get(url).timeout(10000);
					HttpResponse response = httpRequest.send();
					response.charset("utf-8");
					String rc = response.bodyText();
					System.out.println(rc);

				}

}


text:
#pragma once

#include "security-manager-types.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \brief This function is responsible for initializing policy_update_req data structure.
 *
 * It uses dynamic allocation inside and user responsibility is to call
 * policy_update_req_free() for freeing allocated resources.
 *
 * \param[out] pp_req Address of pointer for handle policy_update_req structure
 * \return API return code or error code
 */
int security_manager_policy_update_req_new(policy_update_req **pp_req);

/**
 * \brief This function is used to free resources allocated by calling policy_update_req_new().
 * \param[in] p_req Pointer handling allocated policy_update_req structure
 */
void security_manager_policy_update_req_free(policy_update_req *p_req);

/**
 * \brief This function is responsible for initializing policy_entry data structure.
 *
 * It uses dynamic allocation inside and user responsibility is to call
 * policy_policy_entry_free() for freeing allocated resources.
 *
 * \note application and privilege fields default to SECURITY_MANAGER_ANY wildcard,
 *       user field defaults to calling user's UID, whereas the current and max level
 *       values, default to empty string "".
 *
 * \param[out] pp_entry Address of pointer for handle policy_entry structure
 * \return API return code or error code
 */
int security_manager_policy_entry_new(policy_entry **pp_entry);

/**
 * \brief This function is used to free resources allocated by calling
 * policy_entry_req_new().
 * \param[in] p_entry Pointer handling allocated policy_entry structure
 */
void security_manager_policy_entry_free(policy_entry *p_entry);

/**
 * This function is used to set up application identifier in p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \param[in] app_id Application identifier to be set
 * \return API return code or error code
 */
int security_manager_policy_entry_set_application(policy_entry *p_entry, const char *app_id);

/**
 * This function is used to set up user identifier in p_entry structure
 * Calling this function may be omitted if user wants to set policies for himself
 * \param[in] p_entry Pointer handling policy_entry structure
 * \param[in] user_id User identifier to be set
 * \return API return code or error code
 */
int security_manager_policy_entry_set_user(policy_entry *p_entry, const char *user_id);

/**
 * This function is used to set up privilege in p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \param[in] privilege Privilege to be set
 * \return API return code or error code
 */
int security_manager_policy_entry_set_privilege(policy_entry *p_entry, const char *privilege);

/**
 * This function is used to set up privilege level in p_entry structure.
 * This api is intended to be used to decrease user's own level of privilege.
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \param[in] policy_level Policy level to be set. The level of privilege may
 * be one of strings returned by @ref security_manager_policy_levels_get.
 * If it is not, then error code SECURITY_MANAGER_ERROR_INPUT_PARAM is returned.
 * Two predefined values are always valid here:
 *
 * "Allow", which means that user allows some app (setup by calling function
 * @ref security_manager_policy_entry_set_application) to run with some privilege
 * (setup by @ref security_manager_policy_entry_set_privilege).
 * Note, that this not necessarily mean, that this privilege will really be granted.
 * Final decision of granting privilege also depends on app's manifests,
 * predefined policy and administrator's or manufacturer's settings.
 * If all of those policy sources also allows granting privilege for that app,
 *  then (and only then) it will be granted.
 *
 * "Deny", which means that user disallows some app (setup by calling function
 * @ref security_manager_policy_entry_set_application) to run with some privilege
 * (setup by @ref security_manager_policy_entry_set_privilege).
 * Note, that this denies privilege irrespective of privilege levels granted
 * to app by other policy sources: app's manifests, predefined policy
 * and administrator's or manufacturer's settings.
 *
 * Other levels may be also valid, if returned by security_manager_policy_levels_get.
 * They represent other policy levels configured in system, which security-manager
 * does support. The other levels are always something between "Allow" and "Deny"
 * (like "Allow only once").
 *
 * Irrespective of a meaning of those values security-manager will always treat
 * policy set by security_manager_policy_entry_set_level as a mean to
 * decrease user's own rights. This will never increase overall policy.
 *
 * \return API return code or error code
 */
int security_manager_policy_entry_set_level(policy_entry *p_entry, const char *policy_level);

/**
 * This function is used to set up privilege level for admin policy entries
 * in p_entry structure.
 *
 * This function is intended to be used by admin to change level of privilege.
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \param[in] policy_level Policy level to be set. This may be one of strings
 * returned by @ref security_manager_policy_levels_get. If it is not, then error
 * code is returned (SECURITY_MANAGER_ERROR_INPUT_PARAM).
 * Two predefined values are always valid here:
 *
 * "Allow", which means that admin allows some user's app to
 * get privilege irrespective of predefined policy settings for that user.
 * Note, that this not necessarily mean, that this privilege will really be granted.
 * Final decision of granting privilege also depends on app's manifests,
 * user's own policy (set up by @ref security_manager_policy_entry_set_level)
 * or manufacturer's settings.
 * If all of those policy sources also allows granting privilege for that app,
 * then (and only then) it will be granted.
 *
 * "Deny", which means that admin disallows some user's app to get privilege
 * irrespective of predefined policy settings for that user.
 * Note, that this denies privilege app's manifests, user's own policy
 * (set up by @ref security_manager_policy_entry_set_level) or manufacturer's
 * settings.
 *
 * Other levels may be also valid, if returned by security_manager_policy_levels_get.
 * They represent other policy levels configured in system, which security-manager
 * does support. The other levels are always something between "Allow" and "Deny"
 * (like "Allow only once").
 *
 * Irrespective of a meaning of those values security-manager will always treat
 * policy set by security_manager_policy_entry_admin_set_level as a mean for admin
 * to change user's rights, but will not alter user's own privilege level set up
 * by @ref security_manager_policy_entry_set_level.
 *
 * \return API return code or error code
 */
int security_manager_policy_entry_admin_set_level(policy_entry *p_entry, const char *policy_level);

/**
 * This function is used to add policy entry to policy update request.
 *
 * Note, that this function does not make a copy of object pointed to by p_entry
 * and does not change owner of this handler.
 * User is responsible to keep p_entry untouched until @ref security_manager_policy_update_send
 * is called on p_req. After that p_entry still needs to be freed.
 * (see examples in documentation of @ref security_manager_policy_update_send)
 *
 * \param[in] p_req Pointer handling allocated policy_update_req structure
 * \param[in] p_entry Pointer handling policy_entry structure
 * \return API return code or error code
 */
int security_manager_policy_update_req_add_entry(policy_update_req *p_req, const policy_entry *p_entry);

/**
 * This function is used to obtain user ID from p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \attention Warning: returned pointer to user ID is valid as long as p_entry is valid.
 *
 * \return user uid
 */

const char *security_manager_policy_entry_get_user(policy_entry *p_entry);
/**
 * This function is used to obtain application name from p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \attention Warning: returned pointer to application name is valid as long as p_entry is valid.
 *
 * \return application name
 */

const char *security_manager_policy_entry_get_application(policy_entry *p_entry);
/**
 * This function is used to obtain privilege name from p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \attention Warning: returned pointer to privilege name is valid as long as p_entry is valid.
 *
 * \return privilege name
 */
const char *security_manager_policy_entry_get_privilege(policy_entry *p_entry);
/**
 * This function is used to obtain current policy level from p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure
 * \attention Warning: returned pointer to policy level is valid as long as p_entry is valid.
 *
 * \return Current policy level
 */
const char *security_manager_policy_entry_get_level(policy_entry *p_entry);

/**
 * This function is used to obtain maximal policy level from p_entry structure
 *
 * \param[in] p_entry Pointer handling policy_entry structure.
 * \attention Warning: returned pointer to maximal policy level is valid as long as p_entry is valid.
 *
 * \return Maximal policy level
 */
const char *security_manager_policy_entry_get_max_level(policy_entry *p_entry);

/**
 * \brief This function is used to send the prepared policy update request using privacy manager
 *        entry point. The request should contain at least one policy update unit, otherwise
 *        the SECURITY_MANAGER_ERROR_INPUT_PARAM is returned.
 *
 * \note  1. If user field in policy_entry is empty, then uid of the calling user is assumed
 *        2. If privilege or app field in policy_entry is empty, then SECURITY_MANAGER_API_BAD_REQUEST
 *           is returned
 *        3. For user's personal policy: wildcards usage in application or privilege field of policy_entry
 *           is not allowed
 *
 * Required privileges:
 * - http://tizen.org/privilege/notexist (for setting own policy)
 * - http://tizen.org/privilege/internal/usermanagement (for setting policy for other or all)
 *
 * \param[in] p_req Pointer handling allocated policy_update_req structure
 * \return API return code or error code
 *
 * Example:
 * (warning: checking return codes are omitted in examples just for visibility reasons)
 *
 * - to update policy for user by himself:
 *   (Deny access from app MyApp1 to privilege http://tizen.org/privilege/systemsettings,
 *   deny access from app MyApp2 to privilege http://tizen.org/privilege/systemsettings,
 *   deny access from app MyApp3 to privilege http://tizen.org/privilege/notificationmanager)
 *
 * \parblock
 * \code{.c}
 *      policy_update_req *policy_update_request;
 *      policy_entry *entry1;
 *      policy_entry *entry2;
 *      policy_entry *entry3;
 *
 *      security_manager_policy_update_req_new(&policy_update_request);
 *      security_manager_policy_entry_new(&entry1);
 *      security_manager_policy_entry_new(&entry2);
 *      security_manager_policy_entry_new(&entry3);
 *
 *      security_manager_policy_entry_set_application(entry1, "MyApp1");
 *      security_manager_policy_entry_set_privilege(entry1, "http://tizen.org/privilege/systemsettings");
 *      security_manager_policy_entry_set_level(entry1, "Deny");
 *
 *      security_manager_policy_entry_set_application(entry2, "MyApp2");
 *      security_manager_policy_entry_set_privilege(entry2, "http://tizen.org/privilege/systemsettings");
 *      security_manager_policy_entry_set_level(entry2, "Deny");
 *
 *      security_manager_policy_entry_set_application(entry3, "MyApp3");
 *      security_manager_policy_entry_set_privilege(entry3, "http://tizen.org/privilege/notificationmanager");
 *      security_manager_policy_entry_set_level(entry3, "Deny");
 *
 *      security_manager_policy_update_req_add_entry(policy_update_request, entry1);
 *      security_manager_policy_update_req_add_entry(policy_update_request, entry2);
 *      security_manager_policy_update_req_add_entry(policy_update_request, entry3);
 *
 *      //do not change entry1, entry2 or entry3!
 *
 *      security_manager_policy_update_send(policy_update_request);
 *
 *      security_manager_policy_entry_free(entry1);
 *      security_manager_policy_entry_free(entry2);
 *      security_manager_policy_entry_free(entry3);
 *      security_manager_policy_update_free(policy_update_request);
 * \endcode
 * \endparblock
 *
 * - to update policy by administrator for some user:
 *   (Deny access of user of uid 2001 from any app to privilege http://tizen.org/privilege/vibrator,
 *   (allow access of user of uid 2002 using app "App1" to privilege http://tizen.org/privilege/email.admin)
 *
 * \parblock
 * \code{.c}
 *      policy_update_req *policy_update_request;
 *
 *      security_manager_policy_update_req_new(&policy_update_request);
 *
 *      policy_entry *entry1;
 *      policy_entry *entry2;
 *      char *adminswife = "2001";
 *      char *adminsfriend = "2002";
 *
 *      security_manager_policy_entry_new(&entry1);
 *      security_manager_policy_entry_new(&entry2);
 *
 *      security_manager_policy_entry_set_user(entry1, adminswife);
 *      security_manager_policy_entry_set_application(entry1, SECURITY_MANAGER_ANY);
 *      security_manager_policy_entry_set_privilege(entry1, "http://tizen.org/privilege/vibrator");
 *      security_manager_policy_entry_admin_set_level(entry1, "Deny");
 *
 *      security_manager_policy_entry_set_user(entry2, adminsfriend);
 *      security_manager_policy_entry_set_application(entry2, "App1");
 *      security_manager_policy_entry_set_privilege(entry2, "http://tizen.org/privilege/email.admin");
 *      security_manager_policy_entry_admin_set_level(entry2, "Allow");
 *
 *      security_manager_policy_update_req_add_entry(policy_update_request, entry1);
 *      security_manager_policy_update_req_add_entry(policy_update_request, entry2);
 *
 *      //do not change entry1 or entry2!
 *
 *      security_manager_policy_update_send(policy_update_request);
 *
 *      security_manager_policy_entry_free(entry1);
 *      security_manager_policy_entry_free(entry2);
 *      security_manager_policy_update_free(policy_update_request);
 * \endcode
 * \endparblock
 *
 */
int security_manager_policy_update_send(policy_update_req *p_req);

/**
 * \brief Function fetches all privileges enforced by admin user.
 *        The result is stored in the policy_entry structures array.
 *
 * \attention Developer is responsible for calling security_manager_policy_entries_free()
 *            for freeing allocated resources.
 *
 * Required privileges:
 * - http://tizen.org/privilege/internal/usermanagement
 *
 * \param[in]  p_filter        Pointer to filter struct
 * \param[out] ppp_privs_policy Pointer handling allocated policy_entry structures array
 * \param[out] p_size          Pointer where the size of allocated array will be stored
 * \return API return code or error code
 */
int security_manager_get_configured_policy_for_admin(
        policy_entry *p_filter,
        policy_entry ***ppp_privs_policy,
        size_t *p_size);

/**
 * \brief Function fetches all privileges that are configured by user in his/her
 *        privacy manager. The result is stored in the policy_entry structures array.
 *        User may only fetch privileges for his/her own UID.
 *
 * \attention Developer is responsible for calling security_manager_policy_entries_free()
 *            for freeing allocated resources.

 * Required privileges:
 * - http://tizen.org/privilege/notexist
 *
 * \param[in]  p_filter        Pointer to filter struct
 * \param[out] ppp_privs_policy Pointer handling allocated policy_entry structures array
 * \param[out] p_size          Pointer where the size of allocated array will be stored
 * \return API return code or error code
 */
int security_manager_get_configured_policy_for_self(
        policy_entry *p_filter,
        policy_entry ***ppp_privs_policy,
        size_t *p_size);

/**
 * \brief Function gets the whole policy for all users, their applications and privileges
 *        based on the provided filter. The result is stored in the policy_entry array.
 *
 * \attention Developer is responsible for calling security_manager_policy_entries_free()
 *            for freeing allocated resources.
 *
 * Required privileges:
 * - http://tizen.org/privilege/notexist (for fetching own policy)
 * - http://tizen.org/privilege/internal/usermanagement (for fetching policy for other or all)
 *
 * \param[in]  p_filter        Pointer to filter struct
 * \param[out] ppp_privs_policy Pointer handling allocated policy_entry structures array
 * \param[out] p_size          Pointer where the size of allocated array will be stored
 * \return API return code or error code
 */
int security_manager_get_policy(
        policy_entry *p_filter,
        policy_entry ***ppp_privs_policy,
        size_t *p_size);

/**
 *  \brief This function is used to free resources allocated in policy_entry structures array.
 *  \param[in] p_entries Pointer handling allocated policy status array
 *  \param[in] size      Size of the array
 */
void security_manager_policy_entries_free(policy_entry *p_entries, const size_t size);

/**
 * This function returns array of available policy levels in form of simple
 * text descriptions. List is sorted using internal policy level value,
 * from lowest value to highest and starts with "Deny".
 *
 * Caller needs to free memory allocated for the list using
 * security_manager_policy_levels_free().
 *
 * \param levels        Pointer to array of strings
 * \param levels_count  Number of strings in levels array
 * \return API return code or error code.
 */
int security_manager_policy_levels_get(char ***levels, size_t *levels_count);

/**
 * This function free memory allocated by security_manager_policy_levels_get()
 * function.
 *
 * \param levels        Array of strings returned by
 *                      security_manager_policy_levels_get() function.
 * \param levels_count  Number of strings in levels array
 * \return API return code or error code.
 */
void security_manager_policy_levels_free(char **levels, size_t levels_count);

#ifdef __cplusplus
}
#endif


text:
import os

from bunch import Bunch
import yaml

CWD = os.getcwd()

C = Bunch(solar_db="")
C.riak_ensemble = False
C.lock_bucket_type = None
C.counter_bucket_type = None
C.log_file = 'solar.log'
C.system_log_address = 'ipc:///tmp/solar_system_log'
C.tasks_address = 'ipc:///tmp/solar_tasks'
C.scheduler_address = 'ipc:///tmp/solar_scheduler'
C.timewatcher_address = 'ipc:///tmp/solar_timewatcher'

def _lookup_vals(setter, config, prefix=None):
    for key, val in config.iteritems():
        if prefix is None:
            sub = [key]
        else:
            sub = prefix + [key]
        if isinstance(val, Bunch):
            _lookup_vals(setter, val, sub)
        else:
            setter(config, sub)

def from_configs():

    paths = [
        os.getenv('SOLAR_CONFIG', os.path.join(CWD, '.config')),
        os.getenv('SOLAR_CONFIG_OVERRIDE', None),
        os.path.join(CWD, '.config.override')
    ]
    data = {}

    def _load_from_path(data, path):
        with open(path) as f:
            loaded = yaml.load(f)
            if loaded:
                data.update(loaded)

    for path in paths:
        if not path:
            continue
        if not os.path.exists(path):
            continue
        if not os.path.isfile(path):
            continue
        with open(path) as f:
            loaded = yaml.load(f)
            if loaded:
                data.update(loaded)

    def _setter(config, path):
        vals = data
        for key in path:
            if key not in vals:
                return
            vals = vals[key]
        config[path[-1]] = vals
    if data:
        _lookup_vals(_setter, C)

def from_env():
    def _setter(config, path):
        env_key = '_'.join(path).upper()
        if env_key in os.environ:
            config[path[-1]] = os.environ[env_key]
    _lookup_vals(_setter, C)

from_configs()
from_env()


text:
namespace mc {
namespace block {

bool BrewingStand::ImportNBT(nbt::NBT* nbt) {
    auto nameTag = nbt->GetTag<nbt::TagString>(L"CustomName");

    if (nameTag) {
        this->SetCustomName(nameTag->GetValue());
    }

    auto brewTimeTag = nbt->GetTag<nbt::TagInt>(L"BrewTime");
    if (brewTimeTag)
        m_BrewTime = brewTimeTag->GetValue();

    auto fuelTag = nbt->GetTag<nbt::TagByte>(L"Fuel");
    if (fuelTag)
        m_Fuel = fuelTag->GetValue();

    return InventoryBlock::ImportNBT(nbt);
}

inventory::Slot BrewingStand::GetLeftSlot() const noexcept {
    const auto& items = GetItems();
    auto iter = items.find(0);
    if (iter == items.end()) return inventory::Slot();
    return iter->second;
}

inventory::Slot BrewingStand::GetMiddleSlot() const noexcept {
    const auto& items = GetItems();
    auto iter = items.find(1);
    if (iter == items.end()) return inventory::Slot();
    return iter->second;
}

inventory::Slot BrewingStand::GetRightSlot() const noexcept {
    const auto& items = GetItems();
    auto iter = items.find(2);
    if (iter == items.end()) return inventory::Slot();
    return iter->second;
}

inventory::Slot BrewingStand::GetIngredientSlot() const noexcept {
    const auto& items = GetItems();
    auto iter = items.find(3);
    if (iter == items.end()) return inventory::Slot();
    return iter->second;
}

inventory::Slot BrewingStand::GetFuelSlot() const noexcept {
    const auto& items = GetItems();
    auto iter = items.find(4);
    if (iter == items.end()) return inventory::Slot();
    return iter->second;
}

} // ns block
} // ns mc


text:
package com.facebook.buck.rules.visibility;

/** Attributes pertaining to visibility evaluation. */
public class VisibilityAttributes {

  public static final String VISIBILITY = "visibility";
  public static final String WITHIN_VIEW = "within_view";

  /** Prevent initialization */
  private VisibilityAttributes() {}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="toast_rotation_locked" msgid="7609673011431556092">"Dabar ekranas užrakintas horizontalioje pozicijoje."</string>
</resources>


text:
"use strict";

var EventEmitter = require("events").EventEmitter;
var util = require("util");
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
var Chan = require("../src/models/chan");

function MockClient(opts) {
	this.user = {nick: "test-user"};

	for (var k in opts) {
		this[k] = opts[k];
	}
}
util.inherits(MockClient, EventEmitter);

MockClient.prototype.createMessage = function(opts) {
	var message = _.extend({
		text: "dummy message",
		nick: "test-user",
		target: "#test-channel",
		previews: [],
	}, opts);

	return message;
};

module.exports = {
	createClient: function() {
		return new MockClient();
	},
	createNetwork: function() {
		return new Network({
			host: "example.com",
			channels: [new Chan({
				name: "#test-channel"
			})]
		});
	},
	createWebserver: function() {
		return express();
	}
};


text:
from pyalp_translation.customization import custom_gettext
gettext = custom_gettext('pizza')


text: This is a sample paragraph that will be used for tests.