package net.kencochrane.raven.sentrystub.event;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;
import java.util.Map;

public class Event {
    @JsonProperty(value = "event_id", required = true)
    private String eventId;
    @JsonProperty(value = "checksum")
    private String checksum;
    @JsonProperty(value = "message")
    private String message;
    @JsonProperty(value = "timestamp", required = true)
    private Date timestamp;
    @JsonProperty(value = "level")
    private String level;
    @JsonProperty(value = "logger")
    private String logger;
    @JsonProperty(value = "platform")
    private String platform;
    @JsonProperty(value = "culprit")
    private String culprit;
    @JsonProperty(value = "tags")
    private Map<String, String> tags;
    @JsonProperty(value = "server_name")
    private String serverName;
    @JsonProperty(value = "modules")
    private Map<String, String> modules;
    @JsonProperty(value = "extra")
    private Map<String, Object> extras;
//    @JsonProperty(value = "sentry.interfaces.Message")
//    private Map<String, ?> messageInterface;
}

Create an event class to auto parse JSon files


/**
 * Steven Ward
 * VendingMachine.java | Drink Machine Project
 *
 * This file contains the definition of the VendingMachine interface, which is described below.
 *
 * Due Date: December 4, 2016
 *
 */

/**
 * TODO: CLASS-LEVEL DOCUMENTATION FOR VENDINGMACHINE INTERFACE!
 *       JAVADOC TAGS
 */

public interface VendingMachine<ProductType extends Enum<ProductType>> {

  enum Money {
    PENNY       (0.01),
    NICKEL      (0.05),
    DIME        (0.10),
    QUARTER     (0.25),
    HALF_DOLLAR (0.50),
    ONE_DOLLAR  (1.00),
    FIVE_DOLLAR (5.00);

    public final value;
    Money(double val) { this.value = val; }

    public static double totalValue(List<Money> money) {

    }
  }
}

Add Inventory interface - in progress


/*
 * Copyright 2016 Michael Rozumyanskiy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.michaelrocks.lightsaber;

import io.michaelrocks.lightsaber.internal.AbstractInjectingProvider;
import io.michaelrocks.lightsaber.internal.InjectingProvider;

class InjectorOverridingProvider<T> extends AbstractInjectingProvider<T> {
  private final InjectingProvider<T> provider;

  InjectorOverridingProvider(final InjectingProvider<T> provider, final Injector injector) {
    super(injector);
    this.provider = provider;
  }

  @Override
  public T getWithInjector(final Injector injector) {
    return provider.getWithInjector(injector);
  }
}

Add a wrapping providers that overrides an injector of its delegate provider


package com.novoda.downloadmanager;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

class NetworkResponseFixtures {

    private int code = 201;
    private boolean isSuccessful = true;
    private String header = "header";
    private InputStream inputStream = new ByteArrayInputStream("input".getBytes());

    static NetworkResponseFixtures aNetworkResponse() {
        return new NetworkResponseFixtures();
    }

    NetworkResponseFixtures withCode(int code) {
        this.code = code;
        return this;
    }

    NetworkResponseFixtures withSuccessful(boolean successful) {
        isSuccessful = successful;
        return this;
    }

    NetworkResponseFixtures withHeader(String header) {
        this.header = header;
        return this;
    }

    NetworkResponseFixtures withInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
        return this;
    }

    HttpClient.NetworkResponse build() {
        return new HttpClient.NetworkResponse() {
            @Override
            public int code() {
                return code;
            }

            @Override
            public boolean isSuccessful() {
                return isSuccessful;
            }

            @Override
            public String header(String name, String defaultValue) {
                return header;
            }

            @Override
            public InputStream openByteStream() throws IOException {
                return inputStream;
            }

            @Override
            public void closeByteStream() throws IOException {
                inputStream.close();
            }
        };
    }
}

Add a fixture for a network response.


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sablecc.sablecc.util;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.sablecc.sablecc.exception.InternalException;

public class WorkSet<T> {

    private final Set<T> done = new HashSet<T>();

    private final LinkedHashSet<T> toDo = new LinkedHashSet<T>();

    public boolean hasNext() {

        return !this.toDo.isEmpty();
    }

    public T next() {

        T next = this.toDo.iterator().next();

        this.toDo.remove(next);
        this.done.add(next);

        return next;
    }

    public void add(
            T element) {

        if (element == null) {
            throw new InternalException("element may not be null");
        }

        if (!this.done.contains(element)) {
            this.toDo.add(element);
        }
    }
}

Add class to manage work sets.


package com.sec.ax.restful.crypt.aes;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.sec.ax.restful.crypt.AxCryptException;

import junit.framework.TestCase;

/**
 *
 * @author heesik.jeon
 *
 */

public class AxCryptTest extends TestCase {

	private Logger logger = Logger.getLogger(this.getClass());

	public AxCryptTest() {
		logger.setLevel(Level.DEBUG);
	}

	public void testDecrypt() {

		try {

			String encrypted = "yhAGrcZInqeKNvMiLiBugeIT/Sb/4ldr8YMLaL0OrRmvLc/pHJ8YZTda0R63HRyC";
			String decrypted = AxCrypt.decrypt("Vvb7oruYPkOHrEwoTVnXtw==", encrypted);

			logger.debug(encrypted);
			logger.debug(decrypted);

		} catch (AxCryptException e) {
			fail(e.toString());
		}

	}

}

Add TestCase to decrypt text


package paprika.metrics;

import paprika.entities.PaprikaApp;

/**
 * Created by antonin on 16-04-29.
 */
public class NumberOfBitmaps extends UnaryMetric<Integer> {

    private NumberOfBitmaps(PaprikaApp paprikaApp, int nbOfBitmaps) {
        this.value = nbOfBitmaps;
        this.entity = paprikaApp;
        this.name = "number_of_bitmaps";
    }

    public static NumberOfBitmaps createNumberOfBitmaps(PaprikaApp paprikaApp, int nbOfBitmaps) {
        NumberOfBitmaps numberOfBitmaps = new NumberOfBitmaps(paprikaApp, nbOfBitmaps);
        numberOfBitmaps.updateEntity();
        return numberOfBitmaps;
    }

}

Add the number of bitmaps as a new feature


package org.intermine.webservice.server.exceptions;

import org.intermine.webservice.server.output.Output;

public class UnauthorizedException extends ServiceException {

    private static final long serialVersionUID = 1L;

    public UnauthorizedException() {
        super("This service requires authentication.");
        initResponseCode();
    }

    public UnauthorizedException(String message) {
        super(message);
        initResponseCode();
    }

    private void initResponseCode() {
        setHttpErrorCode(Output.SC_UNAUTHORIZED);
    }
}

Send 406 codes when appropriate


/*
 * Copyright 2012 Greplin, Inc. All Rights Reserved.
 */

package com.greplin.lucene.query;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;

import java.io.IOException;

/**
* A sub-slice of a DocIdSet.
*/
public class DocIdSetSlice extends DocIdSet {

  /**
   * The underlying DocIdSet.
   */
  private final DocIdSet underlying;

  /**
   * The start of the slice.
   */
  private final int start;

  /**
   * The end of the slice.
   */
  private final int end;

  /**
   * Constructs a DocIdSet that is a slice of another DocIdSet.
   * @param underlying the underlying DocIdSet
   * @param start the start of the slice
   * @param end the end of the slice
   */
  public DocIdSetSlice(
      final DocIdSet underlying, final int start, final int end) {
    assert start >= 0;
    assert end >= start;
    this.underlying = underlying;
    this.start = start;
    this.end = end;
  }

  /**
   * Internal iterator implementation for slices.
   */
  private final class Iterator extends DocIdSetIterator {

    /**
     * The underlying iterator.
     */
    private final DocIdSetIterator underlying;

    /**
     * Constructs an iterator.
     * @throws IOException if IO errors are encountered.
     */
    private Iterator() throws IOException {
      this.underlying = DocIdSetSlice.this.underlying.iterator();
    }

    @Override
    public int docID() {
      int docId = this.underlying.docID();
      return docId < DocIdSetSlice.this.end
          ? docId - DocIdSetSlice.this.start : NO_MORE_DOCS;
    }

    @Override
    public int nextDoc() throws IOException {
      if (this.underlying.docID() == -1) {
        this.underlying.advance(DocIdSetSlice.this.start);
      } else {
        this.underlying.nextDoc();
      }
      return docID();
    }

    @Override
    public int advance(final int target) throws IOException {
      if (target == Integer.MAX_VALUE) {
        this.underlying.advance(target);
        return docID();
      }
      assert DocIdSetSlice.this.start + target >= 0;
      this.underlying.advance(DocIdSetSlice.this.start + target);
      return docID();
    }
  }

  @Override
  public DocIdSetIterator iterator() throws IOException {
    return new Iterator();
  }

}

Add utility for sub-slices of DocIdSets


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.cassandra.db;

import java.nio.ByteBuffer;

import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetriedSliceFromReadCommand extends SliceFromReadCommand
{
    static final Logger logger = LoggerFactory.getLogger(RetriedSliceFromReadCommand.class);
    public final int originalCount;

    public RetriedSliceFromReadCommand(String table, ByteBuffer key, ColumnParent column_parent, ByteBuffer start,
            ByteBuffer finish, boolean reversed, int originalCount, int count)
    {
        super(table, key, column_parent, start, finish, reversed, count);
        this.originalCount = originalCount;
    }

    public RetriedSliceFromReadCommand(String table, ByteBuffer key, QueryPath path, ByteBuffer start,
            ByteBuffer finish, boolean reversed, int originalCount, int count)
    {
        super(table, key, path, start, finish, reversed, count);
        this.originalCount = originalCount;
    }

    @Override
    public ReadCommand copy()
    {
        ReadCommand readCommand = new RetriedSliceFromReadCommand(table, key, queryPath, start, finish, reversed, originalCount, count);
        readCommand.setDigestQuery(isDigestQuery());
        return readCommand;
    }

    @Override
    public int getRequestedCount()
    {
        return originalCount;
    }

    @Override
    public String toString()
    {
        return "RetriedSliceFromReadCommand(" +
               "table='" + table + '\'' +
               ", key='" + ByteBufferUtil.bytesToHex(key) + '\'' +
               ", column_parent='" + queryPath + '\'' +
               ", start='" + getComparator().getString(start) + '\'' +
               ", finish='" + getComparator().getString(finish) + '\'' +
               ", reversed=" + reversed +
               ", originalCount=" + originalCount +
               ", count=" + count +
               ')';
    }

}

Add missing file from previous commit


package pinterest;

import com.google.gson.Gson;
import fields.PinFields;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import responses.Pin;
import responses.Pins;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class STestPinterest {
    private static final String PIN_ID = "525091637782793357";

    private final Pinterest pinterest = new Pinterest("ARp8HNzfw2scBtJqtYA57a8xFeAqFBzML4SnnEZCe9w6DeAJGAAAAAA");

    @Test
    public void testPinWithFields() throws IOException {
        final Pin actualPin = pinterest.retrievePinWithFields(PIN_ID, new PinFields().setAllFields());
        final Pin expectedPin = new Gson().fromJson(loadFile("responses/CompletePinResponse.json"), Pin.class);

        assertEquals(expectedPin, actualPin);
    }

    @Test
    public void testPinWithDefaultFields() throws IOException {
        final Pin actualPin = pinterest.retrievePinWithDefaultFields(PIN_ID);
        final Pin expectedPin = new Gson().fromJson(loadFile("responses/DefaultPinResponse.json"), Pin.class);

        assertEquals(expectedPin, actualPin);
    }

    @Test
    public void testBoardWithDefaultFields() throws IOException {
        final Pins actualPins = pinterest.retrievePinsFromBoard("francisabila/all-about-me");
        final Pins expectedPins = new Gson().fromJson(loadFile("responses/DefaultBoardResponse.json"), Pins.class);

        assertEquals(expectedPins, actualPins);
    }

    @Test
    public void testBoardWithAllFields() throws IOException {
        final Pins actualPins = pinterest.retrievePinsFromBoard("francisabila/all-about-me", new PinFields().setAllFields());
        final Pins expectedPins = new Gson().fromJson(loadFile("responses/CompleteBoardResponse.json"), Pins.class);

        assertEquals(expectedPins, actualPins);
    }

    private static String loadFile(final String resource) throws IOException {
        return IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream(resource));
    }
}

Add STest for API calls


package leetcode;

/**
 * https://leetcode.com/problems/range-sum-query-2d-immutable/
 */
public class Problem304 {
    public static class NumMatrix {

        public NumMatrix(int[][] matrix) {

        }

        public int sumRegion(int row1, int col1, int row2, int col2) {
            // TODO:
            return 0;
        }
    }

    public static void main(String[] args) {
        NumMatrix matrix = new NumMatrix(new int[][]{
            {3, 0, 1, 4, 2},
            {5, 6, 3, 2, 1},
            {1, 2, 0, 1, 5},
            {4, 1, 0, 1, 7},
            {1, 0, 3, 0, 5},
        });
        System.out.println(matrix.sumRegion(2, 1, 4, 3)); // 8
        System.out.println(matrix.sumRegion(1, 1, 2, 2)); // 11
        System.out.println(matrix.sumRegion(1, 2, 2, 4)); // 12
    }
}

Create a skeleton for problem 304


import java.util.Scanner;

public class Review {
    public static void main(String[] args) {
        // Printing to STDOUT
        System.out.println("Hello, world!");

        // Getting user input and string concatanation
        Scanner in = new Scanner(System.in);
        System.out.println("Type some text");
        String input = in.nextLine();
        System.out.println("You typed: " + input);

        // For loops and escaped characters
        System.out.println("\nFor Loop Example");
        for (int i = 1; i <= 5; i++) {
            System.out.print(i);
        }
        System.out.println();

        // Data types and if/else statements
        boolean test = true;
        if (test) {
            System.out.println("This is an if statement.");
        } else {
            System.out.println("This is an else statement, but you shouldn't see me!");
        }

        // While loops
        int a = 1;
        int b = 1000;
        while (a < b) {
            a += 42;
            b += 1;
        }
        System.out.println("A: " + a + " B: " + b);
    }
}

Add review program for seniors for first day


/*
 * Copyright (c) 2020 University Corporation for Atmospheric Research/Unidata
 * See LICENSE for license information.
 */
package ucar.nc2.dataset;

import static com.google.common.truth.Truth.assertThat;
import java.io.IOException;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import ucar.nc2.constants.AxisType;
import ucar.unidata.util.test.TestDir;
import ucar.unidata.util.test.category.NeedsCdmUnitTest;

/**
 * Some GOES-16/17 products are "CF-ish", in that they don't quite use projection variable attributes that match what CF
 * expects. Given the widespread use of these files, it's best we try to identify them and "do the right thing", and it
 * no longer appears that products are being produced without duplicating the attributes, so it's for historical data
 * only. This tests our CFConventions class to make sure this case is handled.
 */
@Category(NeedsCdmUnitTest.class)
public class TestGoesCFish {

  private static String testFile = TestDir.cdmUnitTestDir + "/conventions/cf/cf-ish/OR_EFD-060.nc";

  @Test
  public void testBadProjVarAttrsOld() throws IOException {
    try (NetcdfDataset ncd = NetcdfDataset.openDataset(testFile)) {
      checkAxis(ncd);
    }
  }

  @Test
  public void testBadProjVarAttrsNew() throws IOException {
    try (NetcdfDataset ncd = NetcdfDatasets.openDataset(testFile)) {
      checkAxis(ncd);
    }
  }

  private void checkAxis(NetcdfDataset ncd) {
    CoordinateAxis latAxis = ncd.findCoordinateAxis(AxisType.GeoX);
    assertThat(latAxis != null);
    assertThat(latAxis.getAxisType()).isEqualTo(AxisType.GeoX);
  }

}

Add test to fail on CF-ish GOES16 Product


//66. Plus One
/**
 * Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
 *
 * You may assume the integer do not contain any leading zero, except the number 0 itself.
 *
 * The digits are stored such that the most significant digit is at the head of the list.
 *
 * Tags: Array, Math
 *
 * Similar Problems:  (M) Multiply Strings (E) Add Binary (M) Plus One Linked List
 *
 * @author Xinyue Zhang
 *
 */

public class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;

        for (int i = n - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            else
                digits[i] = 0;
        }

        int[] res = new int[n + 1];
        res[0] = 1;
        return res;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] digits = {9,9,9,9};
        int[] res = sol.plusOne(digits);
        for (int i = 0; i < res.length; i++)
            System.out.println(res[i]);
    }
}

Add solution for 066 plus one


package org.cometd.server;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerSession;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.http.HttpHeaders;

public class DisconnectTest extends AbstractBayeuxClientServerTest
{
    private BayeuxServer bayeux;

    @Override
    protected void customizeBayeux(BayeuxServerImpl bayeux)
    {
        this.bayeux = bayeux;
    }

    public void testDisconnect() throws Exception
    {
        ContentExchange handshake = newBayeuxExchange("[{" +
                "\"channel\": \"/meta/handshake\"," +
                "\"version\": \"1.0\"," +
                "\"minimumVersion\": \"1.0\"," +
                "\"supportedConnectionTypes\": [\"long-polling\"]" +
                "}]");
        httpClient.send(handshake);
        assertEquals(HttpExchange.STATUS_COMPLETED, handshake.waitForDone());
        assertEquals(200, handshake.getResponseStatus());

        String clientId = extractClientId(handshake);
        String bayeuxCookie = extractBayeuxCookie(handshake);

        ContentExchange connect = newBayeuxExchange("[{" +
                "\"channel\": \"/meta/connect\"," +
                "\"clientId\": \"" + clientId + "\"," +
                "\"connectionType\": \"long-polling\"" +
                "}]");
        connect.setRequestHeader(HttpHeaders.COOKIE, bayeuxCookie);
        httpClient.send(connect);
        assertEquals(HttpExchange.STATUS_COMPLETED, connect.waitForDone());
        assertEquals(200, connect.getResponseStatus());

        ServerSession serverSession = bayeux.getSession(clientId);
        assertNotNull(serverSession);

        final CountDownLatch latch = new CountDownLatch(1);
        serverSession.addListener(new ServerSession.RemoveListener()
        {
            public void removed(ServerSession session, boolean timeout)
            {
                latch.countDown();
            }
        });

        ContentExchange disconnect = newBayeuxExchange("[{" +
                "\"channel\": \"/meta/disconnect\"," +
                "\"clientId\": \"" + clientId + "\"" +
                "}]");
        httpClient.send(disconnect);
        assertEquals(HttpExchange.STATUS_COMPLETED, disconnect.waitForDone());
        assertEquals(200, disconnect.getResponseStatus());

        assertTrue(latch.await(1, TimeUnit.SECONDS));
    }
}

Test for COMETD-226 (Client's cometd.disconnect() call does not trigger RemoveListener's removed() method immediately).


import org.junit.Test;
import java.util.Arrays;

public class QuickSortTest {

    @Test
    public void test() {
        int list[] = { -5, 8, 0, 12, 55, 1, -66, 35, 3 };
        int listLength = list.length;
        QuickSort quickSort = new QuickSort();
        quickSort.sort(list, 0, listLength-1);
        for (int i = 0; i < list.length - 1; i++) {
            assert (list[i] <= list[i + 1]);
        }
    }

    @Test
    public void nullList(){
        int list[] = {};
        int expectedList[] = {};
        QuickSort quickSort = new QuickSort();
        quickSort.sort(list, 0, 0);
        assert (Arrays.equals(list, expectedList));
    }
}

Add quick sort test for Java implementation


package simple.xml.transform;

import simple.xml.transform.Transform;

public class IntegerArrayTransform implements Transform<Integer[]> {

   private final StringArrayTransform split;

   private final Transform single;

   public IntegerArrayTransform() {
      this.split = new StringArrayTransform();
      this.single = new IntegerTransform();
   }

   public Integer[] read(String value) {
      String[] list = split.read(value);

      if(list.length > 0) {
         return read(list);
      }
      return new Integer[]{};
   }

   private Integer[] read(String[] text) {
      Integer[] list = new Integer[text.length];

      for(int i = 0; i < text.length; i++) {
         list[i] = single.read(entry);
      }
      return list;
   }

   public String write(Integer[] list) {
      String[] text = new String[list.length];

      for(int i = 0; i < text.length; i++) {
         text[i] = single.read(list[i]);
      }
      return split.write(text);
   }
}

Add the integer array transform


/*
 * Copyright 2015 Hippo Seven
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hippo.nimingban.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;

import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.io.InputStreamPipe;

import java.io.IOException;
import java.io.InputStream;

public class BitmapUtils {

    /**
     * @return null or the bitmap
     */
    public static Bitmap decodeStream(@NonNull InputStreamPipe isp, int maxWidth, int maxHeight) {
        try {
            isp.obtain();
            InputStream is = isp.open();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);
            is.close();

            int width = options.outWidth;
            int height = options.outHeight;
            if (width <= 0 || height <= 0) {
                return null;
            }

            options.inJustDecodeBounds = false;
            if (width <= maxWidth && height <= maxHeight) {
                options.inSampleSize = 1;
            } else {
                float scaleW = (float) width / (float) maxWidth;
                float scaleH = (float) height / (float) maxHeight;
                options.inSampleSize = MathUtils.nextPowerOf2((int) Math.max(scaleW, scaleH));
            }

            return BitmapFactory.decodeStream(isp.open(), null, options);
        } catch (IOException e) {
            return null;
        } finally {
            isp.close();
            isp.release();
        }
    }
}

Use image loading strategy for Header


package com.seaglasslookandfeel.demo;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import sun.swing.table.DefaultTableCellHeaderRenderer;

class JComponentTableCellRenderer extends DefaultTableCellHeaderRenderer/*SeaGlassTableHeaderUI.HeaderRenderer*/ {
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
        int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        return /*this;*/(JComponent) value;
    }
}

public class TestTables3 {
    public static void main(String args[]) {
        if (true) {
            try {
                UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        final Object rows[][] = { { "one", "1" }, { "two", "2" }, { "three", "3" } };
        JFrame frame = new JFrame("Label Header");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String headers[] = { "English", "#" };
        JTable table = new JTable(rows, headers);
        JScrollPane scrollPane = new JScrollPane(table);

        TableModel tableModel = table.getModel();
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
        table.setRowSorter(sorter);

        Icon redIcon = new ImageIcon(TestTables3.class.getResource("/com/seaglasslookandfeel/images/gear.png"));
        Icon blueIcon = new ImageIcon(TestTables3.class.getResource("/com/seaglasslookandfeel/images/Event.png"));

        Border headerBorder = UIManager.getBorder("TableHeader.cellBorder");

        JLabel blueLabel = new JLabel(headers[0], blueIcon, JLabel.CENTER);
        blueLabel.setBorder(headerBorder);
        JLabel redLabel = new JLabel(headers[1], redIcon, JLabel.CENTER);
        redLabel.setBorder(headerBorder);

        TableCellRenderer renderer = new JComponentTableCellRenderer();

        TableColumnModel columnModel = table.getColumnModel();

        TableColumn column0 = columnModel.getColumn(0);
        TableColumn column1 = columnModel.getColumn(1);

        column0.setHeaderRenderer(renderer);
        column0.setHeaderValue(blueLabel);

        column1.setHeaderRenderer(renderer);
        column1.setHeaderValue(redLabel);

        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    }
}

Add test for icons in table headers.


package seedu.ezdo.commons.util;

import java.util.ArrayList;

import seedu.ezdo.commons.core.UnmodifiableObservableList;
import seedu.ezdo.model.todo.ReadOnlyTask;
//@@author A0139248X
/**
 * Utility methods for commands supporting multiple index
 */
public class MultipleIndexCommandUtil {
    /** checks if the indexes specified are all smaller than the size of the list and not 0 i.e. valid */
    public static boolean isIndexValid(UnmodifiableObservableList<ReadOnlyTask> lastShownList, ArrayList<Integer> targetIndexes) {
        return targetIndexes.stream().allMatch(index -> index <= lastShownList.size() && index != 0);
    }
}

Add Util class for commands supporting multiple indexes


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import at.ac.tuwien.inso.exception.BusinessObjectNotFoundException;
import at.ac.tuwien.inso.service.UisUserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class UisUserServiceSecurityTests {

    @Autowired
    private UisUserService uisUserService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findAllMatchingNotAuthenticated() {
        uisUserService.findAllMatching("");
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "STUDENT")
    public void findAllMatchingAuthenticatedAsStudent() {
        uisUserService.findAllMatching("");
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "LECTURER")
    public void findAllMatchingAuthenticatedAsLecturer() {
        uisUserService.findAllMatching("");
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    public void findAllMatchingAuthenticatedAsAdmin() {
        uisUserService.findAllMatching("");
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findOneNotAuthenticated() {
        uisUserService.findOne(Long.valueOf(1));
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "STUDENT")
    public void findOneAuthenticatedAsStudent() {
        uisUserService.findOne(Long.valueOf(1));
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "LECTURER")
    public void findOneAuthenticatedAsLecturer() {
        uisUserService.findOne(Long.valueOf(1));
    }

    @Test(expected = BusinessObjectNotFoundException.class)
    @WithMockUser(roles = "ADMIN")
    public void findOneAuthenticatedAsAdmin() {
        uisUserService.findOne(Long.valueOf(1));
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void existsUserWithIdentificationNumberNotAuthenticated() {
        uisUserService.existsUserWithIdentificationNumber("");
    }

    @Test
    @WithMockUser
    public void existsUserWithIdentificationNumberAuthenticated() {
        uisUserService.existsUserWithIdentificationNumber("");
    }

}

Add tests for method security for UisUserService


package net.ttsui.junit.rules.pending;

import org.junit.Rule;
import org.junit.Test;

import junit.framework.Assert;

public class BugWithMultiplePendingAnnotationsTest {
    @Rule public PendingRule rule = new PendingRule();

    @PendingImplementation
    @Test public void
    pendingTest1() {
        Assert.fail();
    }

    @Test public void
    passingTest() {

    }

    @Test public void
    failingTest() {
        Assert.fail();
    }

    @PendingImplementation
    @Test public void
    pendingTest2() {
        Assert.fail();
    }
}

Add test case for possible bug with multiple pending annotations.


/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.model.properties;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;

import java.util.Arrays;

import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.widgets.plots.ImageWidget;
import org.junit.Test;

/** JUnit test of Rules
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class RulesTest
{
    /** Rule that checks pv0>10 and picks a certain value for that */
    @Test
    public void testValueForCondition() throws Exception
    {
        final ImageWidget widget = new ImageWidget();

        final WidgetProperty<Integer> width = widget.propDataWidth().clone();
        width.setValue(47);

        final RuleInfo rule = new RuleInfo("WidthBasedOnPV", "data_width", true,
                Arrays.asList(new RuleInfo.ExprInfoValue<Integer>("pv0>10", width)),
                Arrays.asList(new ScriptPV("XSize")));

        System.out.println(rule);
        final String script = RuleToScript.generatePy(widget, null, rule);
        System.out.println(script);
        // Script must read the PV
        assertThat(script, containsString("pv0 = PVUtil.getDouble(pvs[0])"));
    }

    /** Rules that uses the value of a PV within an expression */
    @Test
    public void testValueAsExpression() throws Exception
    {
        final Widget widget = new ImageWidget();
        final RuleInfo rule = new RuleInfo("WidthFromPV", "data_width", true,
                Arrays.asList(new RuleInfo.ExprInfoString("true", "pv0")),
                Arrays.asList(new ScriptPV("XSize")));

        System.out.println(rule);
        final String script = RuleToScript.generatePy(widget, null, rule);
        System.out.println(script);
        // Script must read the PV
        assertThat(script, containsString("PVUtil.get"));
    }
}

Add test for bug in handling of prop_as_expr_flag


package gsg.client;

import gsg.infrastructure.MessageRegistrator;
import gsg.threads.IJob;
import gsg.threads.JobRunnerConfiguration;
import gsg.threads.JobRunnerData;

/**
 * @author zkejid@gmail.com
 *         Created: 23.07.15 9:18
 */
public class BotLoop implements IJob {
	public static final long STEP_TIME = 5000L;
	private static String[] route = new String[]{"left", "up", "right", "down", "down", "right", "up", "left"};

	private int currentStep;
	private String key;
	private MessageRegistrator registrator;
	private long time;

	public BotLoop(String key, MessageRegistrator registrator) {
		this.key = key;
		this.registrator = registrator;
		currentStep = -1;
		time = -1L;
	}

	@Override
	public void doJob(JobRunnerConfiguration configuration, JobRunnerData data) {
		if (timeHasCome()) {
			time = System.currentTimeMillis() + STEP_TIME;
			currentStep = (currentStep + 1) % route.length;
			//key should be checked by server. not client.
			final String line = key + " " + route[currentStep];
			registrator.registerMessage(line);
			System.out.println("client generates action: "+line);
		}
	}

	private boolean timeHasCome() {
		final long currentTime = System.currentTimeMillis();
		return currentTime >= time;
	}
}

Add stub of "more clever" bot


package de.goddchen.android.rxfiredroid.tests;

import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import de.goddchen.android.rxfiredroid.config.RxFireDroidRemoteConfig;
import io.reactivex.functions.Predicate;

/**
 * Created by goddc on 04.12.2016.
 */

@RunWith(AndroidJUnit4.class)
public class RxFireDroidRemoteConfigTest {

    @Test
    public void staticDefaultsTest() throws InterruptedException {
        RxFireDroidRemoteConfig.getBoolean("static-default")
                .test()
                .await()
                .assertValue(false);
        RxFireDroidRemoteConfig.getString("static-default")
                .test()
                .await()
                .assertValue("");
        RxFireDroidRemoteConfig.getByteArray("static-default")
                .test()
                .await()
                .assertValue(new Predicate<byte[]>() {
                    @Override
                    public boolean test(byte[] bytes) throws Exception {
                        return bytes.length == 0;
                    }
                });
        RxFireDroidRemoteConfig.getDouble("static-default")
                .test()
                .await()
                .assertValue(0D);
        RxFireDroidRemoteConfig.getLong("static-default")
                .test()
                .await()
                .assertValue(0L);
    }
}

Add some tests for RxFireDroidRemoteConfig


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2019
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package elki.evaluation.clustering;

import static org.junit.Assert.*;

import org.junit.Test;

import elki.database.ids.DBIDRange;
import elki.database.ids.DBIDUtil;

/**
 * Validate the {@link MaximumMatchingAccuracy} measure.
 *
 * @author Robert Gehde
 */
public class MaximumMatchingAccuracyTest extends AbstractClusterEvaluationTest {
  @Test
  public void testMMAccuracy() {
    DBIDRange ids = DBIDUtil.generateStaticDBIDRange(SKLEARNA.length);
    ClusterContingencyTable cc = new ClusterContingencyTable(true, false, makeClustering(ids.iter(), SKLEARNA), makeClustering(ids.iter(), SKLEARNB));
    MaximumMatchingAccuracy mmacc = new MaximumMatchingAccuracy(cc);

    assertEquals("KMW Accuracy not as expected", 12. / 17., mmacc.getAccuracy(), 1e-15);
  }
}

Add test for maximum matching cluster accuracy


package ca.uhn.fhir.mdm.api.paging;

import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;

class MdmPageLinkBuilderTest {

	@Test
	void buildLinkWithExistingParameters() {
		//Given
		String expected = "http://localhost:8000/$mdm-query-links?sourceResourceId=Patient/123&_offset=1&_count=1";
		String baseUrl = "http://localhost:8000/$mdm-query-links?sourceResourceId=Patient/123";

		//When
		String builtUrl = MdmPageLinkBuilder.buildLinkWithOffsetAndCount(baseUrl, 1, 1);

		//Then
		assertThat(builtUrl, is(equalTo(expected)));
	}

	@Test
	void buildLinkWithoutExistingParameters() {
		//Given
		String expected = "http://localhost:8000/$mdm-query-links?_offset=1&_count=1";
		String baseUrl = "http://localhost:8000/$mdm-query-links";

		//When
		String builtUrl = MdmPageLinkBuilder.buildLinkWithOffsetAndCount(baseUrl, 1, 1);

		//Then
		assertThat(builtUrl, is(equalTo(expected)));
	}
}

Add tests for link builder


package com.handmark.pulltorefresh.library;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;

final class OverscrollHelper {

	static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
		final Mode mode = view.getCurrentMode();

		if (mode != Mode.DISABLED && !isTouchEvent) {
			final int newY = (deltaY + scrollY);

			if (newY != 0) {
				// Check the mode supports the overscroll direction, and
				// then move scroll
				if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
					view.setHeaderScroll(view.getScrollY() + newY);
				}
			} else {
				// Means we've stopped overscrolling, so scroll back to 0
				view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
			}
		}
	}
}

package com.handmark.pulltorefresh.library;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;

final class OverscrollHelper {

	static void overScrollBy(PullToRefreshBase<?> view, int deltaY, int scrollY, boolean isTouchEvent) {
		final Mode mode = view.getMode();

		if (mode != Mode.DISABLED && !isTouchEvent) {
			final int newY = (deltaY + scrollY);

			if (newY != 0) {
				// Check the mode supports the overscroll direction, and
				// then move scroll
				if ((mode.canPullDown() && newY < 0) || (mode.canPullUp() && newY > 0)) {
					view.setHeaderScroll(view.getScrollY() + newY);
				}
			} else {
				// Means we've stopped overscrolling, so scroll back to 0
				view.smoothScrollTo(0, PullToRefreshBase.SMOOTH_SCROLL_LONG_DURATION_MS);
			}
		}
	}
}

Fix Overscroll when we're using Mode.BOTH


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
 * Used by re-version.sh. Not included in normal compile so it doesn't accidentally end up in artifacts.
 * Need it to be a java class to handle weird manifest lines
 */
public class ManifestReversion {
    public static void main(String[] args) throws Exception {
        String filename = args[0];
        String version = args[1]
                .replaceFirst("^v", "");

        Manifest manifest;
        try (InputStream input = new FileInputStream(filename)) {
            manifest = new Manifest(input);
        }
        final Attributes attributes = manifest.getMainAttributes();

        attributes.putValue("Liquibase-Version", version);

        final String bundleVersion = attributes.getValue("Bundle-Version");
        if (bundleVersion != null) {
            attributes.putValue("Bundle-Version", version);
        }

        final String importPackage = attributes.getValue("Import-Package");
        if (importPackage != null) {
            attributes.putValue("Import-Package", importPackage.replaceAll("version=\"\\[0\\.0,1\\)\"", "version=\"[" + version + ",1)"));
        }

        final String exportPackage = attributes.getValue("Export-Package");
        if (exportPackage != null) {
            attributes.putValue("Export-Package", exportPackage.replaceAll(";version=\"0\\.0\\.0\"", ";version=\"" + version + "\""));
        }

        try (OutputStream out = new FileOutputStream(filename)) {
            manifest.write(out);
        }
    }
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
 * Used by re-version.sh. Not included in normal compile so it doesn't accidentally end up in artifacts.
 * Need it to be a java class to handle weird manifest lines
 */
public class ManifestReversion {
    public static void main(String[] args) throws Exception {
        String filename = args[0];
        String version = args[1]
                .replaceFirst("^v", "");

        Manifest manifest;
        try (InputStream input = new FileInputStream(filename)) {
            manifest = new Manifest(input);
        }
        final Attributes attributes = manifest.getMainAttributes();

        attributes.putValue("Liquibase-Version", version);

        final String bundleVersion = attributes.getValue("Bundle-Version");
        if (bundleVersion != null) {
            attributes.putValue("Bundle-Version", version);
        }

        final String importPackage = attributes.getValue("Import-Package");
        if (importPackage != null) {
            attributes.putValue("Import-Package", importPackage.replaceAll("version=\"\\[0\\.0,1\\)\"", "version=\"[" + version + ",1)\""));
        }

        final String exportPackage = attributes.getValue("Export-Package");
        if (exportPackage != null) {
            attributes.putValue("Export-Package", exportPackage.replaceAll(";version=\"0\\.0\\.0\"", ";version=\"" + version + "\""));
        }

        try (OutputStream out = new FileOutputStream(filename)) {
            manifest.write(out);
        }
    }
}

Fix quoting for MANIFEST.MF Import-Package


/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

package org.openlmis.equipment.repository.mapper;

import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.openlmis.db.categories.IntegrationTests;
import org.openlmis.equipment.domain.EquipmentOperationalStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.junit.Assert.*;

@Category(IntegrationTests.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:test-applicationContext-equipment.xml")
@Transactional
@TransactionConfiguration(defaultRollback = true, transactionManager = "openLmisTransactionManager")
public class EquipmentOperationalStatusMapperIT {

  @Autowired
  private EquipmentOperationalStatusMapper mapper;

  @Test
  public void testGetAll() throws Exception {
    List<EquipmentOperationalStatus> statusList = mapper.getAll();
    assertEquals(3, statusList.size());
  }
}

Create an integration test for Equipment Operational Status Mapper


package com.warrenstrange.googleauth;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Date: 08/04/14
 * Time: 15:21
 *
 * @author Enrico M. Crisostomo
 */
class ReseedingSecureRandom {
    private static final int MAX_OPERATIONS = 1_000_000;
    private final String provider;
    private final String algorithm;
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    private final AtomicInteger count = new AtomicInteger(0);
    private SecureRandom secureRandom;

    ReseedingSecureRandom() {
        this.algorithm = null;
        this.provider = null;

        buildSecureRandom();
    }

    ReseedingSecureRandom(String algorithm) {
        if (algorithm == null) {
            throw new IllegalArgumentException("Algorithm cannot be null.");
        }

        this.algorithm = algorithm;
        this.provider = null;

        buildSecureRandom();
    }

    ReseedingSecureRandom(String algorithm, String provider) {
        if (algorithm == null) {
            throw new IllegalArgumentException("Algorithm cannot be null.");
        }

        if (provider == null) {
            throw new IllegalArgumentException("Provider cannot be null.");
        }

        this.algorithm = algorithm;
        this.provider = provider;

        buildSecureRandom();
    }

    private void buildSecureRandom() {
        try {
            System.out.println("Building secure random instance: " + count.get());
            if (this.algorithm == null && this.provider == null) {
                this.secureRandom = new SecureRandom();
            } else if (this.provider == null) {
                this.secureRandom = SecureRandom.getInstance(this.algorithm);
            } else {
                this.secureRandom = SecureRandom.getInstance(this.algorithm, this.provider);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new GoogleAuthenticatorException(
                    String.format(
                            "Could not initialise SecureRandom " +
                                    "with the specified algorithm: %s",
                            this.algorithm
                    ), e
            );
        } catch (NoSuchProviderException e) {
            throw new GoogleAuthenticatorException(
                    String.format(
                            "Could not initialise SecureRandom " +
                                    "with the specified provider: %s",
                            this.provider
                    ), e
            );
        }
    }

    void nextBytes(byte[] bytes) {
        readLock.lock();

        int currentCount = count.incrementAndGet();

        if (currentCount > MAX_OPERATIONS) {
            readLock.unlock();
            writeLock.lock();

            try {
                currentCount = count.get();

                if (currentCount > MAX_OPERATIONS) {
                    buildSecureRandom();
                    count.set(0);
                }

                readLock.lock();
            } finally {
                writeLock.unlock();
            }
        }

        try {
            this.secureRandom.nextBytes(bytes);
        } finally {
            readLock.unlock();
        }
    }
}

Add class wrapping a SecureRandom instance which is recreated after a certain number of operations are performed.


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Collapse;
import net.imglib2.RandomAccessible;
import net.imglib2.view.Views;
import net.imglib2.view.composite.CompositeView;
import net.imglib2.view.composite.GenericComposite;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.Collapse.class, name = ViewOps.Collapse.NAME)
public class DefaultCollapse2CompositeView<T>
		extends
		AbstractView<RandomAccessible<T>, CompositeView<T, ? extends GenericComposite<T>>>
		implements
		Collapse<RandomAccessible<T>, CompositeView<T, ? extends GenericComposite<T>>> {

	@Override
	public CompositeView<T, ? extends GenericComposite<T>> compute(
			RandomAccessible<T> input) {
		return Views.collapse(input);
	}

}

Add default implementation of Collapse to CompositeView.


package com.github.stephanenicolas.injectview;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

/**
 * These tests are really complex to setup.
 * Take your time for maintenance.
 * @author SNI
 */
@RunWith(InjectViewTestRunner.class)
@Config(manifest= Config.NONE)
public class InjectViewProcessorForViewsWithOtherTest {
  public static final String VIEW_TAG = "TAG";
  public static final String VIEW_TAG2 = "TAG2";
  public static final int VIEW_ID = 101;
  public static final int VIEW_ID2 = 102;

  private InjectViewProcessor processor = new InjectViewProcessor();

  @Test
  public void shouldInjectView_withId() {
    TestActivityWithId activity = Robolectric.buildActivity(TestActivityWithId.class)
        .create()
        .get();
    assertNotNull(activity.viewWithoutOnFinishInflate.text1);
    assertThat(activity.viewWithoutOnFinishInflate.text1.getId(), is(VIEW_ID));
  }

  public static class TestActivityWithId extends Activity {
    private TestViewWithIdWithoutOnFinishInflate viewWithoutOnFinishInflate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      LinearLayout layout = new LinearLayout(this);
      final TextView text1 = new TextView(this);
      text1.setId(VIEW_ID);
      layout.addView(text1);
      viewWithoutOnFinishInflate = new TestViewWithIdWithoutOnFinishInflate(layout);
      setContentView(layout);
    }

  }

  public static class TestViewWithIdWithoutOnFinishInflate {
    @InjectView(VIEW_ID)
    protected TextView text1;

    public TestViewWithIdWithoutOnFinishInflate(View view) {
      text1.setText("");
    }
  }

}

Add 1 test for other class with view injection


package com.google.sps.tasks;

import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsOutputChannel;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.nio.channels.Channels;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/tasks/prepareDownload")
public class PrepareDownload extends HttpServlet {
  WorkspaceFactory workspaceFactory = WorkspaceFactory.getInstance();

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String body = req.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

    String args[] = body.split(",");
    String workspaceID = args[0];
    String downloadID = args[1];

    Workspace w = workspaceFactory.fromWorkspaceID(workspaceID);

    GcsService instance = GcsServiceFactory.createGcsService();
    GcsFileOptions options = GcsFileOptions.getDefaultInstance();
    GcsFilename filename =
        new GcsFilename("fulfillment-deco-step-2020.appspot.com", workspaceID + '/' + downloadID);
    GcsOutputChannel outputChannel = instance.createOrReplace(filename, options);

    try {
      w.getArchive().archive(Channels.newOutputStream(outputChannel));

      w.updateDownloadURL(downloadID, filename.getObjectName());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Add a cloud task to upload an archive to gcs.


package us.kbase.workspace.listener;

import java.util.Map;

/** Doesn't have a zero argument constructor, and so fails to start.
 * @author gaprice@lbl.gov
 *
 */
public class BadListenerFactory implements WorkspaceEventListenerFactory {

	public BadListenerFactory(final int foo) {}

	@Override
	public WorkspaceEventListener configure(Map<String, String> cfg)
			throws ListenerInitializationException {
		return new BadListener();
	}

	public class BadListener implements WorkspaceEventListener {

		@Override
		public void createWorkspace(long id) {}

		@Override
		public void cloneWorkspace(long id) {}

	}

}

Add failing listener factory for testing purposes


package com.semperos.screwdriver.js;

import java.util.HashMap;

/**
 * @todo Steps needed:
 *   * Create generic {@link org.mozilla.javascript.ScriptableObject} class to handle
 *     properties used for RequireJS optimizer's config (see hardcoded-build.js).
 *   * For each needed build (determined by user-provided list of main JS modules to target),
 *     create unique instance of that object and set it's data accordingly (i.e., change values
 *     based on the config needs for each main JS module)
 *   * Add those objects to an array, say of __Screwdriver.rjsMainModules, which can then
 *     be iterated through in the evaluated JavaScript and passed to requirejs.optimize
 */
public class RequireJsConfigCompiler extends RhinoCompiler {
    private RhinoCompiler rhinoCompiler;

    public RequireJsConfigCompiler() {
        rhinoCompiler = new RhinoCompiler();
        HashMap<String,String> deps = new HashMap<String,String>();
        deps.put("r.js", "com/semperos/screwdriver/js/vendor/r-2.1.4.js");
        rhinoCompiler.addDependencies(deps);
    }

}

Add initial code for r.js via Rhino, include comments for next steps


package de.otto.jlineup.report;

import de.otto.jlineup.file.FileService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

import static java.util.Collections.singletonList;
import static org.mockito.MockitoAnnotations.initMocks;

public class JSONReportWriterV2Test {

    private JSONReportWriter_V2 testee;

    @Mock
    private FileService fileServiceMock;

    @Before
    public void setup() {
        initMocks(this);
        testee = new JSONReportWriter_V2(fileServiceMock);
    }

    @Test
    public void shouldWriteComparisonReportAsJson() throws Exception {

        ScreenshotComparisonResult screenshotComparisonResult =
                new ScreenshotComparisonResult("url", 1337, 1338, 0d, "before", "after", "differenceSum");
        Report report = new Report(new Summary(false, 0d, 0d), singletonList(screenshotComparisonResult));

        String expectedString = "{\n" +
                "  \"summary\": {\n" +
                "    \"error\": false,\n" +
                "    \"differenceSum\": 0.0,\n" +
                "    \"differenceMax\": 0.0\n" +
                "  },\n" +
                "  \"screenshotComparisons\": [\n" +
                "    {\n" +
                "      \"url\": \"url\",\n" +
                "      \"width\": 1337,\n" +
                "      \"verticalScrollPosition\": 1338,\n" +
                "      \"difference\": 0.0,\n" +
                "      \"screenshotBeforeFileName\": \"before\",\n" +
                "      \"screenshotAfterFileName\": \"after\",\n" +
                "      \"differenceImageFileName\": \"differenceSum\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        testee.writeComparisonReportAsJson(report);

        Mockito.verify(fileServiceMock).writeJsonReport(expectedString);
    }
}

Test for report format v2


/*
 * This file is part of whereisthat-android
 *
 * Unless otherwise stated in a separate LICENSE file for this project
 * or agreed via contract, all rights reserved by the author.
 */

package com.michael_kuck.android.mkcommons;

public class Version {

    final public static int MAJOR = 1;
    final public static int MINOR = 0;
    final public static int PATCH = 0;

}

Add class for tracking library version


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onosproject.vtnrsc.tenantnetwork;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.PhysicalNetwork;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for PhysicalNetwork class.
 */
public class PhysicalNetworkTest {

    final PhysicalNetwork physicalNetwork1 = PhysicalNetwork.physicalNetwork("1");
    final PhysicalNetwork sameAsPhysicalNetwork1 = PhysicalNetwork.physicalNetwork("1");
    final PhysicalNetwork physicalNetwork2 = PhysicalNetwork.physicalNetwork("2");

    /**
     * Checks that the PhysicalNetwork class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(PhysicalNetwork.class);
    }

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(physicalNetwork1, sameAsPhysicalNetwork1)
                .addEqualityGroup(physicalNetwork2).testEquals();
    }

    /**
     * Checks the construction of a PhysicalNetwork object.
     */
    @Test
    public void testConstruction() {
        final String physicalNetworkValue = "s";
        final PhysicalNetwork physicalNetwork = PhysicalNetwork
                .physicalNetwork(physicalNetworkValue);
        assertThat(physicalNetwork, is(notNullValue()));
        assertThat(physicalNetwork.physicalNetwork(), is(physicalNetworkValue));
    }
}

Add the junit test code of PhysicalNetwork


package ru.ifmo.nds;

import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class RunGivenTest {
    public static void main(String[] args) {
        Locale.setDefault(Locale.US);
        try (Scanner in = new Scanner(System.in)) {
            int n = in.nextInt();
            int d = in.nextInt();
            double[][] data = new double[n][d];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < d; ++j) {
                    data[i][j] = in.nextDouble();
                }
            }
            int[] ranks = new int[n];
            int[] referenceRanks = new int[n];
            boolean set = false;
            String referenceAlgo = null;
            for (String s : IdCollection.getAllNonDominatedSortingIDs()) {
                Arrays.fill(ranks, -1);
                NonDominatedSorting sorting = IdCollection.getNonDominatedSortingFactory(s).getInstance(n, d);
                sorting.sort(data, ranks);
                if (set) {
                    if (!Arrays.equals(referenceRanks, ranks)) {
                        System.out.println("Ranks different for " + s + " and " + referenceAlgo);
                    }
                } else {
                    set = true;
                    referenceAlgo = s;
                    System.arraycopy(ranks, 0, referenceRanks, 0, n);
                }
                System.out.println(s + " seems to be OK, rank[0] = " + ranks[0]);
            }
        }
    }
}

Add a main class that runs a test given from the console on all algos.


package ru.stqa.selenium.example;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.pagefactory.ByAll;

public class correctProduct extends TestBase {
    @Test
    public void correctProduct() {
        driver.get("http://localhost/litecart/en/");

        WebElement campaignsBlock = driver.findElement(By.id("box-campaigns"));
        String nameOfProduct1 = campaignsBlock.findElement(By.className("name")).getText();

        WebElement prices = campaignsBlock.findElement(By.className("price-wrapper"));
        String regularPrice1 = prices.findElement(By.className("regular-price")).getText();
        String campaignPrice1 = prices.findElement(By.className("campaign-price")).getText();

        campaignsBlock.findElement(By.className("link")).click();

        campaignsBlock = driver.findElement(By.id("box-product"));
        String nameOfProduct2 = campaignsBlock.findElement(By.className("title")).getText();

        prices = campaignsBlock.findElement(By.className("price-wrapper"));
        String regularPrice2 = prices.findElement(By.className("regular-price")).getText();
        String campaignPrice2 = prices.findElement(By.className("campaign-price")).getText();

        System.out.println(nameOfProduct1 + " = " + nameOfProduct2);
        System.out.println(regularPrice1 + " = " + regularPrice2);
        System.out.println(campaignPrice1 + " = " + campaignPrice2);
    }
}

Create file for the task №10. Done the task №10 (a,b)


package com.ezardlabs.dethsquare.multiplayer;

import java.nio.ByteBuffer;

public class NetworkAnimator extends NetworkBehaviour {

	@Override
	protected ByteBuffer onSend() {
		data.putInt(0, gameObject.animator.getCurrentAnimationId()); // 0 - 3
		data.putInt(4, gameObject.animator.getCurrentAnimationFrame()); // 4 - 7
		return data;
	}

	@Override
	protected void onReceive(ByteBuffer data, int index) {
		gameObject.animator.setCurrentAnimationId(data.getInt(index));
		gameObject.animator.setCurrentAnimationFrame(data.getInt(index + 4));
	}

	@Override
	public int getSize() {
		return 8;
	}
}

Add component for automatically synchronising an Animator component between multiplayer clients


/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.tomcat.util.http;

import org.junit.Test;

public class TestFastHttpDateFormatPerformance {

    @Test
    public void testGetCurrentDateConcurrent() throws InterruptedException {
        int threadCount = 8;
        int callCount = 100000000;
        Thread[] threads = new Thread[threadCount];

        for (int i = 0; i < threadCount; i++) {
            threads[i] = new GetCurrentDateThread(callCount);
        }

        long startTime = System.nanoTime();

        for (int i = 0; i < threadCount; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threadCount; i++) {
            threads[i].join();
        }

        long endTime = System.nanoTime();

        System.out.println("Duration: " + (endTime - startTime));
    }

    private static class GetCurrentDateThread extends Thread {

        private final int callCount;

        public GetCurrentDateThread(int callCount) {
            this.callCount = callCount;
        }

        @Override
        public void run() {
            for (int i = 0; i < callCount; i++) {
                FastHttpDateFormat.getCurrentDate();
            }
        }
    }
}

Add a test to use to check for performance changes during refactoring of data formatting.


package org.hollowcraft.model;
/*
 * HollowCraft License
 *  Copyright (c) 2010 Caleb Champlin.
 *  All rights reserved
 *  This license must be include in all copied, cloned and derived works
 */

/**
 * A class which holds block id constants.
 * @author Caleb Champlin
 */
public class BlockActions {
	private BlockActions() { }
	public static final int DESTROY = 0;
	public static final int BUILD = 1;
}

Add a constants class for block actions (atm only two: destory and build)


/*
 * Licensed to the University of California, Berkeley under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License. You may obtain a
 * copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package tachyon.master.block;

import org.powermock.reflect.Whitebox;

import tachyon.collections.IndexedSet;
import tachyon.master.block.meta.MasterWorkerInfo;

/**
 * Class which provides access to private state of {@link BlockMaster}.
 */
public final class BlockMasterPrivateAccess {
  public static boolean isWorkerRegistered(BlockMaster master, long workerId) {
    IndexedSet<MasterWorkerInfo> workers = Whitebox.getInternalState(master, "mWorkers");
    IndexedSet.FieldIndex<MasterWorkerInfo> idIndex = Whitebox.getInternalState(master, "mIdIndex");
    if (workers == null || idIndex == null) {
      return false;
    }
    synchronized (workers) {
      MasterWorkerInfo workerInfo = workers.getFirstByField(idIndex, workerId);
      return workerInfo != null && workerInfo.isRegistered();
    }
  }
}

Add private access for BlockMaster


// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.acceptance.rest.group;

import static com.google.gerrit.acceptance.rest.group.GroupAssert.assertGroupInfo;

import com.google.common.reflect.TypeToken;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.AccountCreator;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.acceptance.RestSession;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.account.GroupCache;
import com.google.gson.Gson;
import com.google.inject.Inject;

import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class GetGroupIT extends AbstractDaemonTest {

  @Inject
  private AccountCreator accounts;

  @Inject
  private GroupCache groupCache;

  private TestAccount admin;
  private RestSession session;

  @Before
  public void setUp() throws Exception {
    admin = accounts.create("admin", "admin@example.com", "Administrator",
            "Administrators");
    session = new RestSession(admin);
  }

  @Test
  public void testGetGroup() throws IOException {
    AccountGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators"));

    // by UUID
    testGetGroup("/groups/" + adminGroup.getGroupUUID().get(), adminGroup);

    // by name
    testGetGroup("/groups/" + adminGroup.getName(), adminGroup);

    // by legacy numeric ID
    testGetGroup("/groups/" + adminGroup.getId().get(), adminGroup);
  }

  private void testGetGroup(String url, AccountGroup expectedGroup) throws IOException {
    RestResponse r = session.get(url);
    @SuppressWarnings("serial")
    GroupInfo group = (new Gson()).fromJson(r.getReader(), new TypeToken<GroupInfo>() {}.getType());
    assertGroupInfo(expectedGroup, group);
  }
}

Add acceptance test to retrieve group via REST


package de.philipphager.disclosure.database;

import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import javax.inject.Inject;
import rx.schedulers.Schedulers;

public class DatabaseManager {
  private final DatabaseOpenHelper openHelper;
  private final SqlBrite sqlBrite;
  private BriteDatabase database;

  @Inject public DatabaseManager(DatabaseOpenHelper openHelper, SqlBrite sqlBrite) {
    this.openHelper = openHelper;
    this.sqlBrite = sqlBrite;
  }

  public synchronized BriteDatabase open() {
    ensureDatabase();
    return database;
  }

  public synchronized void close() {
    if (database != null) {
      database.close();
      database = null;
    }
  }

  private void ensureDatabase() {
    if (database == null) {
      database = sqlBrite.wrapDatabaseHelper(openHelper, Schedulers.io());
      ;
    }
  }
}

Add a database manager to manage database instances.


//
// BackReferenceTest.java
//

/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.formats.utests.xml;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

import java.io.IOException;
import java.io.InputStream;

import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.services.OMEXMLService;

import ome.xml.model.OME;
import ome.xml.model.Plate;
import ome.xml.model.Well;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 *

Source code:

 *
Trac,
 * Gitweb

 *
 * @author Melissa Linkert melissa at glencoesoftware.com
 */
public class BackReferenceTest {

  private OMEXMLService service;
  private OMEXMLMetadata metadata;

  @BeforeMethod
  public void setUp() throws DependencyException, ServiceException, IOException
  {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    metadata = service.createOMEXMLMetadata();
  }

  @Test
  public void testPlateWellReferences() {
    metadata.setPlateID("Plate:0", 0);
    metadata.setWellID("Well:0:0", 0, 0);

    OME root = (OME) metadata.getRoot();

    Plate plate = root.getPlate(0);
    Well well = plate.getWell(0);

    assertNotNull(plate);
    assertNotNull(well);
    assertEquals(plate, well.getPlate());
  }

}

Add one back reference test


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

import org.junit.Before;
import org.junit.Test;

/**
 * JUnit test for Request class.
 *
 * @author wscott
 *
 */
public class RequestTest {

    private Request request;

    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);
    private static final ArrayList<Param> PARAMS = new ArrayList<Param>(0);
    private static final ArrayList<Representation> REPRESENTATIONS = new ArrayList<Representation>(0);

    @Before
    public void setup() throws Exception {
        request = new Request(DOC, PARAMS, REPRESENTATIONS);
    }

    @Test
    public void testNullParams() {
        new Request(DOC, null, REPRESENTATIONS);
    }

    @Test
    public void testNullRepresentations() {
        new Request(DOC, PARAMS, null);
    }

    @Test
    public void testGetParams() {
        assertEquals(PARAMS, request.getParams());
    }

    @Test
    public void testGetRepresentations() {
        assertEquals(REPRESENTATIONS, request.getRepresentations());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(request.toString()));
    }
}

Add JUnit test for Request class in rest modeling module.


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.apache.jmeter.report.processor;

import junit.framework.TestCase;

import org.apache.jmeter.report.core.Sample;
import org.apache.jmeter.report.core.SampleMetadata;
import org.junit.Test;

public class FieldSampleComparatorTest extends TestCase {

    private SampleMetadata sampleMetadata;
    private FieldSampleComparator comparator;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        sampleMetadata = new SampleMetadata(',', "test");
        comparator = new FieldSampleComparator("test");
        comparator.initialize(sampleMetadata);
    }

    @Test
    public void testCompare() {
        Sample s1 = new Sample(0, sampleMetadata, "1");
        Sample s2 = new Sample(1, sampleMetadata, "2");
        assertTrue(comparator.compare(s1, s2) < 0);
        assertTrue(comparator.compare(s2, s1) > 0);
        assertTrue(comparator.compare(s2, s2) == 0);
        assertTrue(comparator.compare(s1, s1) == 0);
    }

}

Use simple test case for FieldSampleComparator.


package edu.iastate.cs.design.spec.export;

import boa.types.Spec;

import java.util.List;

public class JmlToBoa {

    public static List<Spec.Specification> JmlToBoaProtobuf(String jml) {
        // TODO
        return null;
    }

}

Add skeleton class for exporting Boa specs


/**
 * Twist in the Tale 4.3 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 1/3/14.
 */
public class TwistInTheTale4_3 {
    public static void main(String[] args) {
        String multiStrArr[][] = new String[][] {
                {"A", "B"},
                null,
                {"Jan", "Feb", null}
        };

        System.out.println(multiStrArr[2][2]);
//        System.out.println(multiStrArr[1][1]);

        for (int i = 0; i < multiStrArr.length; i++) {
            if (multiStrArr[i] == null) { System.out.println("length:null\tnull"); continue; }

            System.out.print("length:" + multiStrArr[i].length + "\t");
            for (int j = 0; j < multiStrArr[i].length; j++) {
                System.out.print(multiStrArr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Add code for Twist In The Tale 4.3


/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fuzz.indicator.text;

import android.support.annotation.NonNull;

/**
 * These are designed to be translated (in a 2-dimensional plane) above
 * their associated {@link android.text.Spannable Spannables}.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public interface MigratorySpan {

    /**
     * Consider a Spannable sequence has a lower bound at 0% of its length
     * and upper bound at 100% of that length. The MigratoryRange returned
     * by this method represents some portion of indices within that sequence.
     *

     *     Sample caller code may be as follows:
     *

     *         MigratorySpan ms;
     *         //...
     *         Range<Float> bounds = ms.getCoverage();
     *         String percentLower = String.format("%0.2f", bounds.getLower()/100);
     *         String percentUpper = String.format("%0.2f", bounds.getUpper()/100);
     *

     *

     *
     * @return a range which can be used to figure out what
     * percentages of the Spannable is covered.
     */
    @NonNull
    MigratoryRange<Float> getCoverage();

    /**
     * Whatever is returned here should be a valid argument into
     * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s
     * {@code flags} argument. Feel free to return the parameter directly
     * if they don't need to change.
     *
     * @return a combination of valid span-laying-out flags
     * @param previousFlags    flags used for the previous layout - will
     *                         be 0 if not currently attached to a
     *                         {@link android.text.Spannable Spannable}
     */
    int preferredFlags(int previousFlags);
}

Create dedicated interface for Migratory spans


package arithlang;

public interface Value {
	public String toString();
	static class NumVal implements Value {
		private double _val;
	    public NumVal(double v) { _val = v; }
	    public double v() { return _val; }
	    public String toString() {
	    	int tmp = (int) _val;
	    	if(tmp == _val) return "" + tmp;
	    	return "" + _val;
	    }
	}
}

Set of values for Arithlang


package com.googlecode.gentyref;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

/**
 * Sample in the form of a JUnit test, to show gentyref solves the problem on
 * http://stackoverflow.com/questions/182872/
 *
 * @author Wouter Coekaerts <wouter@coekaerts.be>
 */
public class StackoverflowQ182872Test extends TestCase {
	private static Type LIST_OF_STRING = new TypeToken<List<String>>(){}.getType();

	public static class StringList extends ArrayList<String> {}

	public List<String> method1() {return null;}
	public ArrayList<String> method2() {return null;}
	public StringList method3() {return null;}
	interface Parameterized<T extends StringList> {
		T method4();
	}
	interface Parameterized2<T> {
		T method5();
	}
	interface Parameterized2ListString extends Parameterized2<List<String>> {
	}

	public boolean returnTypeExtendsListOfString(Class<?> clazz, String methodName) throws NoSuchMethodException {
		Method method = clazz.getMethod(methodName);
		Type returnType = GenericTypeReflector.getExactReturnType(method, clazz); // needed for method5, else the return type is just "T"
		return GenericTypeReflector.isSuperType(LIST_OF_STRING, returnType);
	}

	public void testIt() throws NoSuchMethodException {
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method1"));
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method2"));
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method3"));
		assertTrue(returnTypeExtendsListOfString(Parameterized.class, "method4"));
		assertTrue(returnTypeExtendsListOfString(Parameterized2ListString.class, "method5"));
	}
}

Add test sample for question 182872 on stackoverflow.com


import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.gson.Gson;
package com.google.sps;
import com.google.sps.data.Fields;
import com.google.sps.data.Video;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

// Servlet for testing queries.
@WebServlet("/data")
public class DataServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        return;
    }

      @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Video video = requestToVideoObject(request);
        Entity videoEntity = videoToEntity(video);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(videoEntity);
        response.sendRedirect("/");
    }

    public Video requestToVideoObject(HttpServletRequest request){
        // Get the input from the form.
        String videoId = request.getParameter(Fields.VIDEO_ID);
        // Extra fields in form for metadata until we can fetch them.
        String title = request.getParameter(Fields.TITLE);
        String description = request.getParameter(Fields.DESCRIPTION);
        String captions = request.getParameter(Fields.CAPTIONS);
        Video video = new Video(videoId, title, description, captions);
        return video;
    }

    public Entity videoToEntity(Video video){
        Entity videoEntity = new Entity("Video");
        videoEntity.setProperty("videoId", video.getVideoId());
        videoEntity.setProperty("videoObjectAsJSON", new Gson().toJson(video));
        return videoEntity;
    }
}

Add Data Servlet, handles putting video data into DataStore


/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.testing.logging;

import com.google.common.truth.ObjectArraySubject;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.Extension;

import static com.google.common.truth.Truth.assertThat;

@DisplayName("@MuteLogging should")
class MuteLoggingTest {

    @Test
    @DisplayName("be marked as an extension")
    void annotated() {
        Class<MuteLogging> annotation = MuteLogging.class;
        ExtendWith extendsWith = annotation.getAnnotation(ExtendWith.class);
        Class<? extends Extension>[] extensions = extendsWith.value();
        ObjectArraySubject<Class<? extends Extension>> assertExtensions = assertThat(extensions);
        assertExtensions.hasLength(1);
        assertExtensions.asList().contains(MuteLoggingExtension.class);
    }
}

Add a test for `MuteLogging`.


/*
 * $Log: JmsRealmsFactory.java,v $
 * Revision 1.1  2007-10-23 09:18:28  europe\M00035F
 * Add Digester-Factory for the JmsRealmFactory object to retrieve it from spring beans factory instead of old helper-bean-object.
 *
 * Created on 23-okt-07
 *
 */
package nl.nn.adapterframework.configuration;

/**
 * Factory for the JMS Realms instance, which holds all JMS Realm definitions
 * found in the Configuration File.
 *
 * This bean is a singleton, not a prototype, which is why the GenericFactory
 * can not be used.
 *
 * @author Tim van der Leeuw
 * @version Id
 *
 */
public class JmsRealmsFactory extends AbstractSpringPoweredDigesterFactory {

    /* (non-Javadoc)
     * @see nl.nn.adapterframework.configuration.AbstractSpringPoweredDigesterFactory#getBeanName()
     */
    public String getBeanName() {
        return "jmsRealmsFactory";
    }

    /* (non-Javadoc)
     * @see nl.nn.adapterframework.configuration.AbstractSpringPoweredDigesterFactory#isPrototypesOnly()
     */
    public boolean isPrototypesOnly() {
        return false;
    }

}


/******************************************************************************
 *                                                                            *
 *                    Copyright 2018 Subterranean Security                    *
 *                                                                            *
 *  Licensed under the Apache License, Version 2.0 (the "License");           *
 *  you may not use this file except in compliance with the License.          *
 *  You may obtain a copy of the License at                                   *
 *                                                                            *
 *      http://www.apache.org/licenses/LICENSE-2.0                            *
 *                                                                            *
 *  Unless required by applicable law or agreed to in writing, software       *
 *  distributed under the License is distributed on an "AS IS" BASIS,         *
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 *  See the License for the specific language governing permissions and       *
 *  limitations under the License.                                            *
 *                                                                            *
 *****************************************************************************/
package com.sandpolis.core.instance.storage.converter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import com.sandpolis.core.proto.util.Platform.Instance;

/**
 * When used on a persistent {@link Instance} field, this converter makes
 * database operations much more efficient by replacing {@link Instance}s with
 * their numeric identifier.
 *
 * @author cilki
 * @since 5.0.0
 */
@Converter
public class InstanceConverter implements AttributeConverter<Instance, Integer> {

	@Override
	public Integer convertToDatabaseColumn(Instance instance) {
		return instance.getNumber();
	}

	@Override
	public Instance convertToEntityAttribute(Integer dbData) {
		return Instance.forNumber(dbData);
	}

}

Add JPA Converter so Instance types can be persisted cleanly


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.test.escaping.framework;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.apache.http.entity.ContentType;

public class URLContent
{
    private ContentType type;

    private byte[] content;

    public URLContent(String typeHeader, byte[] content)
    {
        this.type = typeHeader != null ? ContentType.parse(typeHeader) : null;
        this.content = content;
    }

    public ContentType getType()
    {
        return this.type;
    }

    public byte[] getContent()
    {
        return this.content;
    }

    public Reader getContentReader()
    {
        Charset charset;
        if (this.type != null && this.type.getCharset() != null) {
            charset = this.type.getCharset();
        } else {
            charset = StandardCharsets.UTF_8;
        }

        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(getContent()), charset));
    }
}

Add class missing in previous commit


package com.twu.biblioteca;

import java.util.Scanner;

public class InputReader {

    String readFromConsole() {
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.next();
        return inputString;
    }
}

Implement an Input Reader which takes input from user


package ca.antonious.viewcelladapter;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by George on 2016-12-18.
 */

public class ListenerCollectionTests {
    private RegisteredListener registeredListener;
    private ListenerCollection listenerCollection;

    @Before
    public void set_up() {
        registeredListener = new RegisteredListener() {
            @Override
            public void listen() {

            }
        };

        listenerCollection = new ListenerCollection();
        listenerCollection.addListener(registeredListener);
    }

    @Test
    public void test_getListener_ifListenerIsRegistered_returnsInstanceOfListener() {
        Object expectedListener = registeredListener;
        Object actualListener = listenerCollection.getListener(RegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    @Test
    public void test_getListener_ifListenerIsNotRegistered_returnsNull() {
        Object expectedListener = null;
        Object actualListener = listenerCollection.getListener(NotRegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    @Test
    public void test_removeListener_removesListener() {
        listenerCollection.removeListener(registeredListener);

        Object expectedListener = null;
        Object actualListener = listenerCollection.getListener(RegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    public interface RegisteredListener {
        void listen();
    }

    public interface NotRegisteredListener {
        void listen();
    }
}

Add tests for the ListenerCollection


package org.sagebionetworks.profiler;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;

/**
 * Test for Frame.
 *
 */
public class FrameTest {

	Frame root = null;

	@Before
	public void before(){
		// Create a frame that is a few levels deep
		root = new Frame(0, "root");
		root.setEnd(12);
		// Add some children
		for(int i=0; i<4; i++){
			Frame child = new Frame(i, "child"+1);
			child.setEnd(i+1);
			root.addChild(child);
			// Add one more level
			for(int j=0; j<2; j++){
				Frame grand = new Frame(i, "grand"+j);
				grand.setEnd(i);
				child.addChild(grand);
			}
		}
	}

	/**
	 * @throws JSONException
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 *
	 */
	@Test
	public void testJSONRoundTrip() throws JSONException {
		// Write it to json
		String json = Frame.writeFrameJSON(root);
		assertNotNull(json);
		System.out.println(json);
		// Now convert back to Frames
		Frame cloneRoot = Frame.readFrameFromJSON(json);
		assertNotNull(cloneRoot);
		assertEquals(root, cloneRoot);
	}
}

Move the unit tests of the profiler package to logging