/*
 * Copyright 2006 The Apache Software Foundation.
 *
 * 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.apache.jorphan.math;

/**
 * Class to calculate various items that don't require all previous results to be saved:
 * - mean = average
 * - standard deviation
 * - minimum
 * - maximum
 */
public class Calculator {

	private double sum = 0;

	private double sumOfSquares = 0;

	private double mean = 0;

	private double deviation = 0;

	private int count = 0;

	private long bytes = 0;

	private long maximum = Long.MIN_VALUE;

	private long minimum = Long.MAX_VALUE;

	public void clear() {
		maximum = Long.MIN_VALUE;
		minimum = Long.MAX_VALUE;
		sum = 0;
		sumOfSquares = 0;
		mean = 0;
		deviation = 0;
		count = 0;
	}

	public void addValue(long newValue) {
		count++;
		minimum=Math.min(newValue, minimum);
		maximum=Math.max(newValue, maximum);
		double currentVal = newValue;
		sum += currentVal;
		sumOfSquares += currentVal * currentVal;
		// Calculate each time, as likely to be called for each add
		mean = sum / count;
		deviation = Math.sqrt((sumOfSquares / count) - (mean * mean));
	}

	public void addBytes(long newValue) {
		bytes += newValue;
	}

	public long getTotalBytes() {
		return bytes;
	}

	public double getMean() {
		return mean;
	}

	public double getStandardDeviation() {
		return deviation;
	}

	public long getMin() {
		return minimum;
	}

	public long getMax() {
		return maximum;
	}

	public int getCount() {
		return count;
	}
}

Add cheaper calculator (no need to save results)


package replicant;

import java.util.HashMap;
import javax.annotation.Nonnull;

public class TestEntityChangeData
  implements EntityChangeData
{
  private final HashMap<String, Object> _data = new HashMap<>();

  public HashMap<String, Object> getData()
  {
    return _data;
  }

  @Override
  public boolean containsKey( @Nonnull final String key )
  {
    return _data.containsKey( key );
  }

  @Override
  public boolean isNull( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return null == _data.get( key );
  }

  @Override
  public int getIntegerValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (int) _data.get( key );
  }

  @Nonnull
  @Override
  public String getStringValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (String) _data.get( key );
  }

  @Override
  public boolean getBooleanValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (Boolean) _data.get( key );
  }
}

Add EntityChangeData implementation used for testing


package com.aemreunal.controller;

/*
 ***************************
 * Copyright (c) 2014      *
 *                         *
 * This code belongs to:   *
 *                         *
 * @author Ahmet Emre Ünal *
 * S001974                 *
 *                         *
 * aemreunal@gmail.com     *
 * emre.unal@ozu.edu.tr    *
 *                         *
 * aemreunal.com           *
 ***************************
 */

import org.junit.Test;
import org.springframework.security.crypto.codec.Base64;

public class GenAuth {
    @Test
    public void generateAuth() {
        String auth = "adminr:password";
        byte[] encodedAuthorisation = Base64.encode(auth.getBytes());
        System.out.println("Basic " + new String(encodedAuthorisation));
    }
}

Add OAuth token generating test


/*
 * Java core library component.
 *
 * Copyright (c) 1999
 *	Archie L. Cobbs.  All rights reserved.
 * Copyright (c) 1999
 *	Transvirtual Technologies, Inc.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file.
 *
 * Author: Archie L. Cobbs <archie@whistle.com>
 */

package java.net;

import java.io.IOException;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.SecureClassLoader;
import java.util.Enumeration;
import java.util.Vector;
import java.util.jar.Manifest;

// XXX this class is not complete!

public class URLClassLoader extends SecureClassLoader {
	final Vector urls;
	final ClassLoader parent;

	public URLClassLoader(URL[] urls, ClassLoader parent) {
		this(urls, parent, null);
	}

	public URLClassLoader(URL[] urls) {
		this(urls, URLClassLoader.class.getClassLoader(), null);
	}

	public URLClassLoader(URL[] urls, ClassLoader parent,
			URLStreamHandlerFactory factory) {
		this.urls = new Vector();
		for (int i = 0; i < urls.length; i++) {
			this.urls.addElement(urls[i]);
		}
		this.parent = parent;
	}

	protected void addURL(URL url) {
		urls.addElement(url);
	}

	public URL[] getURLs() {
		return (URL[])urls.toArray(new URL[urls.size()]);
	}

	//protected Class findClass(String name) throws ClassNotFoundException {
	//}

	protected Package definePackage(String name, Manifest man, URL url)
			throws IllegalArgumentException {
		return super.definePackage(name, "", "", "", "", "", "", url);
	}

	//public URL findResource(String name) {
	//}

	//public Enumeration findResources(String name) throws IOException {
	//}

	protected PermissionCollection getPermissions(CodeSource codesource) {
		return null;
	}

	public static URLClassLoader newInstance(URL[] urls,
			ClassLoader parent) {
		return new URLClassLoader(urls, parent);
	}

	public static URLClassLoader newInstance(URL[] urls) {
		return new URLClassLoader(urls);
	}
}

Add missing class (mostly unimplemented).


package org.krugler.yalder;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.krugler.yalder.hash.HashLanguageModel;
import org.krugler.yalder.text.TextLanguageModel;

public class ModelLoader {

    public static Collection<BaseLanguageModel> loadModelsFromResources() {
        // TODO use language-detector code to find/load resources
        return null;
    }

    public static Collection<BaseLanguageModel> loadModelsFromDirectory(File dirFile, boolean isBinary) throws IOException {
        Set<BaseLanguageModel> result = new HashSet<>();

        String modelSuffix = isBinary ? "bin" : "txt";
        for (File file : FileUtils.listFiles(dirFile, new String[]{modelSuffix}, true)) {
            String filename = file.getName();
            Pattern p = Pattern.compile(String.format("yalder_model_(.+).%s", modelSuffix));
            Matcher m = p.matcher(filename);
            if (!m.matches()) {
                continue;
            }

            // Verify that language is valid
            LanguageLocale.fromString(m.group(1));

            if (isBinary) {
                try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
                    HashLanguageModel binaryModel = new HashLanguageModel();
                    binaryModel.readAsBinary(dis);
                    result.add(binaryModel);
                }
            } else {
                try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
                    TextLanguageModel textModel = new TextLanguageModel();
                    textModel.readAsText(isr);
                    result.add(textModel);
                }
            }
        }

        return result;
    }
}

Add first cut at model loader


package leetcode.palindrome_partitioning_ii;

public class Solution {

	public void buildTable(char[] charAry, int[] table){
		int L = 0, R = -1, C = 0;
		int len = charAry.length;
		for(int i = 0; i < len * 2 - 1; i++){
			int ref = 2 * C - i;
			if(i > R || ref - table[ref] + 1 <= L){
				int rad;
				int minrad = i > R ? 1 : R - i + 1;
				if(minrad > len * 2 - i) minrad = len * 2 - i;
				C = i;
				for(rad = minrad; i - rad + 1 >= 0 && i + rad - 1 < len * 2 - 1; rad++){
					int l = i - rad + 1, r = i + rad - 1;
					if(l % 2 == 1 || charAry[l / 2] == charAry[r / 2]){
						table[i] = rad;
						R = i + rad - 1;
						L = i - rad + 1;
					}else{
						break;
					}
				}
			}else{
				table[i] = table[ref];
			}
		}
		for(int i = 0; i < len * 2 - 1; i++){
			if(i % 2 == 0){
				table[i] = (table[i] - 1) / 2 * 2 + 1;
			}else{
				table[i] = table[i] / 2 * 2;
			}
		}
	}

    public int minCut(String s) {
    	if(s.length() == 0) return 0;
    	int[] maxPalinTable = new int[s.length() * 2 - 1];
    	buildTable(s.toCharArray(), maxPalinTable);
    	int[] cut = new int[s.length() + 1];
    	for(int i = 0; i < s.length() * 2 - 1; i++){
    		int palinLength = maxPalinTable[i];
    		int jumpStart = i / 2 - (palinLength + 1) / 2 + 1;
    		int jumpEnd = i / 2;
    		for(int j = jumpStart; j <= jumpEnd; j++){
    			int jumpLength = palinLength + jumpStart * 2 - j * 2;
    			if(cut[j + jumpLength] == 0 || cut[j + jumpLength] > cut[j] + 1){
    				cut[j + jumpLength] = cut[j] + 1;
    			}
    		}
    	}
    	return cut[s.length()] - 1;
    }

	public static void main(String[] args){
		System.err.println(new Solution().minCut("a"));
	}
}

Add java solution for 132. Palindrome Partitioning II


package com.pturpin.quickcheck.generator;

import java.math.BigDecimal;
import java.math.BigInteger;

import static com.google.common.base.Preconditions.checkArgument;

public class Numbers {

    public static Generator<Integer> integerGen() {
        return integerGen(Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public static Generator<Integer> integerGen(int min, int max) {
        checkArgument(max > min);
        return re -> re.nextInt() % (max - min) + min;
    }

    public static Generator<Long> longGen() {
        return longGen(Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public static Generator<Long> longGen(long min, long max) {
        checkArgument(max > min);
        return re -> re.nextLong() % (max - min) + min;
    }

    public static Generator<Float> floatGen() {
        return floatGen(-Float.MAX_VALUE, Float.MAX_VALUE);
    }

    public static Generator<Float> floatGen(float min, float max) {
        checkArgument(max > min);
        return re -> re.nextFloat() * (max - min) + min; // FIXME handle overflow
    }

    public static Generator<Double> doubleGen() {
        return doubleGen(-Double.MAX_VALUE, Double.MAX_VALUE);
    }

    public static Generator<Double> doubleGen(double min, double max) {
        checkArgument(max > min);
        return re -> re.nextDouble() * (max - min) + min;  // FIXME handle overflow
    }

    public static Generator<Double> specialDouble() {
        return Generators.oneOf(Double.MIN_VALUE, Double.MAX_VALUE,
                Double.MIN_NORMAL, Double.NaN, 0.d, -0.d,
                Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
    }

    public static Generator<BigInteger> bigIntegerGen(BigInteger min, BigInteger max) {
        checkArgument(max.compareTo(min) > 0);
        BigInteger delta = max.subtract(min);

        int deltaNumBits = delta.bitCount();
        Generator<Integer> numBitsGen = integerGen(0, deltaNumBits);

        return re -> {
            BigInteger generated = new BigInteger(numBitsGen.get(re), re);
            return generated.remainder(delta).add(min);
        };
    }

    public static Generator<BigDecimal> bigDecimalGen(BigDecimal min, BigDecimal max) {
        checkArgument(max.compareTo(min) > 0);

        BigInteger minInt = min.unscaledValue();
        BigInteger maxInt = max.unscaledValue();
        Generator<BigInteger> bigIntGen = bigIntegerGen(minInt, maxInt);

        int minScale = min.scale();
        int maxScale = max.scale();
        Generator<Integer> scaleGen = integerGen(minScale, maxScale);

        BigDecimal delta = max.subtract(min);

        return re -> {
            BigDecimal generated = new BigDecimal(bigIntGen.get(re), scaleGen.get(re));
            return generated.remainder(delta).add(min);
        };
    }
}

Create basic implementations (lambda) of numbers generators


package com.darwinsys.todo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.pobox.cbarham.testhelpers.EqualsHashCodeTestCase;

public class TaskEqualsHashcodeTest extends EqualsHashCodeTestCase {

	@Override
	protected App createInstance() throws Exception {
		return new Task("Get Stuff Done");
	}

	@Override
	protected App createNotEqualInstance() throws Exception {
		return new App("Get MORE stuff done!");
	}

	@Test
	public void testAssertTrue() {
		assertTrue(true);
	}
}

Test our Equals method a bit


package de.gurkenlabs.litiengine.entities;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

import de.gurkenlabs.litiengine.annotation.Action;

public class EntityTests {

  @Test
  public void testEntityAction() {
    TestEntity entity = new TestEntity();

    assertTrue(entity.actions().exists("doSomething"));

    EntityAction action = entity.actions().get("doSomething");

    assertNotNull(action);

    action.perform();

    assertTrue(entity.didSomething);
  }

  @Test
  public void testNamedAction() {
    TestEntity entity = new TestEntity();

    assertTrue(entity.actions().exists("myName"));

    EntityAction action = entity.actions().get("myName");

    assertNotNull(action);

    action.perform();

    assertTrue(entity.didNamedAction);
  }

  @Test
  public void testCustomAction() {
    Entity entity = new TestEntity();
    entity.register("customAction", () -> {
      return;
    });

    assertTrue(entity.actions().exists("customAction"));

    entity.actions().unregister("customAction");

    assertFalse(entity.actions().exists("customAction"));
  }

  private class TestEntity extends Entity {
    private boolean didSomething;
    private boolean didNamedAction;

    @Action(description = "does something")
    public void doSomething() {
      didSomething = true;
    }

    @Action(name = "myName")
    public void namedAction() {
      didNamedAction = true;
    }
  }
}

Add some test cases for entity actions.


package net.imagej.ops.views;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ZeroMin;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ZeroMin.class, name = ViewOps.ZeroMin.NAME)
public class DefaultZeroMin<T> extends
		AbstractView<RandomAccessibleInterval<T>, IntervalView<T>> implements
		ZeroMin<RandomAccessibleInterval<T>, IntervalView<T>> {

	@Override
	public IntervalView<T> compute(RandomAccessibleInterval<T> input) {
		return Views.zeroMin(input);
	}

}

Add default implementation of ZeroMin interface.


package leetcode.reverse_nodes_in_k_group;

import common.ListNode;

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || k <= 1) return head;

        ListNode prev = null;
        while(true){
        	ListNode groupHead;
        	if(prev == null){
        		groupHead = head;
        	}else{
        		groupHead = prev.next;
        	}
        	if(groupHead == null) return head;
        	ListNode groupTail = groupHead;
        	int steps;
        	for(steps = 0; steps < k - 1 && groupTail.next != null; steps++){
        		groupTail = groupTail.next;
        	}
        	if(steps < k - 1) return head;
        	else{
        		ListNode groupNext = groupHead.next;
        		ListNode groupPrev = groupHead;
        		for(int i = 0; i < k - 1; i++){
        			ListNode groupTmp = groupNext.next;
        			groupNext.next = groupHead;
        			groupPrev.next = groupTmp;
        			groupHead = groupNext;
        			groupTail = groupPrev;
        			groupNext = groupTmp;
        		}
        		if(prev == null){
        			head = groupHead;
        		}else{
        			prev.next = groupHead;
        		}
        		prev = groupTail;
        	}
        }
    }

    public static void dump(ListNode head){
    	while(head != null){
    		System.err.print(head.val + "->");
    		head = head.next;
    	}
    }
    public static void main(String[] args){
    	final int N = 3;
    	ListNode[] list = new ListNode[N];
    	for(int i = 0; i < N; i++){
    		list[i] = new ListNode(i);
    		if(i > 0) list[i - 1].next = list[i];
    	}
    	dump(new Solution().reverseKGroup(list[0], 4));
    }
}

Add java solution for 25. Reverse Nodes in k-Group


import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import com.hewgill.android.nzsldict.Dictionary;

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

import java.util.List;

import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class DictionaryAndroidUnitTest {
    private Dictionary mDictionary;
    private List<Dictionary.DictItem> mResults;

    @Before
    public void createDictionary() {
        mDictionary = new Dictionary(getInstrumentation().getTargetContext());
    }

    @After
    public void clearResults() {
        mResults = null;
    }

    @Test
    public void dictionary_getWordsContainsWords() {
        assertNotEquals(mDictionary.getWords().size(), 0);
    }

    @Test
    public void dictionary_getWordsExactMatchMainGloss() {
        mResults = mDictionary.getWords("Book");
        assertEquals(mResults.get(0).gloss, "book");
    }

    @Test
    public void dictionary_getWordsContainsMatchMainGlass() {
        mResults = mDictionary.getWords("las");
        assertEquals(mResults.get(0).gloss, "sunglasses");
    }

    @Test
    public void dictionary_getWordsExactMatchMaoriGloss() {
        mResults = mDictionary.getWords("ora");
        assertEquals(mResults.get(0).gloss, "alive, live, survive");
    }

    @Test
    public void dictionary_getWordsContainsMatchMaoriGloss() {
        mResults = mDictionary.getWords("orang");
        assertEquals(mResults.get(0).gloss, "politics");
    }

    @Test
    public void dictionary_getWordsExactSecondaryGloss() {
        mResults = mDictionary.getWords("nought");
        assertEquals(mResults.get(0).gloss, "zero");
    }

    @Test
    public void dictionary_getWordsContainsSecondaryGloss() {
        mResults = mDictionary.getWords("keep ou");
        assertEquals(mResults.get(0).gloss, "want nothing to do with");
    }
}

Add tests asserting that search matching is working as per spec


package core.util;

import java.util.ArrayList;
import java.util.List;

import core.Database;
import net.dv8tion.jda.core.entities.User;

public class MatchMaker {

	String guildId;
	List<Ranking> rankings = new ArrayList<Ranking>();

	public MatchMaker(String guildId, List<User> players){
		this.guildId = guildId;
		for(User p : players){
			rankings.add(new Ranking(p));
		}
		calcRank();
	}

	private void calcRank(){
		for(Ranking ranking : rankings){
			double score = 0.0;
			for(Ranking r : rankings){
				if(r != ranking){
					Double pickDiff = Database.queryGetPickOrderDiff(Long.valueOf(guildId), ranking.player.getIdLong(), r.player.getIdLong());

					if(pickDiff > 0){
						score += pickDiff;
					}
				}
			}

			ranking.score = (int)(score * 100);
		}
	}

	public User getMatch(User captain){
		Ranking captainRanking = getRanking(captain);
		Ranking closestMatch = null;

		for(Ranking r : rankings){
			if(r != captainRanking){
				if(closestMatch != null){
					if(captainRanking.getDifference(r) > r.score){
						closestMatch = r;
					}
				}else{
					closestMatch = r;
				}
			}
		}
		return closestMatch.player;
	}

	private Ranking getRanking(User player){
		for(Ranking ranking : rankings){
			if(ranking.player == player){
				return ranking;
			}
		}
		return null;
	}

	private class Ranking{
		private User player;
		private Integer score;

		public Ranking(User player){
			this.player = player;
			this.score = 0;
		}

		private Integer getDifference(Ranking r){
			return Math.abs(score - r.score);
		}
	}
}

Create first matchmaking implementation for captains


/*
 * DomUI Java User Interface - shared code
 * Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
 *
 * This library 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 library 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 library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * See the "sponsors" file for a list of supporters.
 *
 * The latest version of DomUI and related code, support and documentation
 * can be found at http://www.domui.org/
 * The contact for the project is Frits Jalvingh <jal@etc.to>.
 */
package javax.annotation;

import java.lang.annotation.*;

import javax.annotation.meta.*;

@Documented
@TypeQualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultNonNull {
}

Add DefaultNonnull annotation to jst305 crap


/*
 *
 * Copyright 2016, TeamDev Ltd. 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 org.spine3.base;

import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.spine3.test.Tests.hasPrivateUtilityConstructor;

/**
 * @author Alex Tymchenko
 */
public class QueriesShould {

    @Test
    public void have_private_constructor() {
        assertTrue(hasPrivateUtilityConstructor(Queries.class));
    }

}

Create a test for `Queries` utility class.


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package cx2x.translator.transformation;

import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Transformer;
import cx2x.xcodeml.xnode.XcodeProgram;

/**
 * Simple transformation for documentation example
 */
public class MyFirstTransformation extends ClawTransformation {

  // Constructor that received the analyzed pragma as argument
  public MyFirstTransformation(ClawLanguage directive) {
    super(directive);
  }

  // The analyzis step
  public boolean analyze(XcodeProgram xcodeml, Transformer transformer) {
    return true;
  }

  // The transformation step
  public void transform(XcodeProgram xcodeml, Transformer transformer,
                        Transformation other) throws Exception
  {
    _claw.delete();
  }

  // Only used by dependent transformation
  public boolean canBeTransformedWith(Transformation other) {
    return false; // Independent transformation
  }
}

Add simple example of transformation class


package org.jsmpp.util;

import static org.testng.Assert.*;
import org.jsmpp.bean.DeliveryReceipt;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class DeliveryReceiptParserTest {
    private PDUDecomposer decomposer = new DefaultDecomposer();
    private static final String ORIGINAL_MESSAGE = "testing jsmpp bow";

    @Test
    public void parseTextWithLowerCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parsingTextWithUpperCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parseWithNoTextAttribute() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), null);
        } catch (InvalidDeliveryReceiptException e) {
            e.printStackTrace();
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }
}

Add delivery receipt test case


package jme3test.scene;

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;

public class TestRefreshFlagBug extends SimpleApplication {

    private float time = 0;
    private boolean attached = false;
    private Node inBetweenNode;

    public static void main(String[] args) {
        TestRefreshFlagBug app = new TestRefreshFlagBug();
        app.start();
    }

    @Override
    public void simpleUpdate(float tpf) {
        time += tpf;
        if (time > 5 && !attached) {
            attached = true;

            Box b = new Box(1, 1, 1);
            Geometry geom = new Geometry("Box", b);
            Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            geom.setMaterial(mat);

            inBetweenNode.attachChild(geom);

            // the refresh flags become corrupted here ...
            inBetweenNode.getWorldBound();
        }
    }

    @Override
    public void simpleInitApp() {
        inBetweenNode = new Node("In Between Node");
        rootNode.attachChild(inBetweenNode);

        flyCam.setDragToRotate(true);
    }
}

Add simple test case for the "scene not updated" crash in the SDK


/*
 * Copyright 2021 The Bazel Authors. All rights reserved.
 *
 * 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.idea.blaze.base.projectview;

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

import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Test for {@link ProjectViewStorageManager}. */
@RunWith(JUnit4.class)
public class ProjectViewStorageManagerTest {

  private static final com.google.common.collect.ImmutableList<String>
      VALID_PROJECT_VIEW_FILENAMES =
          ImmutableList.of(
              ".blazeproject",
              ".asproject",
              ".bazelproject",
              "foo.blazeproject",
              "bar.baz.bazelproject");

  private static final com.google.common.collect.ImmutableList<String>
      INVALID_PROJECT_VIEW_FILENAMES =
          ImmutableList.of(
              ".buckproject",
              ".bazel",
              "blazeproject",
              "bazelproject",
              "blazeproject.foo",
              "bar.bazelproject.baz",
              ".",
              "");

  @Test
  public void testIsProjectViewFile() {
    VALID_PROJECT_VIEW_FILENAMES.forEach(
        filename -> assertThat(ProjectViewStorageManager.isProjectViewFile(filename)).isTrue());

    INVALID_PROJECT_VIEW_FILENAMES.forEach(
        filename -> assertThat(ProjectViewStorageManager.isProjectViewFile(filename)).isFalse());
  }
}

Add a test for detecting the blazeproject filetype.


/*******************************************************************************
 * Copyright (c) 2016 Red Hat Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies range distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat Inc. - initial API and implementation
 *******************************************************************************/
package org.jboss.tools.vscode.java.internal;

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

import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;

/**
 * A set of assertion methods about LSP4J entities
 *
 * @author Fred Bricon
 *
 */
public class Lsp4jAssertions {

	public static void assertRange(int expectedLine, int expectedStart, int expectedEnd, Range range) {
		assertNotNull("Range is null", range);
		assertPosition(expectedLine, expectedStart, range.getStart());
		assertPosition(expectedLine, expectedEnd, range.getEnd());
	}

	public static void assertPosition(int expectedLine, int expectedChar, Position position) {
		assertNotNull("Position is null", position);
		assertEquals("Unexpected line position from "+position, expectedLine, position.getLine());
		assertEquals("Unexpected character position from "+position, expectedChar, position.getCharacter());
	}
}

Add test assertion helper class


package org.csstudio.utility.ldap.engine;

public class Engine extends Thread {

	private static Engine thisEngine = null;
	/**
	 * @param args
	 */
	public void run () {

	}

	private Engine() {
    	// absicherung
    }

    public static Engine getInstance() {
		//
		// get an instance of our sigleton
		//
		if ( thisEngine == null) {
			synchronized (Engine.class) {
				if (thisEngine == null) {
					thisEngine = new Engine();
				}
			}
		}
		return thisEngine;
	}

}

Add engine for common use of asynch LDAP requests


package org.cyclops.cyclopscore.helper;

import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;

import javax.annotation.Nullable;

/**
 * Helpers related to guis.
 */
public class GuiHelpers {

    /**
     * Render a fluid tank in a gui.
     *
     * @param gui The gui to render in.
     * @param fluidStack The fluid to render.
     * @param capacity The tank capacity.
     * @param x The gui x position, including gui left.
     * @param y The gui y position, including gui top.
     * @param width The tank width.
     * @param height The tank height.
     */
    public static void renderFluidTank(Gui gui, @Nullable FluidStack fluidStack, int capacity,
                                       int x, int y, int width, int height) {
        if (fluidStack != null && capacity > 0) {
            int level = height * fluidStack.amount / capacity;
            TextureAtlasSprite icon = RenderHelpers.getFluidIcon(fluidStack, EnumFacing.UP);
            int verticalOffset = 0;
            while(level > 0) {
                int textureHeight;
                if(level > 16) {
                    textureHeight = 16;
                    level -= 16;
                } else {
                    textureHeight = level;
                    level = 0;
                }

                RenderHelpers.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
                gui.drawTexturedModalRect(x, y - textureHeight - verticalOffset + height, icon, width, textureHeight);
                verticalOffset = verticalOffset + 16;
            }
        }
    }

    /**
     * Render a fluid tank in a gui with a tank overlay.
     * This assumes that the tank overlay has the provided width and height.
     *
     * @param gui The gui to render in.
     * @param fluidStack The fluid to render.
     * @param capacity The tank capacity.
     * @param x The gui x position, including gui left.
     * @param y The gui y position, including gui top.
     * @param width The tank width.
     * @param height The tank height.
     * @param textureOverlay The texture of the tank overlay.
     * @param overlayTextureX The overlay x texture position.
     * @param overlayTextureY The overlay y texture position.
     */
    public static void renderOverlayedFluidTank(Gui gui, @Nullable FluidStack fluidStack, int capacity,
                                                int x, int y, int width, int height,
                                                ResourceLocation textureOverlay, int overlayTextureX, int overlayTextureY) {
        renderFluidTank(gui, fluidStack, capacity, x, y, width, height);
        if (fluidStack != null && capacity > 0) {
            GlStateManager.enableBlend();
            RenderHelpers.bindTexture(textureOverlay);
            gui.drawTexturedModalRect(x, y, overlayTextureX, overlayTextureY, width, height);
        }
    }

}

Add helpers for rendering fluid tanks in guis


package ca.antonious.viewcelladapter.utilstests;

import org.junit.Test;

import ca.antonious.viewcelladapter.TestViewCell;
import ca.antonious.viewcelladapter.utils.ViewCellUtils;
import ca.antonious.viewcelladapter.viewcells.AbstractViewCell;

import static org.junit.Assert.*;

/**
 * Created by George on 2017-05-14.
 */

public class GetSpanSizeTests {
    @Test
    public void test_totalPerLineOf1_spanCountOf3_shouldReturnSpanSizeOf3() {
        AbstractViewCell viewCell = new TestViewCell("id", 1);

        int expectedSpanSize = 3;
        int actualSpanSize = ViewCellUtils.getSpanSizeFor(viewCell, 3);

        assertEquals(expectedSpanSize, actualSpanSize);
    }

    @Test
    public void test_totalPerLineOf3_spanCountOf3_shouldReturnSpanSizeOf1() {
        AbstractViewCell viewCell = new TestViewCell("id", 3);

        int expectedSpanSize = 1;
        int actualSpanSize = ViewCellUtils.getSpanSizeFor(viewCell, 3);

        assertEquals(expectedSpanSize, actualSpanSize);
    }
}

Add basic tests for calculating span count


/*
 * Copyright 2015 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 com.michaelrocks.lightsaber.processor.descriptors;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.objectweb.asm.Type;

public class ParameterizedType {
    private final Type rawType;
    private final Type parameterType;

    public ParameterizedType(final Type rawType) {
        this(rawType, null);
    }

    public ParameterizedType(final Type rawType, final Type parameterType) {
        this.rawType = rawType;
        this.parameterType = parameterType;
    }

    public static ParameterizedType fromType(final Type type) {
        return new ParameterizedType(type, null);
    }

    public Type getRawType() {
        return rawType;
    }

    public Type getParameterType() {
        return parameterType;
    }

    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final ParameterizedType that = (ParameterizedType) object;
        return new EqualsBuilder()
                .append(rawType, that.rawType)
                .append(parameterType, that.parameterType)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(rawType)
                .append(parameterType)
                .toHashCode();
    }

    @Override
    public String toString() {
        if (parameterType == null) {
            return rawType.toString();
        } else {
            return rawType + "<" + parameterType + ">";
        }
    }
}

Add a descriptor for parameterized types


package rsc.processor;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.junit.Test;

import rsc.test.TestSubscriber;

public class UnicastProcessorTest {

    @Test
    public void secondSubscriberRejectedProperly() {

        UnicastProcessor<Integer> up = new UnicastProcessor<>(new ConcurrentLinkedQueue<>());

        up.subscribe();

        TestSubscriber<Integer> ts = new TestSubscriber<>();

        up.subscribe(ts);

        ts.assertNoValues()
        .assertError(IllegalStateException.class)
        .assertNotComplete();

    }
}

Add test fro UnicastProcessor rejecting second Subscriber properly


package fm.last.commons.kyoto;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class FixedPointTest {
  private static final double ERROR_MARGIN = 0.000000000000001d;

  private static final byte[] _10_0001 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 23, 72, 118, -25, -1 };
  private static final byte[] __1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 };
  private static final byte[] __1_1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -91, 12, -17, -123, -64, 0 };
  private static final byte[] _1_1 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 90, -13, 16, 122, 64, 0 };

  private byte[] bytes;
  private double expected;

  @Parameters
  public static Collection<Object[]> data() {
    List<Object[]> data = new ArrayList<Object[]>();
    data.add(new Object[] { 10.0001d, _10_0001 });
    data.add(new Object[] { -1.0d, __1 });
    data.add(new Object[] { -1.1d, __1_1 });
    data.add(new Object[] { 1.1d, _1_1 });
    return data;
  }

  public FixedPointTest(double expected, byte[] bytes) {
    this.expected = expected;
    this.bytes = bytes;
  }

  @Test
  public void testFixedPointToDouble() {
    double decodedValue = FixedPoint.toDouble(bytes);
    assertEquals("Expected to get " + expected, expected, decodedValue, ERROR_MARGIN);
  }
}

Add unit test for FixedPoint


package leetcode;

/**
 * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
 */
public class Problem81 {
    public boolean search(int[] nums, int target) {
        return false;
    }

    public static void main(String[] args) {
        Problem81 prob = new Problem81();
//        System.out.println(prob.search(nums, target));
    }
}

Create a skeleton for problem 81


/*
 * Copyright (c) 2016 Instituto Atlântico Development Company, L.P. and others. 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.opendaylight.nic.of.renderer.strategy;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.opendaylight.nic.of.renderer.impl.RedirectFlowManager;
import org.opendaylight.nic.utils.FlowAction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.intent.rev150122.intents.Intent;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * @author victor. Created on 17/11/16.
 */
@RunWith(PowerMockRunner.class)
public class RedirectExecutorTest {

    @InjectMocks
    private RedirectExecutor redirectExecutor;

    @Mock
    private RedirectFlowManager redirectFlowManager;

    @Mock
    private Intent intentMock;

    @Before
    public void setUp() throws Exception {
        redirectExecutor = new RedirectExecutor(redirectFlowManager);
    }

    @Test
    public void testExecuteIntentAddFlow() throws Exception {
        redirectExecutor.execute(intentMock, FlowAction.ADD_FLOW);
    }
}

Increase of-renderer coverage on RedirectExecutor.


package arez.integration.observed;

import arez.Arez;
import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Observed;
import arez.annotations.ObserverRef;
import arez.integration.AbstractArezIntegrationTest;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservedNonArezDependenciesTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    int _renderCallCount;

    @Observed( arezOnlyDependencies = false )
    void render()
    {
      getValue();
      _renderCallCount++;
    }

    @ObserverRef
    abstract Observer getRenderObserver();

    @SuppressWarnings( "UnusedReturnValue" )
    @Observable
    abstract long getValue();

    abstract void setValue( long value );
  }

  @Test
  public void scenario()
    throws Exception
  {
    final TestComponent1 component = new ObservedNonArezDependenciesTest_Arez_TestComponent1();

    assertEquals( component._renderCallCount, 1 );

    // reportStale should result in re-render invocation
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().reportStale() );

    assertEquals( component._renderCallCount, 2 );

    // Trigger a dependency change, mark observer as dirty
    safeAction( () -> component.setValue( ValueUtil.randomLong() ) );

    assertEquals( component._renderCallCount, 3 );

    // reportStale and dependency change should result in single re-render invocation
    Arez.context().safeAction( () -> {
      component.setValue( ValueUtil.randomLong() );
      component.getRenderObserver().reportStale();
    } );

    assertEquals( component._renderCallCount, 4 );
  }
}

Add integration tests for non-arez dependencies


/**
 * An implementation of the HTTP Digest authentication scheme for Android.
 *
 * With a small effort you can use it to get HTTP digest working with HttpURLConnection or any
 * other HTTP stack.
 *

 * Here is an example of how to make a request and respond to a Digest challenge:
 *
 *

{@code
 * // Step 1. Create the connection
 * URL url = new URL("http://httpbin.org/digest-auth/auth/user/passwd");
 * HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 *
 * // Step 2. Make the request and check to see if the response contains an authorization challenge
 * if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
 *     // Step 3. Create a authentication object from the challenge...
 *     DigestAuthentication auth = DigestAuthentication.fromResponse(connection);
 *     // ...with correct credentials
 *     auth.username("user").password("passwd");
 *
 *     // Step 4 (Optional). Check if the challenge was a digest challenge of a supported type
 *     if (!auth.canRespond()) {
 *         // No digest challenge or a challenge of an unsupported type - do something else or fail
 *         return;
 *     }
 *
 *     // Step 5. Create a new connection, identical to the original one...
 *     connection = (HttpURLConnection) url.openConnection();
 *     // ...and set the Authorization header on the request, with the challenge response
 *     connection.setRequestProperty(DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
 *     auth.getAuthorizationForRequest("GET", connection.getURL().getPath()));
 * }
 * }

 *
 * {@link com.albroco.barebonesdigest.DigestAuthentication} is the main entry point of the API,
 * read the documentation for more examples. Some other useful classes include:
 *

 *
{@link com.albroco.barebonesdigest.WwwAuthenticateHeader} which can be used to parse
 * challenges from WWW-Authenticate headers, including challenges of other types than Digest.

 *
{@link com.albroco.barebonesdigest.DigestChallenge} which provides functionality for
 * parsing digest challenges.

 *
{@link com.albroco.barebonesdigest.DigestChallengeResponse} which provides functionality
 * for generating responses to digest challenges.

 *

 */
package com.albroco.barebonesdigest;

Add top-level package info to javadoc


package fi.nls.oskari.control.view.modifier.param;

import fi.nls.oskari.annotation.OskariViewModifier;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.view.modifier.ModifierException;
import fi.nls.oskari.view.modifier.ModifierParams;
import fi.nls.oskari.view.modifier.ParamHandler;
import org.json.JSONArray;
import org.json.JSONObject;

@OskariViewModifier("timeseries")
public class TimeseriesParamHandler extends ParamHandler {
    private static final String KEY_TIME = "time";

    public boolean handleParam(final ModifierParams params) throws ModifierException {
        String paramValue = params.getParamValue();
        if (paramValue == null) {
            return false;
        }
        final JSONObject bundleState = getBundleState(params.getConfig(), BUNDLE_TIMESERIES);
        final String[] timeProps = paramValue.split("/");
        if (timeProps.length != 2) {
            JSONHelper.putValue(bundleState, KEY_TIME, paramValue);
            return false;
        }
        JSONArray time = new JSONArray();
        time.put(timeProps[0]);
        time.put(timeProps[1]);
        JSONHelper.putValue(bundleState, KEY_TIME, time);
        return false;
    }
}

Add handler for timeseries parameter


/*
 * Copyright 2018 Red Hat, Inc.
 *
 * 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.jboss.shamrock.jaxrs.runtime.graal;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
import org.w3c.dom.Document;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

@TargetClass(className = "org.jboss.resteasy.plugins.providers.DocumentProvider")
final class DeleteDocumentProvider {

    @Substitute
    public boolean isReadable(Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType) {
        return false;
    }

    @Substitute
    public Document readFrom(Class<Document> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream input) throws IOException, WebApplicationException {
        return null;
    }

    @Substitute
    public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType) {
        return false;
    }

    @Substitute
    public void writeTo(Document document, Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream output) throws IOException, WebApplicationException {

    }
}

Remove DocumentProvider from native image


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 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 HOLDERS 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 zorbage.type.storage;

import zorbage.type.algebra.Group;

/**
 *
 * @author Barry DeZonia
 *
 * @param <U>
 */
public class ArrayStorageGeneric<T extends Group<T,U>,U>
	implements Storage<U>
{

	private final Object[] data;
	private final T g;

	public ArrayStorageGeneric(long size, T g) {
		if (size < 0)
			throw new IllegalArgumentException("ArrayStorage cannot handle a negative request");
		if (size > Integer.MAX_VALUE)
			throw new IllegalArgumentException("ArrayStorage cannot handle such a large request");
		this.data = new Object[(int)size];
		for (int i = 0; i < size; i++) {
			this.data[i] = g.construct();
		}
		this.g = g;
	}

	@Override
	public void put(long index, U value) {
		g.assign(value, (U)data[(int)index]);
	}

	@Override
	public void get(long index, U value) {
		g.assign((U)data[(int)index], value);
	}

	@Override
	public long size() {
		return data.length;
	}

}

Define generic storage based upon a group


package com.codenvy.ide.ext.datasource.client.common;

import com.codenvy.ide.api.mvp.View;
import com.codenvy.ide.api.parts.PartStackUIResources;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.LayoutPanel;

public abstract class ViewWithToolbar<T> extends Composite implements View<T> {

    private final LayoutPanel     toolBar;
    private final DockLayoutPanel container;
    private T                     delegate;

    public ViewWithToolbar(final PartStackUIResources resources) {
        container = new DockLayoutPanel(Style.Unit.PX);
        initWidget(container);
        container.setSize("100%", "100%");
        toolBar = new LayoutPanel();
        toolBar.addStyleName(resources.partStackCss().ideBasePartToolbar());
        container.addNorth(toolBar, 20);

        // this hack used for adding box shadow effect to toolbar
        toolBar.getElement().getParentElement().getStyle().setOverflow(Style.Overflow.VISIBLE);
    }

    /** {@inheritDoc} */
    @Override
    public void setDelegate(T delegate) {
        this.delegate = delegate;
    }

    public T getDelegate() {
        return delegate;
    }

    public DockLayoutPanel getContainer() {
        return container;
    }

    public LayoutPanel getToolBar() {
        return toolBar;
    }
}

Add view with a toolbar (but without minimize button as in BaseView)


package io.quarkus.hibernate.reactive;

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

import javax.enterprise.context.control.ActivateRequestContext;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.reactive.mutiny.Mutiny;
import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

public class NoJtaTest {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClass(MyEntity.class)
                    .addAsResource("application.properties"));

    @Inject
    SessionFactory sessionFactory; // This is an ORM SessionFactory, but it's backing Hibernate Reactive.

    @Inject
    Mutiny.Session session;

    @Test
    @ActivateRequestContext
    public void test() {
        ServiceRegistryImplementor serviceRegistry = sessionFactory.unwrap(SessionFactoryImplementor.class)
                .getServiceRegistry();

        // Two assertions are necessary, because these values are influenced by separate configuration
        assertThat(serviceRegistry.getService(JtaPlatform.class).retrieveTransactionManager()).isNull();
        assertThat(serviceRegistry.getService(TransactionCoordinatorBuilder.class).isJta()).isFalse();

        // Quick test to make sure HRX works
        MyEntity entity = new MyEntity("default");
        MyEntity retrievedEntity = session.withTransaction(tx -> session.persist(entity))
                .chain(() -> session.withTransaction(tx -> session.clear().find(MyEntity.class, entity.getId())))
                .await().indefinitely();
        assertThat(retrievedEntity)
                .isNotSameAs(entity)
                .returns(entity.getName(), MyEntity::getName);
    }

    @Entity
    public static class MyEntity {

        private long id;

        private String name;

        public MyEntity() {
        }

        public MyEntity(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return getClass().getSimpleName() + ":" + name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "defaultSeq")
        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

Test that JTA is disabled for Hibernate Reactive persistence units


// 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.pgm.util;

import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

public class GuiceLogger {
  private static final Handler HANDLER;
  static {
    HANDLER = new StreamHandler(System.out, new Formatter() {
      public String format(LogRecord record) {
        return String.format("[Guice %s] %s%n", record.getLevel().getName(),
            record.getMessage());
      }
    });
    HANDLER.setLevel(Level.ALL);
  }

  private GuiceLogger() {
  }

  public static Logger getLogger() {
    return Logger.getLogger("com.google.inject");
  }

  public static void enable() {
    Logger guiceLogger = getLogger();
    guiceLogger.addHandler(GuiceLogger.HANDLER);
    guiceLogger.setLevel(Level.ALL);
  }

  public static void disable() {
    Logger guiceLogger = getLogger();
    guiceLogger.setLevel(Level.OFF);
    guiceLogger.removeHandler(GuiceLogger.HANDLER);
  }
}

Add utility class to inspect Guice wiring


/*
 * Copyright 2015 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.processor.descriptors;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.objectweb.asm.Type;

public class EnumValueDescriptor {
    private final Type type;
    private final String value;

    public EnumValueDescriptor(final Type type, final String value) {
        this.type = type;
        this.value = value;
    }

    public static EnumValueDescriptor from(final String desc, final String value) {
        return new EnumValueDescriptor(Type.getType(desc), value);
    }

    public Type getType() {
        return type;
    }

    public String getValue() {
        return value;
    }

    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final EnumValueDescriptor that = (EnumValueDescriptor) object;
        return new EqualsBuilder()
                .append(type, that.type)
                .append(value, that.value)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(type)
                .append(value)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("type", type)
                .append("value", value)
                .toString();
    }
}

Implement a descriptor for enum values


/*
 * Copyright 2016 MovingBlocks
 *
 * 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.
 */
@Generated("com.google.protobuf")
package org.terasology.protobuf;

import javax.annotation.Generated;

Add @Generated to protobuf package file.


package leetcode;

/**
 * https://leetcode.com/problems/kth-largest-element-in-an-array/
 */
public class Problem215 {
    public int findKthLargest(int[] nums, int k) {

    }

    public static void main(String[] args) {
        Problem215 prob = new Problem215();
        System.out.println(prob.findKthLargest(new int[]{2, 7, 4, 5, 6, 3, 1}, 4));
    }
}

Create skeleton for problem 215


package com.vladmihalcea.book.hpjp.hibernate.identifier;

import org.hibernate.cfg.AvailableSettings;
import org.junit.Test;

import javax.persistence.*;
import java.util.Properties;

public class PreferredPooledLoSequenceIdentifierTest extends AbstractPooledSequenceIdentifierTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
                Post.class
        };
    }

    @Override
    protected void additionalProperties(Properties properties) {
        properties.put(AvailableSettings.PREFERRED_POOLED_OPTIMIZER, "pooled-lo");
    }

    @Override
    protected Object newEntityInstance() {
        return new Post();
    }

    @Test
    public void testOptimizer() {
        insertSequences();
    }

    @Entity(name = "Post")
    public static class Post {

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "post_sequence")
        @SequenceGenerator(
            name = "post_sequence",
            sequenceName = "post_sequence",
            allocationSize = 3
        )
        private Long id;
    }
}

Add test case for setting the preferred pooled optimizer strategy


/*
 * 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.prestosql.execution;

import io.prestosql.plugin.memory.MemoryQueryRunner;
import io.prestosql.testing.AbstractTestQueryFramework;
import io.prestosql.testing.QueryRunner;
import org.testng.annotations.Test;

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

public class TestTry
        extends AbstractTestQueryFramework
{
    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        return MemoryQueryRunner.createQueryRunner();
    }

    @Test
    public void testTryWithColumnWithAt()
    {
        assertUpdate("CREATE TABLE table_with_column_with_at(\"a@b\" integer)");
        assertUpdate("INSERT INTO table_with_column_with_at VALUES (55)", 1);
        assertThat(query("SELECT try(\"a@b\") FROM table_with_column_with_at"))
                .matches("VALUES 55");
        assertUpdate("DROP TABLE table_with_column_with_at");
    }
}

Add test with try and column with at sign


package seedu.taskitty.model;

import java.util.ArrayList;
import java.util.Collection;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.model.tag.Tag;
import seedu.taskitty.model.tag.UniqueTagList;
import seedu.taskitty.model.tag.UniqueTagList.DuplicateTagException;

//@@author A0130853L
public class UniqueTagListTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void individualTags_hasDuplicates_exceptionThrown() throws DuplicateTagException, IllegalValueException {
        thrown.expect(DuplicateTagException.class);
        UniqueTagList list = new UniqueTagList(new Tag("hi"), new Tag("hi"));
    }

    @Test
    public void createTagCollection_hasDuplicates_exceptionThrown() throws DuplicateTagException, IllegalValueException {
        thrown.expect(DuplicateTagException.class);
        Collection<Tag> tags = new ArrayList<Tag>();
        tags.add(new Tag("hi"));
        tags.add(new Tag("hi"));
        UniqueTagList list = new UniqueTagList(tags);
    }

    @Test
    public void addTagToUniqueTagList_hasDuplicate_exceptionThrown() throws DuplicateTagException, IllegalValueException {
        thrown.expect(DuplicateTagException.class);
        UniqueTagList list = new UniqueTagList();
        list.add(new Tag("hi"));
        list.add(new Tag("hi"));
    }
}

Add UniqueTagList test to account for duplicateTagException thrown to improve test coverage


/*
 * Copyright 2008-2013 the original author or authors.
 *
 * 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.broadleafcommerce.common.util.sql.importsql;

import org.hibernate.tool.hbm2ddl.SingleLineSqlCommandExtractor;

import java.io.Reader;

/**
 * This is a utility class that is only meant to be used for testing the BLC demo on SQL Server. In our current
 * import sql files, there are a number of value declarations that are incompatible with Sql Server. This
 * custom extractor takes care of transforming those values into something SQL Server understands.
 *
 * @author Jeff Fischer
 */
public class DemoSqlServerSingleLineSqlCommandExtractor extends SingleLineSqlCommandExtractor {

    private static final String BOOLEANTRUEMATCH = "(?i)(true)";
    private static final String BOOLEANFALSEMATCH = "(?i)(false)";
    private static final String TIMESTAMPMATCH = "(?i)(current_date)";
    public static final String TRUE = "'TRUE'";
    public static final String FALSE = "'FALSE'";
    public static final String CURRENT_TIMESTAMP = "CURRENT_TIMESTAMP";

    @Override
    public String[] extractCommands(Reader reader) {
        String[] statements = super.extractCommands(reader);
        for (int j=0; j<statements.length; j++) {
            //try start matches
            statements[j] = statements[j].replaceAll(BOOLEANTRUEMATCH + "\\s*[,]", TRUE + ",");
            statements[j] = statements[j].replaceAll(BOOLEANFALSEMATCH + "\\s*[,]", FALSE + ",");
            statements[j] = statements[j].replaceAll(TIMESTAMPMATCH + "\\s*[,]", CURRENT_TIMESTAMP + ",");

            //try middle matches
            statements[j] = statements[j].replaceAll("[,]\\s*" + BOOLEANTRUEMATCH + "\\s*[,]", "," + TRUE + ",");
            statements[j] = statements[j].replaceAll("[,]\\s*" + BOOLEANFALSEMATCH + "\\s*[,]", "," + FALSE + ",");
            statements[j] = statements[j].replaceAll("[,]\\s*" + TIMESTAMPMATCH + "\\s*[,]", "," + CURRENT_TIMESTAMP + ",");

            //try end matches
            statements[j] = statements[j].replaceAll("[,]\\s*" + BOOLEANTRUEMATCH, "," + TRUE);
            statements[j] = statements[j].replaceAll("[,]\\s*" + BOOLEANFALSEMATCH, "," + FALSE);
            statements[j] = statements[j].replaceAll("[,]\\s*" + TIMESTAMPMATCH, "," + CURRENT_TIMESTAMP);
        }

        return statements;
    }
}

Allow dynamic conversion of import sql for SQL Server compatibility


package ships.model;

/**
 *
 * @author r4pt0r
 */
public class ShipPlacementMode {

    private Ship.Size size = Ship.Size.ONE;
    private Ship.Direction dir = Ship.Direction.HORIZONTAL;
    private Boolean active = Boolean.FALSE;

    /**
     * @return the size
     */
    public Ship.Size getSize() {
        return size;
    }

    /**
     * @param size the size to set
     */
    public void setSize(Ship.Size size) {
        this.size = size;
    }

    /**
     * @return the dir
     */
    public Ship.Direction getDir() {
        return dir;
    }

    /**
     * @return the active
     */
    public Boolean isActive() {
        return active;
    }

    public void activate() {
        this.active = Boolean.TRUE;
    }

    public void deactivate() {
        this.active = Boolean.FALSE;
    }

    public void switchDirection() {
        if (dir == Ship.Direction.HORIZONTAL) {
            dir = Ship.Direction.VERTICAL;
        } else {
            dir = Ship.Direction.HORIZONTAL;
        }
    }

}

Add class for storing status of ship placement


/*
 * Copyright (c) 2012 The University of Manchester, UK.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the names of The University of Manchester nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * 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 uk.org.taverna.server.client;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({ uk.org.taverna.server.client.util.TestURIUtils.class,
		TestServer.class })
public class TestAll {

}

Add a top-level test suite to run all tests at once.


/*
 * 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 com.xpn.xwiki.wysiwyg.client.dom.internal.ie;

import com.xpn.xwiki.wysiwyg.client.dom.JavaScriptObject;

/**
 * A mock native selection to be used in unit tests. It holds a reference to a given native range which is always
 * returned.
 *
 * @version $Id$
 */
public final class MockNativeSelection extends JavaScriptObject
{
    /**
     * Default constructor. Needs to be protected because all instances are created from JavaScript.
     */
    protected MockNativeSelection()
    {
    }

    /**
     * @param nativeRange a reference to the native range which will always be returned by the new mock native selection
     * @return a new mock native selection object casted to {@link NativeSelection}
     */
    public static native NativeSelection newInstance(NativeRange nativeRange)
    /*-{
        return {
            ownerDocument : nativeRange.ownerDocument,
            createRange : function() {
                return nativeRange;
            }
        };
    }-*/;
}

Use the same Range implementation for all browsers


package me.proxer.library.api;

import me.proxer.library.api.ConferenceAdapter.IntermediateConference;
import me.proxer.library.entitiy.messenger.Conference;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

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

/**
 * @author Ruben Gees
 */
public class ConferenceAdapterTest {

    private ConferenceAdapter adapter;

    @Before
    public void setUp() {
        adapter = new ConferenceAdapter();
    }

    @Test
    public void testFromJson() {
        assertThat(adapter.fromJson(constructIntermediateConference(true)))
                .isEqualTo(constructConference(true));
    }

    @Test
    public void testFromJsonWithNoImage() {
        assertThat(adapter.fromJson(constructIntermediateConference(false)))
                .isEqualTo(constructConference(false));
    }

    private IntermediateConference constructIntermediateConference(boolean withImage) {
        IntermediateConference result = new IntermediateConference();

        result.id = "123";
        result.topic = "something";
        result.customTopic = "somethingElse";
        result.participantAmount = 13;
        result.group = true;
        result.read = false;
        result.date = new Date(123456L);
        result.unreadMessageAmount = 2;
        result.lastReadMessageId = "321";
        result.image = withImage ? "avatar:http://example.com/image.png" : "";

        return result;
    }

    private Conference constructConference(boolean withImage) {
        return new Conference("123", "something", "somethingElse", 13,
                withImage ? "http://example.com/image.png" : "", withImage ? "avatar" : "", true, false,
                new Date(123456L), 2, "321");
    }
}

Add tests for the ConferenceAdapter


/**
 * 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 hdfs.jsr203;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestDocUseCases {

	private static MiniDFSCluster cluster;
	private static URI clusterUri;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		cluster = startMini(TestFileSystem.class.getName());
		clusterUri = cluster.getFileSystem().getUri();
	}

	@AfterClass
	public static void teardownClass() throws Exception {
		if (cluster != null) {
			cluster.shutdown();
		}
	}

	private static MiniDFSCluster startMini(String testName) throws IOException {
		File baseDir = new File("./target/hdfs/" + testName).getAbsoluteFile();
		FileUtil.fullyDelete(baseDir);
		Configuration conf = new Configuration();
		conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
		MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
		MiniDFSCluster hdfsCluster = builder.clusterId(testName).build();
		hdfsCluster.waitActive();
		return hdfsCluster;
	}

	@Test
	public void testWriteBuffered() throws IOException {
		Path rootPath = Paths.get(clusterUri);

		Path file = rootPath.resolve(rootPath.resolve("temp_file.txt"));

		Charset charset = Charset.forName("US-ASCII");
		String s = "this is a test";
		BufferedWriter writer = Files.newBufferedWriter(file, charset);
		writer.write(s, 0, s.length());
		writer.close();
	}

}

Add more unit test from Oracle NIO documentation.


package me.izstas.rfs.client.util;

import java.util.concurrent.Executor;
import javax.swing.SwingUtilities;

/**
 * An executor whose {@link Executor#execute(Runnable)} method delegates to {@link SwingUtilities#invokeLater(Runnable)}.
 */
public final class SwingExecutor implements Executor {
    public static final Executor INSTANCE = new SwingExecutor();

    private SwingExecutor() {
    }

    @Override
    public void execute(Runnable command) {
        SwingUtilities.invokeLater(command);
    }
}

Add Executor implementation which executes tasks in Swing event thread


package edu.hm.hafner.analysis.parser;

import java.io.IOException;
import java.io.Reader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.IssueParser;
import edu.hm.hafner.analysis.ParsingException;
import edu.hm.hafner.analysis.ReaderFactory;
import edu.hm.hafner.analysis.Report;
import edu.hm.hafner.analysis.Severity;

public class BrakemanParser extends IssueParser {
    private static final long serialVersionUID = 1374428573878091300L;

    @Override
    public boolean accepts(final ReaderFactory readerFactory) {
        return readerFactory.getFileName().endsWith(".json");
    }

    @Override
    public Report parse(final ReaderFactory readerFactory) throws ParsingException {
        final Report report = new Report();
        try (Reader reader = readerFactory.create()) {
            final JSONObject jsonReport = (JSONObject) new JSONTokener(reader).nextValue();

            final JSONArray warnings = jsonReport.getJSONArray("warnings");
            for (Object warning : warnings) {
                report.add(convertToIssue((JSONObject) warning));
            }
        }
        catch (IOException | JSONException | ClassCastException e) {
            throw new ParsingException(e);
        }
        return report;
    }

    private Issue convertToIssue(JSONObject warning) throws JSONException {
        String fileName = warning.getString("file");
        String category = warning.getString("warning_type");
        Severity severity = getSeverity(warning.getString("confidence"));
        String fingerprint = warning.getString("fingerprint");
        String warning_type = warning.getString("check_name");
        StringBuilder message = new StringBuilder();
        message.append(warning.getString("message"));

        if(warning.has("code")) {
            String code = warning.optString("code", "");

            if(!code.isEmpty()) {
                message.
                    append(": ").
                    append(warning.getString("code"));
            }
        }

        int line = warning.optInt("line", 1);

        return new IssueBuilder()
            .setMessage(message.toString())
            .setCategory(category)
            .setType(warning_type)
            .setSeverity(severity)
            .setFileName(fileName)
            .setLineStart(line)
            .setFingerprint(fingerprint)
            .build();
    }

    private Severity getSeverity(String confidence) {
        if ("Medium".equalsIgnoreCase(confidence)) {
            return Severity.WARNING_NORMAL;
        } else if ("High".equalsIgnoreCase(confidence)) {
            return Severity.WARNING_HIGH;
        } else if ("Weak".equalsIgnoreCase(confidence)) {
            return Severity.WARNING_LOW;
        }
        else {
            return Severity.WARNING_HIGH;
        }
    }
}

Add parser for Brakeman JSON reports


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.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.sps.data.Recipe;
import com.google.sps.data.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/shopping-list")
public class ShoppinListServlet extends HttpServlet {

  @Override
  @SuppressWarnings("unchecked") // Compiler cannot verify cast to ArrayList
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idToken = request.getParameter("idToken");
    User user = new User(idToken);
    List<Key> plannerKeys = user.getPlannerList();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    // Avoid repeating ingredients.
    HashSet<String> shoppingList = new HashSet<>();

    plannerKeys.forEach(key -> {
      try {
        Entity entity = datastore.get(key);
        ArrayList<String> ingredients = (ArrayList<String>) entity.getProperty("ingredients");
        ingredients.forEach(ingredient -> shoppingList.add(ingredient));

      } catch(EntityNotFoundException e) {
        System.out.prinln("Ignoring invalid key");
      }
    });

    Gson gson = new Gson();
    response.setContentType("application/json");
    response.getWriter().print(gson.toJson(shoppingList));
  }
}

Implement servlet for fetching user shopping list


@ParametersAreNonnullByDefault
@DefaultAnnotation(Nonnull.class)
package com.swrve.logging;

import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;

Add null checking by default


package com.brewtab.ircbot.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SQLProperties<V extends Serializable> {
    private Connection connection;

    public SQLProperties(Connection connection) {
        this.connection = connection;
        try {
            this.connection.prepareStatement(
                "CREATE TABLE IF NOT EXISTS properties (k VARCHAR PRIMARY KEY, v BLOB)"
                ).execute();

            this.connection.prepareStatement(
                "CREATE INDEX IF NOT EXISTS idxprops ON properties(k)"
                ).execute();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public V get(String key) {
        try {
            PreparedStatement statement = connection.prepareStatement(
                "SELECT v FROM properties WHERE k = ?"
                );

            statement.setString(1, key);

            ResultSet results = statement.executeQuery();
            if (results.next()) {
                Blob valueBlob = results.getBlob(1);
                InputStream stream = valueBlob.getBinaryStream();
                ObjectInputStream objectStream = new ObjectInputStream(stream);

                return (V) objectStream.readObject();
            } else {
                return null;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void set(String key, V value) {
        try {
            Blob blob = connection.createBlob();

            ObjectOutputStream valueStream = new ObjectOutputStream(blob.setBinaryStream(1));
            valueStream.writeObject(value);
            valueStream.close();

            PreparedStatement statement = connection.prepareStatement(
                "UPDATE properties SET v = ? WHERE k = ? LIMIT 1"
                );

            statement.setBlob(1, blob);
            statement.setString(2, key);

            // If no update was performed instead insert the value
            if (statement.executeUpdate() == 0) {
                statement = connection.prepareStatement(
                    "INSERT INTO properties (k, v) VALUES (?, ?)"
                    );

                statement.setString(1, key);
                statement.setBlob(2, blob);
                statement.execute();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Add SQLProperites class for storing simple key value properties


package brooklyn.cli;

import brooklyn.rest.BrooklynService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ClientTest {

    @BeforeClass
    public void testSetUp() {}

    @AfterClass
    public void testTearDown() {}

    @Test
    public void testCatalogEntitiesCommand() {

    }

}

Add a unit test class for the new cli client


package rabbit.filter.authenticate;

import rabbit.http.HttpHeader;
import rabbit.proxy.Connection;

/** Something that can authenticate users using some kind of database.
 */
public interface Authenticator {

    /** Find the token used to authenticate */
    String getToken (HttpHeader header, Connection con);

    /** Try to authenticate the user.
     * @param user the username
     * @param pwd the password of the user
     * @param channel the socket channel the user is currently using
     * @return true if authentication succeeded, false otherwise.
     */
    boolean authenticate (String user, String pwd);
}

package rabbit.filter.authenticate;

import rabbit.http.HttpHeader;
import rabbit.proxy.Connection;

/** Something that can authenticate users using some kind of database.
 */
public interface Authenticator {

    /** Find the token used to authenticate */
    String getToken (HttpHeader header, Connection con);

    /** Try to authenticate the user.
     * @param user the username
     * @param pwd the password of the user
     * @return true if authentication succeeded, false otherwise.
     */
    boolean authenticate (String user, String pwd);
}

Remove param that is no longer used.


package algorithms.problems;

import java.util.HashMap;
import java.util.Map;

import datastructures.tree.BinaryTree;
import datastructures.tree.TreeNode;

public class DeepestNodeBinaryTree {

  private BinaryTree<Integer> tree = null;
  private Map<Integer, TreeNode<Integer>> nodesMap = null;

  public DeepestNodeBinaryTree() {
    tree = new BinaryTree<Integer>();
    nodesMap = new HashMap<Integer, TreeNode<Integer>>();
  }

  public void constructTree(String[] input) {
    for (String line : input) {
      String[] values = line.split(" ");
      int val = 0;
      switch (values[0]) {
      case "insertRoot":
        val = Integer.parseInt(values[1]);
        nodesMap.put(val, tree.insertRoot(val));
        break;
      case "insertLeft":
        insert(values[1], values[2], true);
        break;
      case "insertRight":
        insert(values[1], values[2], false);
        break;
      }
    }
  }

  public Integer getDeepestNode() {
    return deepestNode(tree.getRoot()).treeNode.data;
  }

  private TreeNodeWrapper<Integer> deepestNode(TreeNode<Integer> root) {
    if(root == null) {
      return new TreeNodeWrapper<Integer>(null, -1);
    }

    TreeNodeWrapper<Integer> leftWrapper = deepestNode(root.left);
    TreeNodeWrapper<Integer> rightWrapper = deepestNode(root.right);

    if(leftWrapper.treeNode == null && rightWrapper.treeNode == null) {
      return new TreeNodeWrapper<Integer>(root, 1);
    } else {
      TreeNodeWrapper<Integer> deepestWrapper = (leftWrapper.depth >= rightWrapper.depth) ? leftWrapper : rightWrapper;
      deepestWrapper.depth += 1;
      return deepestWrapper;
    }
  }

  private void insert(String parentStr, String nodeStr, boolean isLeft) {
    int parentVal = Integer.parseInt(parentStr);
    int nodeVal = Integer.parseInt(nodeStr);
    TreeNode<Integer> parentNode = nodesMap.get(parentVal);
    if(parentNode == null) {
      return;
    }

    TreeNode<Integer> node = new TreeNode<Integer>(nodeVal);
    nodesMap.put(nodeVal, tree.insert(parentNode, node, isLeft));
  }

  @SuppressWarnings("hiding")
  private class TreeNodeWrapper<Integer> {
    TreeNode<Integer> treeNode = null;
    int depth = 0;

    public TreeNodeWrapper(TreeNode<Integer> treeNode, int depth) {
      this.treeNode = treeNode;
      this.depth = depth;
    }
  }
}

Add solution for deepest node in a BinaryTree :smile:


package org.pilgrim.leetcode.y2022;

import java.util.Arrays;

public class SumTwoInSorterArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[] indexes = twoSum(new int[] {1,2,3,4,4,9,56,90}, 8);
		System.out.println(Arrays.toString(indexes));
	}

	public static int[] twoSum(int[] arr, int k) {
        // Validate input values
        if(arr == null || arr.length <= 1 || arr.length > 3 * 10000 || k< -1000 || k > 1000){
            return null;
        }

        // Traverse array from both sides
        int[] res = new int[] {-1, -1};
        int i = 0;
        int j = arr.length - 1;
        while(i < j){
            int s = arr[i] + arr[j];
            if(k == s){
                res[0] = i+1;
                res[1] = j+1;
                break;
            }
            else if(k > s){
                i++;
                while(i < j && arr[i] == arr[i+1] && arr[i]*2 != k){
                    i++;
                }
            }
            else if(k < s){
                j--;
                while(i < j && arr[j] == arr[j - 1] && arr[j]*2 != k){
                    j--;
                }
            }
        }

        return res;
    }

	public static int[] twoSum2(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            int mid = left + (right - left) / 2;
            if (sum > target)
                if (numbers[left] + numbers[mid] > target)
                    right = mid - 1;
                else
                    right--;
            else if (sum < target)
                if (numbers[mid] + numbers[right] < target)
                    left = mid + 1;
                else
                    left++;
            else
                return new int[] {left +1, right + 1};
        }
        return null;
    }

}

Add sum two in sorted array


package fr.tvbarthel.apps.simpleweatherforcast.openweathermap;

import android.os.AsyncTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class DailyForecastJsonParser extends AsyncTask<String, Void, ArrayList<DailyForecastModel>> {

	private static String TAG_WEATHER_LIST = "list";
	private static String TAG_HUMIDITY = "humidity";
	private static String TAG_WEATHER = "weather";
	private static String TAG_WEATHER_DESCRIPTION = "description";
	private static String TAG_TEMPERATURE = "temp";
	private static String TAG_TEMPERATURE_DAY = "day";
	private static String TAG_DATE_TIME = "dt";

	@Override
	protected ArrayList<DailyForecastModel> doInBackground(String... params) {
		return parse(params[0]);
	}

	private ArrayList<DailyForecastModel> parse(final String json) {
		final ArrayList<DailyForecastModel> result = new ArrayList<DailyForecastModel>();
		try {
			JSONObject root = new JSONObject(json);
			JSONArray weatherList = root.getJSONArray(TAG_WEATHER_LIST);
			for (int i = 0; i < weatherList.length(); i++) {
				result.add(parseDailyForecast(weatherList.getJSONObject(i)));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	private DailyForecastModel parseDailyForecast(JSONObject jsonDailyForecast) {
		final DailyForecastModel model = new DailyForecastModel();
		model.setDateTime(parseDateTime(jsonDailyForecast));
		model.setHumidity(parseHumidity(jsonDailyForecast));
		model.setDescription(parseWeatherDescription(jsonDailyForecast));
		model.setTemperature(parseDayTemperature(jsonDailyForecast));
		return model;
	}

	private Double parseDayTemperature(JSONObject dailyForecast) {
		Double dayTemperature = 0d;
		try {
			dayTemperature = dailyForecast.getJSONObject(TAG_TEMPERATURE).getDouble(TAG_TEMPERATURE_DAY);
		} catch (JSONException exception) {
			exception.printStackTrace();
		}
		return dayTemperature;
	}

	private String parseWeatherDescription(JSONObject dailyForecast) {
		String weatherDescription = "";
		try {
			weatherDescription = dailyForecast.getJSONArray(TAG_WEATHER).getJSONObject(0).getString(TAG_WEATHER_DESCRIPTION);
		} catch (JSONException exception) {
			exception.printStackTrace();
		}
		return weatherDescription;
	}

	private int parseHumidity(JSONObject dailyForecast) {
		int humidity = 0;
		try {
			humidity = dailyForecast.getInt(TAG_HUMIDITY);
		} catch (JSONException exception) {
			exception.printStackTrace();
		}
		return humidity;
	}

	private long parseDateTime(JSONObject dailyForecast) {
		long dateTime = 0;
		try {
			dateTime = dailyForecast.getLong(TAG_DATE_TIME);
		} catch (JSONException exception) {
			exception.printStackTrace();
		}
		return dateTime;
	}

}

Add an async task to parse the json.


package ua.qa.training.sandbox;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by osoboleva on 9/18/2016.
 */
public class SquareTests {

  @Test
  public void testArea() {
    Square s = new Square(5);
    Assert.assertEquals(s.area(), 25.0);
  }
}

Add test for Square (from the video)


package org.bitrepository.monitoringservice;

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

import org.bitrepository.common.settings.Settings;
import org.bitrepository.protocol.messagebus.MessageSender;

/**
 * Class for the monitoring service keep a watch on non responding components, and send alarms if needed.
 */
public class MonitoringServiceAlerter {

	private final MessageSender messageSender;
	private final Settings settings;
	private final BigInteger maxRetries;
	private final Map<String, Integer> expectedContributors;

	public MonitoringServiceAlerter(Settings settings, MessageSender messageSender) {
		this.settings = settings;
		this.messageSender = messageSender;
		expectedContributors = new HashMap<String, Integer>(
				settings.getCollectionSettings().getGetStatusSettings().getContributorIDs().size());
		for(String ID : settings.getCollectionSettings().getGetStatusSettings().getContributorIDs()) {
			expectedContributors.put(ID, 0);
		}
		maxRetries = settings.getReferenceSettings().getMonitoringServiceSettings().getMaxRetries();
	}

	/**
	 *  Method to reload counters when status is requested.
	 */
	public void reload() {
		for(String ID : expectedContributors.keySet()) {
			Integer i = expectedContributors.get(ID);
			i++;
			expectedContributors.put(ID, i);
		}
	}

	/**
	 * A component has responded, reset it's not responding count.
	 */
	public void checkInComponent(String componentID) {
		if(!expectedContributors.containsKey(componentID)) {
			//log unexpected contributor
			return ;
		} else {
			expectedContributors.put(componentID, 0);
		}
	}

	/**
	 * Check for components that have not responded withing the given constraints, and send alarm
	 * message if there is any.
	 */
	public void checkNonRespondingAndSendAlarm() {
		List<String> nonRespondingComponents = new ArrayList<String>();
		for(String ID : expectedContributors.keySet()) {
			if(expectedContributors.get(ID) == maxRetries.intValue()) {
				nonRespondingComponents.add(ID);
			}
		}
		if(!nonRespondingComponents.isEmpty()) {
			sendAlarm(nonRespondingComponents);
		}
	}

	private void sendAlarm(List<String> components) {
		//Erhm, send alarm...
	}

}

Add begining of alarm sending in monitoring service


package cz.eeg.data;

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

import org.junit.Test;

public class MarkerTest  {

	Marker mk=new Marker("Mk6=Stimulus,S  6,19469,0,0");

	@Test
	public void testGetMarkerNumber() {
		assertEquals(6,mk.getMarkerNumber());
	}

	@Test
	public void testGetType() {
		assertEquals("Stimulus",mk.getType());
	}

	@Test
	public void testGetDescription() {
		assertEquals("S  6",mk.getDescription());
	}

	@Test
	public void testGetPositionInDataPoints() {
		assertEquals("19469",mk.getPositionInDataPoints());
	}

	@Test
	public void testGetSizeInDataPoints() {
		assertEquals("0",mk.getSizeInDataPoints());
	}

	@Test
	public void testGetChannelNumber() {
		assertEquals("0",mk.getChannelNumber());
	}

}

TEst pro marker třídu pokrývá 50%